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>
36 #include <dbus/dbus.h>
42 #include "utmp-wtmp.h"
46 #include "dbus-common.h"
47 #include "cgroup-show.h"
48 #include "cgroup-util.h"
50 #include "path-lookup.h"
51 #include "conf-parser.h"
52 #include "sd-daemon.h"
53 #include "shutdownd.h"
54 #include "exit-status.h"
55 #include "bus-errors.h"
57 #include "unit-name.h"
59 static const char *arg_type = NULL;
60 static char **arg_property = NULL;
61 static bool arg_all = false;
62 static bool arg_fail = false;
63 static bool arg_session = false;
64 static bool arg_global = false;
65 static bool arg_immediate = false;
66 static bool arg_no_block = false;
67 static bool arg_no_wtmp = false;
68 static bool arg_no_sync = false;
69 static bool arg_no_wall = false;
70 static bool arg_no_reload = false;
71 static bool arg_dry = false;
72 static bool arg_quiet = false;
73 static bool arg_full = false;
74 static bool arg_force = false;
75 static bool arg_defaults = false;
76 static char **arg_wall = NULL;
77 static usec_t arg_when = 0;
94 ACTION_CANCEL_SHUTDOWN,
96 } arg_action = ACTION_SYSTEMCTL;
103 static bool private_bus = false;
105 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
107 static bool on_tty(void) {
110 if (_unlikely_(t < 0))
111 t = isatty(STDOUT_FILENO) > 0;
116 static const char *ansi_highlight(bool b) {
121 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
124 static const char *ansi_highlight_green(bool b) {
129 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
132 static bool error_is_no_service(const DBusError *error) {
135 if (!dbus_error_is_set(error))
138 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
141 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
144 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
147 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
150 if (!dbus_error_is_set(error))
153 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
154 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
155 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
156 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
157 return EXIT_NOPERMISSION;
159 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
160 return EXIT_NOTINSTALLED;
162 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
163 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
164 return EXIT_NOTIMPLEMENTED;
166 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
167 return EXIT_NOTCONFIGURED;
175 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
180 if (dbus_message_iter_get_arg_type(iter) != type)
183 dbus_message_iter_get_basic(iter, data);
185 if (!dbus_message_iter_next(iter) != !next)
191 static void warn_wall(enum action action) {
192 static const char *table[_ACTION_MAX] = {
193 [ACTION_HALT] = "The system is going down for system halt NOW!",
194 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
195 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
196 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
197 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
206 if (!(p = strv_join(arg_wall, " "))) {
207 log_error("Failed to join strings.");
223 utmp_wall(table[action]);
228 const char *description;
229 const char *load_state;
230 const char *active_state;
231 const char *sub_state;
232 const char *following;
233 const char *unit_path;
235 const char *job_type;
236 const char *job_path;
239 static int compare_unit_info(const void *a, const void *b) {
241 const struct unit_info *u = a, *v = b;
243 d1 = strrchr(u->id, '.');
244 d2 = strrchr(v->id, '.');
249 if ((r = strcasecmp(d1, d2)) != 0)
253 return strcasecmp(u->id, v->id);
256 static bool output_show_job(const struct unit_info *u) {
259 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
260 streq(dot+1, arg_type))) &&
261 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0);
264 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
265 unsigned active_len, sub_len, job_len;
266 const struct unit_info *u;
268 active_len = sizeof("ACTIVE")-1;
269 sub_len = sizeof("SUB")-1;
270 job_len = sizeof("JOB")-1;
272 for (u = unit_infos; u < unit_infos + c; u++) {
273 if (!output_show_job(u))
276 active_len = MAX(active_len, strlen(u->active_state));
277 sub_len = MAX(sub_len, strlen(u->sub_state));
279 job_len = MAX(job_len, strlen(u->job_type));
283 printf("%-25s %-6s %-*s %-*s %-*s", "UNIT", "LOAD",
284 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
285 if (columns() >= 80+12 || arg_full)
286 printf(" %s\n", "DESCRIPTION");
291 for (u = unit_infos; u < unit_infos + c; u++) {
294 const char *on_loaded, *off_loaded;
295 const char *on_active, *off_active;
297 if (!output_show_job(u))
300 if (!streq(u->load_state, "loaded")) {
301 on_loaded = ansi_highlight(true);
302 off_loaded = ansi_highlight(false);
304 on_loaded = off_loaded = "";
306 if (streq(u->active_state, "failed")) {
307 on_active = ansi_highlight(true);
308 off_active = ansi_highlight(false);
310 on_active = off_active = "";
312 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
314 printf("%-25s %s%-6s%s %s%-*s %-*s%s%n",
316 on_loaded, u->load_state, off_loaded,
317 on_active, active_len, u->active_state,
318 sub_len, u->sub_state, off_active,
323 a -= strlen(on_loaded) + strlen(off_loaded);
324 a -= strlen(on_active) + strlen(off_active);
327 printf(" %-*s", job_len, u->job_type);
331 if (a + b + 1 < columns()) {
333 printf(" %-*s", job_len, "");
336 printf(" %s", u->description);
338 printf(" %.*s", columns() - a - b - 1, u->description);
345 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
346 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
347 "SUB = The low-level unit activation state, values depend on unit type.\n"
348 "JOB = Pending job for the unit.\n");
351 printf("\n%u units listed.\n", c);
353 printf("\n%u units listed. Pass --all to see inactive units, too.\n", c);
357 static int list_units(DBusConnection *bus, char **args, unsigned n) {
358 DBusMessage *m = NULL, *reply = NULL;
361 DBusMessageIter iter, sub, sub2;
362 unsigned c = 0, n_units = 0;
363 struct unit_info *unit_infos = NULL;
365 dbus_error_init(&error);
369 if (!(m = dbus_message_new_method_call(
370 "org.freedesktop.systemd1",
371 "/org/freedesktop/systemd1",
372 "org.freedesktop.systemd1.Manager",
374 log_error("Could not allocate message.");
378 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
379 log_error("Failed to issue method call: %s", bus_error_message(&error));
384 if (!dbus_message_iter_init(reply, &iter) ||
385 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
386 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
387 log_error("Failed to parse reply.");
392 dbus_message_iter_recurse(&iter, &sub);
394 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
397 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
398 log_error("Failed to parse reply.");
406 n_units = MAX(2*c, 16);
407 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
410 log_error("Failed to allocate unit array.");
420 dbus_message_iter_recurse(&sub, &sub2);
422 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
423 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
424 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
425 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
426 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
427 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
428 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
429 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
430 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
431 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
432 log_error("Failed to parse reply.");
437 dbus_message_iter_next(&sub);
441 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
442 output_units_list(unit_infos, c);
448 dbus_message_unref(m);
451 dbus_message_unref(reply);
455 dbus_error_free(&error);
460 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
461 static const char * const colors[] = {
462 "Requires", "[color=\"black\"]",
463 "RequiresOverridable", "[color=\"black\"]",
464 "Requisite", "[color=\"darkblue\"]",
465 "RequisiteOverridable", "[color=\"darkblue\"]",
466 "Wants", "[color=\"darkgrey\"]",
467 "Conflicts", "[color=\"red\"]",
468 "ConflictedBy", "[color=\"red\"]",
469 "After", "[color=\"green\"]"
472 const char *c = NULL;
479 for (i = 0; i < ELEMENTSOF(colors); i += 2)
480 if (streq(colors[i], prop)) {
488 if (arg_dot != DOT_ALL)
489 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
492 switch (dbus_message_iter_get_arg_type(iter)) {
494 case DBUS_TYPE_ARRAY:
496 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
499 dbus_message_iter_recurse(iter, &sub);
501 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
504 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
505 dbus_message_iter_get_basic(&sub, &s);
506 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
508 dbus_message_iter_next(&sub);
518 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
519 DBusMessage *m = NULL, *reply = NULL;
520 const char *interface = "org.freedesktop.systemd1.Unit";
523 DBusMessageIter iter, sub, sub2, sub3;
528 dbus_error_init(&error);
530 if (!(m = dbus_message_new_method_call(
531 "org.freedesktop.systemd1",
533 "org.freedesktop.DBus.Properties",
535 log_error("Could not allocate message.");
540 if (!dbus_message_append_args(m,
541 DBUS_TYPE_STRING, &interface,
542 DBUS_TYPE_INVALID)) {
543 log_error("Could not append arguments to message.");
548 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
549 log_error("Failed to issue method call: %s", bus_error_message(&error));
554 if (!dbus_message_iter_init(reply, &iter) ||
555 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
556 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
557 log_error("Failed to parse reply.");
562 dbus_message_iter_recurse(&iter, &sub);
564 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
567 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
568 log_error("Failed to parse reply.");
573 dbus_message_iter_recurse(&sub, &sub2);
575 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
576 log_error("Failed to parse reply.");
581 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
582 log_error("Failed to parse reply.");
587 dbus_message_iter_recurse(&sub2, &sub3);
589 if (dot_one_property(name, prop, &sub3)) {
590 log_error("Failed to parse reply.");
595 dbus_message_iter_next(&sub);
602 dbus_message_unref(m);
605 dbus_message_unref(reply);
607 dbus_error_free(&error);
612 static int dot(DBusConnection *bus, char **args, unsigned n) {
613 DBusMessage *m = NULL, *reply = NULL;
616 DBusMessageIter iter, sub, sub2;
618 dbus_error_init(&error);
622 if (!(m = dbus_message_new_method_call(
623 "org.freedesktop.systemd1",
624 "/org/freedesktop/systemd1",
625 "org.freedesktop.systemd1.Manager",
627 log_error("Could not allocate message.");
631 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
632 log_error("Failed to issue method call: %s", bus_error_message(&error));
637 if (!dbus_message_iter_init(reply, &iter) ||
638 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
639 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
640 log_error("Failed to parse reply.");
645 printf("digraph systemd {\n");
647 dbus_message_iter_recurse(&iter, &sub);
648 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
649 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
651 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
652 log_error("Failed to parse reply.");
657 dbus_message_iter_recurse(&sub, &sub2);
659 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
660 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
661 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
662 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
663 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
664 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
665 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
666 log_error("Failed to parse reply.");
671 if ((r = dot_one(bus, id, unit_path)) < 0)
674 /* printf("\t\"%s\";\n", id); */
675 dbus_message_iter_next(&sub);
680 log_info(" Color legend: black = Requires\n"
681 " dark blue = Requisite\n"
682 " dark grey = Wants\n"
686 if (isatty(fileno(stdout)))
687 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
688 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
694 dbus_message_unref(m);
697 dbus_message_unref(reply);
699 dbus_error_free(&error);
704 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
705 DBusMessage *m = NULL, *reply = NULL;
708 DBusMessageIter iter, sub, sub2;
711 dbus_error_init(&error);
715 if (!(m = dbus_message_new_method_call(
716 "org.freedesktop.systemd1",
717 "/org/freedesktop/systemd1",
718 "org.freedesktop.systemd1.Manager",
720 log_error("Could not allocate message.");
724 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
725 log_error("Failed to issue method call: %s", bus_error_message(&error));
730 if (!dbus_message_iter_init(reply, &iter) ||
731 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
732 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
733 log_error("Failed to parse reply.");
738 dbus_message_iter_recurse(&iter, &sub);
740 if (isatty(STDOUT_FILENO))
741 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
743 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
744 const char *name, *type, *state, *job_path, *unit_path;
748 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
749 log_error("Failed to parse reply.");
754 dbus_message_iter_recurse(&sub, &sub2);
756 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
757 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
758 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
759 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
760 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
761 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
762 log_error("Failed to parse reply.");
767 e = arg_full ? NULL : ellipsize(name, 25, 33);
768 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
773 dbus_message_iter_next(&sub);
776 if (isatty(STDOUT_FILENO))
777 printf("\n%u jobs listed.\n", k);
783 dbus_message_unref(m);
786 dbus_message_unref(reply);
788 dbus_error_free(&error);
793 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
794 DBusMessage *m = NULL, *reply = NULL;
799 dbus_error_init(&error);
804 for (i = 1; i < n; i++) {
806 if (!(m = dbus_message_new_method_call(
807 "org.freedesktop.systemd1",
808 "/org/freedesktop/systemd1",
809 "org.freedesktop.systemd1.Manager",
811 log_error("Could not allocate message.");
816 if (!dbus_message_append_args(m,
817 DBUS_TYPE_STRING, &args[i],
818 DBUS_TYPE_INVALID)) {
819 log_error("Could not append arguments to message.");
824 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
825 log_error("Failed to issue method call: %s", bus_error_message(&error));
830 dbus_message_unref(m);
831 dbus_message_unref(reply);
840 dbus_message_unref(m);
843 dbus_message_unref(reply);
845 dbus_error_free(&error);
850 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
851 DBusMessage *m = NULL, *reply = NULL;
856 dbus_error_init(&error);
862 return daemon_reload(bus, args, n);
864 for (i = 1; i < n; i++) {
868 if (!(m = dbus_message_new_method_call(
869 "org.freedesktop.systemd1",
870 "/org/freedesktop/systemd1",
871 "org.freedesktop.systemd1.Manager",
873 log_error("Could not allocate message.");
878 if ((r = safe_atou(args[i], &id)) < 0) {
879 log_error("Failed to parse job id: %s", strerror(-r));
883 assert_cc(sizeof(uint32_t) == sizeof(id));
884 if (!dbus_message_append_args(m,
885 DBUS_TYPE_UINT32, &id,
886 DBUS_TYPE_INVALID)) {
887 log_error("Could not append arguments to message.");
892 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
893 log_error("Failed to issue method call: %s", bus_error_message(&error));
898 if (!dbus_message_get_args(reply, &error,
899 DBUS_TYPE_OBJECT_PATH, &path,
900 DBUS_TYPE_INVALID)) {
901 log_error("Failed to parse reply: %s", bus_error_message(&error));
906 dbus_message_unref(m);
907 if (!(m = dbus_message_new_method_call(
908 "org.freedesktop.systemd1",
910 "org.freedesktop.systemd1.Job",
912 log_error("Could not allocate message.");
917 dbus_message_unref(reply);
918 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
919 log_error("Failed to issue method call: %s", bus_error_message(&error));
924 dbus_message_unref(m);
925 dbus_message_unref(reply);
933 dbus_message_unref(m);
936 dbus_message_unref(reply);
938 dbus_error_free(&error);
943 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
944 DBusMessage *m = NULL, *reply = NULL;
945 dbus_bool_t b = FALSE;
946 DBusMessageIter iter, sub;
948 *interface = "org.freedesktop.systemd1.Unit",
949 *property = "NeedDaemonReload",
952 /* We ignore all errors here, since this is used to show a warning only */
954 if (!(m = dbus_message_new_method_call(
955 "org.freedesktop.systemd1",
956 "/org/freedesktop/systemd1",
957 "org.freedesktop.systemd1.Manager",
961 if (!dbus_message_append_args(m,
962 DBUS_TYPE_STRING, &unit,
966 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
969 if (!dbus_message_get_args(reply, NULL,
970 DBUS_TYPE_OBJECT_PATH, &path,
974 dbus_message_unref(m);
975 if (!(m = dbus_message_new_method_call(
976 "org.freedesktop.systemd1",
978 "org.freedesktop.DBus.Properties",
982 if (!dbus_message_append_args(m,
983 DBUS_TYPE_STRING, &interface,
984 DBUS_TYPE_STRING, &property,
985 DBUS_TYPE_INVALID)) {
989 dbus_message_unref(reply);
990 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
993 if (!dbus_message_iter_init(reply, &iter) ||
994 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
997 dbus_message_iter_recurse(&iter, &sub);
999 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1002 dbus_message_iter_get_basic(&sub, &b);
1006 dbus_message_unref(m);
1009 dbus_message_unref(reply);
1014 typedef struct WaitData {
1019 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1027 dbus_error_init(&error);
1029 log_debug("Got D-Bus request: %s.%s() on %s",
1030 dbus_message_get_interface(message),
1031 dbus_message_get_member(message),
1032 dbus_message_get_path(message));
1034 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1035 log_error("Warning! D-Bus connection terminated.");
1036 dbus_connection_close(connection);
1038 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1041 dbus_bool_t success = true;
1043 if (!dbus_message_get_args(message, &error,
1044 DBUS_TYPE_UINT32, &id,
1045 DBUS_TYPE_OBJECT_PATH, &path,
1046 DBUS_TYPE_BOOLEAN, &success,
1048 log_error("Failed to parse message: %s", bus_error_message(&error));
1052 if ((p = set_remove(d->set, (char*) path)))
1060 dbus_error_free(&error);
1061 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1064 static int enable_wait_for_jobs(DBusConnection *bus) {
1072 dbus_error_init(&error);
1073 dbus_bus_add_match(bus,
1075 "sender='org.freedesktop.systemd1',"
1076 "interface='org.freedesktop.systemd1.Manager',"
1077 "member='JobRemoved',"
1078 "path='/org/freedesktop/systemd1'",
1081 if (dbus_error_is_set(&error)) {
1082 log_error("Failed to add match: %s", bus_error_message(&error));
1083 dbus_error_free(&error);
1087 /* This is slightly dirty, since we don't undo the match registrations. */
1091 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1102 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1103 log_error("Failed to add filter.");
1108 while (!set_isempty(s) &&
1109 dbus_connection_read_write_dispatch(bus, -1))
1112 if (!arg_quiet && d.failed)
1113 log_error("Job failed, see system logs for details.");
1115 r = d.failed ? -EIO : 0;
1118 /* This is slightly dirty, since we don't undo the filter registration. */
1123 static int start_unit_one(
1124 DBusConnection *bus,
1131 DBusMessage *m = NULL, *reply = NULL;
1140 assert(arg_no_block || s);
1142 if (!(m = dbus_message_new_method_call(
1143 "org.freedesktop.systemd1",
1144 "/org/freedesktop/systemd1",
1145 "org.freedesktop.systemd1.Manager",
1147 log_error("Could not allocate message.");
1152 if (!dbus_message_append_args(m,
1153 DBUS_TYPE_STRING, &name,
1154 DBUS_TYPE_STRING, &mode,
1155 DBUS_TYPE_INVALID)) {
1156 log_error("Could not append arguments to message.");
1161 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1163 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1164 /* There's always a fallback possible for
1165 * legacy actions. */
1170 log_error("Failed to issue method call: %s", bus_error_message(error));
1175 if (!dbus_message_get_args(reply, error,
1176 DBUS_TYPE_OBJECT_PATH, &path,
1177 DBUS_TYPE_INVALID)) {
1178 log_error("Failed to parse reply: %s", bus_error_message(error));
1183 if (need_daemon_reload(bus, name))
1184 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1185 arg_session ? "--session" : "--system");
1187 if (!arg_no_block) {
1190 if (!(p = strdup(path))) {
1191 log_error("Failed to duplicate path.");
1196 if ((r = set_put(s, p)) < 0) {
1198 log_error("Failed to add path to set.");
1207 dbus_message_unref(m);
1210 dbus_message_unref(reply);
1215 static enum action verb_to_action(const char *verb) {
1216 if (streq(verb, "halt"))
1218 else if (streq(verb, "poweroff"))
1219 return ACTION_POWEROFF;
1220 else if (streq(verb, "reboot"))
1221 return ACTION_REBOOT;
1222 else if (streq(verb, "rescue"))
1223 return ACTION_RESCUE;
1224 else if (streq(verb, "emergency"))
1225 return ACTION_EMERGENCY;
1226 else if (streq(verb, "default"))
1227 return ACTION_DEFAULT;
1229 return ACTION_INVALID;
1232 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1234 static const char * const table[_ACTION_MAX] = {
1235 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1236 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1237 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1238 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1239 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1240 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1241 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1242 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1243 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1244 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET
1249 const char *method, *mode, *one_name;
1253 dbus_error_init(&error);
1257 if (arg_action == ACTION_SYSTEMCTL) {
1259 streq(args[0], "stop") ? "StopUnit" :
1260 streq(args[0], "reload") ? "ReloadUnit" :
1261 streq(args[0], "restart") ? "RestartUnit" :
1262 streq(args[0], "try-restart") ||
1263 streq(args[0], "condrestart") ? "TryRestartUnit" :
1264 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1265 streq(args[0], "reload-or-try-restart") ||
1266 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1270 (streq(args[0], "isolate") ||
1271 streq(args[0], "rescue") ||
1272 streq(args[0], "emergency")) ? "isolate" :
1276 one_name = table[verb_to_action(args[0])];
1279 assert(arg_action < ELEMENTSOF(table));
1280 assert(table[arg_action]);
1282 method = "StartUnit";
1284 mode = (arg_action == ACTION_EMERGENCY ||
1285 arg_action == ACTION_RESCUE ||
1286 arg_action == ACTION_RUNLEVEL2 ||
1287 arg_action == ACTION_RUNLEVEL3 ||
1288 arg_action == ACTION_RUNLEVEL4 ||
1289 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1291 one_name = table[arg_action];
1294 if (!arg_no_block) {
1295 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1296 log_error("Could not watch jobs: %s", strerror(-ret));
1300 if (!(s = set_new(string_hash_func, string_compare_func))) {
1301 log_error("Failed to allocate set.");
1308 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1311 for (i = 1; i < n; i++)
1312 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1313 ret = translate_bus_error_to_exit_status(r, &error);
1314 dbus_error_free(&error);
1319 if ((r = wait_for_jobs(bus, s)) < 0) {
1328 dbus_error_free(&error);
1333 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1339 r = start_unit(bus, args, n);
1342 warn_wall(verb_to_action(args[0]));
1347 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1348 DBusMessage *m = NULL, *reply = NULL;
1350 *interface = "org.freedesktop.systemd1.Unit",
1351 *property = "ActiveState";
1352 int r = 3; /* According to LSB: "program is not running" */
1359 dbus_error_init(&error);
1361 for (i = 1; i < n; i++) {
1362 const char *path = NULL;
1364 DBusMessageIter iter, sub;
1366 if (!(m = dbus_message_new_method_call(
1367 "org.freedesktop.systemd1",
1368 "/org/freedesktop/systemd1",
1369 "org.freedesktop.systemd1.Manager",
1371 log_error("Could not allocate message.");
1376 if (!dbus_message_append_args(m,
1377 DBUS_TYPE_STRING, &args[i],
1378 DBUS_TYPE_INVALID)) {
1379 log_error("Could not append arguments to message.");
1384 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1386 /* Hmm, cannot figure out anything about this unit... */
1390 dbus_error_free(&error);
1394 if (!dbus_message_get_args(reply, &error,
1395 DBUS_TYPE_OBJECT_PATH, &path,
1396 DBUS_TYPE_INVALID)) {
1397 log_error("Failed to parse reply: %s", bus_error_message(&error));
1402 dbus_message_unref(m);
1403 if (!(m = dbus_message_new_method_call(
1404 "org.freedesktop.systemd1",
1406 "org.freedesktop.DBus.Properties",
1408 log_error("Could not allocate message.");
1413 if (!dbus_message_append_args(m,
1414 DBUS_TYPE_STRING, &interface,
1415 DBUS_TYPE_STRING, &property,
1416 DBUS_TYPE_INVALID)) {
1417 log_error("Could not append arguments to message.");
1422 dbus_message_unref(reply);
1423 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1424 log_error("Failed to issue method call: %s", bus_error_message(&error));
1429 if (!dbus_message_iter_init(reply, &iter) ||
1430 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1431 log_error("Failed to parse reply.");
1436 dbus_message_iter_recurse(&iter, &sub);
1438 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1439 log_error("Failed to parse reply.");
1444 dbus_message_iter_get_basic(&sub, &state);
1449 if (streq(state, "active") || streq(state, "reloading"))
1452 dbus_message_unref(m);
1453 dbus_message_unref(reply);
1459 dbus_message_unref(m);
1462 dbus_message_unref(reply);
1464 dbus_error_free(&error);
1469 typedef struct ExecStatusInfo {
1475 usec_t start_timestamp;
1476 usec_t exit_timestamp;
1481 LIST_FIELDS(struct ExecStatusInfo, exec);
1484 static void exec_status_info_free(ExecStatusInfo *i) {
1492 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1493 uint64_t start_timestamp, exit_timestamp;
1494 DBusMessageIter sub2, sub3;
1498 int32_t code, status;
1504 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1507 dbus_message_iter_recurse(sub, &sub2);
1509 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1512 if (!(i->path = strdup(path)))
1515 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1516 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1520 dbus_message_iter_recurse(&sub2, &sub3);
1521 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1522 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1523 dbus_message_iter_next(&sub3);
1528 if (!(i->argv = new0(char*, n+1)))
1532 dbus_message_iter_recurse(&sub2, &sub3);
1533 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1536 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1537 dbus_message_iter_get_basic(&sub3, &s);
1538 dbus_message_iter_next(&sub3);
1540 if (!(i->argv[n++] = strdup(s)))
1544 if (!dbus_message_iter_next(&sub2) ||
1545 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1546 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1547 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1548 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1549 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1550 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1554 i->start_timestamp = (usec_t) start_timestamp;
1555 i->exit_timestamp = (usec_t) exit_timestamp;
1556 i->pid = (pid_t) pid;
1563 typedef struct UnitStatusInfo {
1565 const char *load_state;
1566 const char *active_state;
1567 const char *sub_state;
1569 const char *description;
1572 const char *default_control_group;
1574 usec_t inactive_exit_timestamp;
1575 usec_t active_enter_timestamp;
1576 usec_t active_exit_timestamp;
1577 usec_t inactive_enter_timestamp;
1579 bool need_daemon_reload;
1584 const char *status_text;
1586 #ifdef HAVE_SYSV_COMPAT
1590 usec_t start_timestamp;
1591 usec_t exit_timestamp;
1593 int exit_code, exit_status;
1596 unsigned n_accepted;
1597 unsigned n_connections;
1601 const char *sysfs_path;
1603 /* Mount, Automount */
1609 LIST_HEAD(ExecStatusInfo, exec);
1612 static void print_status_info(UnitStatusInfo *i) {
1614 const char *on, *off, *ss;
1616 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1617 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1621 /* This shows pretty information about a unit. See
1622 * print_property() for a low-level property printer */
1624 printf("%s", strna(i->id));
1626 if (i->description && !streq_ptr(i->id, i->description))
1627 printf(" - %s", i->description);
1631 if (streq_ptr(i->load_state, "failed")) {
1632 on = ansi_highlight(true);
1633 off = ansi_highlight(false);
1638 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1640 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1642 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1644 if (streq_ptr(i->active_state, "failed")) {
1645 on = ansi_highlight(true);
1646 off = ansi_highlight(false);
1647 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1648 on = ansi_highlight_green(true);
1649 off = ansi_highlight_green(false);
1654 printf("\t Active: %s%s (%s)%s",
1656 strna(i->active_state),
1660 printf("\t Active: %s%s%s",
1662 strna(i->active_state),
1665 timestamp = (streq_ptr(i->active_state, "active") ||
1666 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1667 (streq_ptr(i->active_state, "inactive") ||
1668 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1669 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1670 i->active_exit_timestamp;
1672 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1673 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1676 printf(" since [%s; %s]\n", s2, s1);
1678 printf(" since [%s]\n", s2);
1683 printf("\t Device: %s\n", i->sysfs_path);
1685 printf("\t Where: %s\n", i->where);
1687 printf("\t What: %s\n", i->what);
1690 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1692 LIST_FOREACH(exec, p, i->exec) {
1695 /* Only show exited processes here */
1699 t = strv_join(p->argv, " ");
1700 printf("\t Process: %u (%s, code=%s, ", p->pid, strna(t), sigchld_code_to_string(p->code));
1703 if (p->code == CLD_EXITED) {
1706 printf("status=%i", p->status);
1708 #ifdef HAVE_SYSV_COMPAT
1709 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1711 if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1716 printf("signal=%s", signal_to_string(p->status));
1719 if (i->main_pid == p->pid &&
1720 i->start_timestamp == p->start_timestamp &&
1721 i->exit_timestamp == p->start_timestamp)
1722 /* Let's not show this twice */
1725 if (p->pid == i->control_pid)
1729 if (i->main_pid > 0 || i->control_pid > 0) {
1732 if (i->main_pid > 0) {
1733 printf("Main PID: %u", (unsigned) i->main_pid);
1737 get_process_name(i->main_pid, &t);
1742 } else if (i->exit_code > 0) {
1743 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1745 if (i->exit_code == CLD_EXITED) {
1748 printf("status=%i", i->exit_status);
1750 #ifdef HAVE_SYSV_COMPAT
1751 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1753 if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
1758 printf("signal=%s", signal_to_string(i->exit_status));
1763 if (i->main_pid > 0 && i->control_pid > 0)
1766 if (i->control_pid > 0) {
1769 printf(" Control: %u", (unsigned) i->control_pid);
1771 get_process_name(i->control_pid, &t);
1782 printf("\t Status: \"%s\"\n", i->status_text);
1784 if (i->default_control_group) {
1787 printf("\t CGroup: %s\n", i->default_control_group);
1789 if ((c = columns()) > 18)
1794 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
1797 if (i->need_daemon_reload)
1798 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1799 ansi_highlight(true),
1800 ansi_highlight(false),
1801 arg_session ? "--session" : "--system");
1804 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1806 switch (dbus_message_iter_get_arg_type(iter)) {
1808 case DBUS_TYPE_STRING: {
1811 dbus_message_iter_get_basic(iter, &s);
1814 if (streq(name, "Id"))
1816 else if (streq(name, "LoadState"))
1818 else if (streq(name, "ActiveState"))
1819 i->active_state = s;
1820 else if (streq(name, "SubState"))
1822 else if (streq(name, "Description"))
1824 else if (streq(name, "FragmentPath"))
1826 #ifdef HAVE_SYSV_COMPAT
1827 else if (streq(name, "SysVPath")) {
1832 else if (streq(name, "DefaultControlGroup"))
1833 i->default_control_group = s;
1834 else if (streq(name, "StatusText"))
1836 else if (streq(name, "SysFSPath"))
1838 else if (streq(name, "Where"))
1840 else if (streq(name, "What"))
1847 case DBUS_TYPE_BOOLEAN: {
1850 dbus_message_iter_get_basic(iter, &b);
1852 if (streq(name, "Accept"))
1854 else if (streq(name, "NeedDaemonReload"))
1855 i->need_daemon_reload = b;
1860 case DBUS_TYPE_UINT32: {
1863 dbus_message_iter_get_basic(iter, &u);
1865 if (streq(name, "MainPID")) {
1867 i->main_pid = (pid_t) u;
1870 } else if (streq(name, "ControlPID"))
1871 i->control_pid = (pid_t) u;
1872 else if (streq(name, "ExecMainPID")) {
1874 i->main_pid = (pid_t) u;
1875 } else if (streq(name, "NAccepted"))
1877 else if (streq(name, "NConnections"))
1878 i->n_connections = u;
1883 case DBUS_TYPE_INT32: {
1886 dbus_message_iter_get_basic(iter, &j);
1888 if (streq(name, "ExecMainCode"))
1889 i->exit_code = (int) j;
1890 else if (streq(name, "ExecMainStatus"))
1891 i->exit_status = (int) j;
1896 case DBUS_TYPE_UINT64: {
1899 dbus_message_iter_get_basic(iter, &u);
1901 if (streq(name, "ExecMainStartTimestamp"))
1902 i->start_timestamp = (usec_t) u;
1903 else if (streq(name, "ExecMainExitTimestamp"))
1904 i->exit_timestamp = (usec_t) u;
1905 else if (streq(name, "ActiveEnterTimestamp"))
1906 i->active_enter_timestamp = (usec_t) u;
1907 else if (streq(name, "InactiveEnterTimestamp"))
1908 i->inactive_enter_timestamp = (usec_t) u;
1909 else if (streq(name, "InactiveExitTimestamp"))
1910 i->inactive_exit_timestamp = (usec_t) u;
1911 else if (streq(name, "ActiveExitTimestamp"))
1912 i->active_exit_timestamp = (usec_t) u;
1917 case DBUS_TYPE_ARRAY: {
1919 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
1920 startswith(name, "Exec")) {
1921 DBusMessageIter sub;
1923 dbus_message_iter_recurse(iter, &sub);
1924 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1925 ExecStatusInfo *info;
1928 if (!(info = new0(ExecStatusInfo, 1)))
1931 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
1936 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
1938 dbus_message_iter_next(&sub);
1949 static int print_property(const char *name, DBusMessageIter *iter) {
1953 /* This is a low-level property printer, see
1954 * print_status_info() for the nicer output */
1956 if (arg_property && !strv_find(arg_property, name))
1959 switch (dbus_message_iter_get_arg_type(iter)) {
1961 case DBUS_TYPE_STRING: {
1963 dbus_message_iter_get_basic(iter, &s);
1965 if (arg_all || s[0])
1966 printf("%s=%s\n", name, s);
1971 case DBUS_TYPE_BOOLEAN: {
1973 dbus_message_iter_get_basic(iter, &b);
1974 printf("%s=%s\n", name, yes_no(b));
1979 case DBUS_TYPE_UINT64: {
1981 dbus_message_iter_get_basic(iter, &u);
1983 /* Yes, heuristics! But we can change this check
1984 * should it turn out to not be sufficient */
1986 if (strstr(name, "Timestamp")) {
1987 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
1989 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
1990 printf("%s=%s\n", name, strempty(t));
1991 } else if (strstr(name, "USec")) {
1992 char timespan[FORMAT_TIMESPAN_MAX];
1994 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
1996 printf("%s=%llu\n", name, (unsigned long long) u);
2001 case DBUS_TYPE_UINT32: {
2003 dbus_message_iter_get_basic(iter, &u);
2005 if (strstr(name, "UMask") || strstr(name, "Mode"))
2006 printf("%s=%04o\n", name, u);
2008 printf("%s=%u\n", name, (unsigned) u);
2013 case DBUS_TYPE_INT32: {
2015 dbus_message_iter_get_basic(iter, &i);
2017 printf("%s=%i\n", name, (int) i);
2021 case DBUS_TYPE_DOUBLE: {
2023 dbus_message_iter_get_basic(iter, &d);
2025 printf("%s=%g\n", name, d);
2029 case DBUS_TYPE_STRUCT: {
2030 DBusMessageIter sub;
2031 dbus_message_iter_recurse(iter, &sub);
2033 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2036 dbus_message_iter_get_basic(&sub, &u);
2039 printf("%s=%u\n", name, (unsigned) u);
2041 printf("%s=\n", name);
2044 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2047 dbus_message_iter_get_basic(&sub, &s);
2049 if (arg_all || s[0])
2050 printf("%s=%s\n", name, s);
2058 case DBUS_TYPE_ARRAY:
2060 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2061 DBusMessageIter sub;
2064 dbus_message_iter_recurse(iter, &sub);
2066 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2067 printf("%s=", name);
2069 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2072 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2073 dbus_message_iter_get_basic(&sub, &s);
2074 printf("%s%s", space ? " " : "", s);
2077 dbus_message_iter_next(&sub);
2085 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2086 DBusMessageIter sub;
2088 dbus_message_iter_recurse(iter, &sub);
2090 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2091 printf("%s=", name);
2093 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2096 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2097 dbus_message_iter_get_basic(&sub, &u);
2100 dbus_message_iter_next(&sub);
2108 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2109 DBusMessageIter sub, sub2;
2111 dbus_message_iter_recurse(iter, &sub);
2112 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2113 const char *type, *path;
2115 dbus_message_iter_recurse(&sub, &sub2);
2117 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2118 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2119 printf("%s=%s\n", type, path);
2121 dbus_message_iter_next(&sub);
2126 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2127 DBusMessageIter sub, sub2;
2129 dbus_message_iter_recurse(iter, &sub);
2130 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2132 uint64_t value, next_elapse;
2134 dbus_message_iter_recurse(&sub, &sub2);
2136 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2137 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2138 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2139 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2141 printf("%s={ value=%s ; next_elapse=%s }\n",
2143 format_timespan(timespan1, sizeof(timespan1), value),
2144 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2147 dbus_message_iter_next(&sub);
2152 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2153 DBusMessageIter sub;
2155 dbus_message_iter_recurse(iter, &sub);
2156 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2157 ExecStatusInfo info;
2160 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2161 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2164 t = strv_join(info.argv, " ");
2166 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2170 yes_no(info.ignore),
2171 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2172 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2173 (unsigned) info. pid,
2174 sigchld_code_to_string(info.code),
2176 info.code == CLD_EXITED ? "" : "/",
2177 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2183 strv_free(info.argv);
2185 dbus_message_iter_next(&sub);
2195 printf("%s=[unprintable]\n", name);
2200 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2201 DBusMessage *m = NULL, *reply = NULL;
2202 const char *interface = "";
2205 DBusMessageIter iter, sub, sub2, sub3;
2206 UnitStatusInfo info;
2214 dbus_error_init(&error);
2216 if (!(m = dbus_message_new_method_call(
2217 "org.freedesktop.systemd1",
2219 "org.freedesktop.DBus.Properties",
2221 log_error("Could not allocate message.");
2226 if (!dbus_message_append_args(m,
2227 DBUS_TYPE_STRING, &interface,
2228 DBUS_TYPE_INVALID)) {
2229 log_error("Could not append arguments to message.");
2234 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2235 log_error("Failed to issue method call: %s", bus_error_message(&error));
2240 if (!dbus_message_iter_init(reply, &iter) ||
2241 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2242 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2243 log_error("Failed to parse reply.");
2248 dbus_message_iter_recurse(&iter, &sub);
2255 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2258 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2259 log_error("Failed to parse reply.");
2264 dbus_message_iter_recurse(&sub, &sub2);
2266 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2267 log_error("Failed to parse reply.");
2272 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2273 log_error("Failed to parse reply.");
2278 dbus_message_iter_recurse(&sub2, &sub3);
2280 if (show_properties)
2281 r = print_property(name, &sub3);
2283 r = status_property(name, &sub3, &info);
2286 log_error("Failed to parse reply.");
2291 dbus_message_iter_next(&sub);
2296 if (!show_properties)
2297 print_status_info(&info);
2299 if (!streq_ptr(info.active_state, "active") &&
2300 !streq_ptr(info.active_state, "reloading"))
2301 /* According to LSB: "program not running" */
2304 while ((p = info.exec)) {
2305 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2306 exec_status_info_free(p);
2311 dbus_message_unref(m);
2314 dbus_message_unref(reply);
2316 dbus_error_free(&error);
2321 static int show(DBusConnection *bus, char **args, unsigned n) {
2322 DBusMessage *m = NULL, *reply = NULL;
2326 bool show_properties, new_line = false;
2331 dbus_error_init(&error);
2333 show_properties = !streq(args[0], "status");
2335 if (show_properties && n <= 1) {
2336 /* If not argument is specified inspect the manager
2339 ret = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2343 for (i = 1; i < n; i++) {
2344 const char *path = NULL;
2347 if (safe_atou32(args[i], &id) < 0) {
2349 /* Interpret as unit name */
2351 if (!(m = dbus_message_new_method_call(
2352 "org.freedesktop.systemd1",
2353 "/org/freedesktop/systemd1",
2354 "org.freedesktop.systemd1.Manager",
2356 log_error("Could not allocate message.");
2361 if (!dbus_message_append_args(m,
2362 DBUS_TYPE_STRING, &args[i],
2363 DBUS_TYPE_INVALID)) {
2364 log_error("Could not append arguments to message.");
2369 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2371 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2372 log_error("Failed to issue method call: %s", bus_error_message(&error));
2377 dbus_error_free(&error);
2379 dbus_message_unref(m);
2380 if (!(m = dbus_message_new_method_call(
2381 "org.freedesktop.systemd1",
2382 "/org/freedesktop/systemd1",
2383 "org.freedesktop.systemd1.Manager",
2385 log_error("Could not allocate message.");
2390 if (!dbus_message_append_args(m,
2391 DBUS_TYPE_STRING, &args[i],
2392 DBUS_TYPE_INVALID)) {
2393 log_error("Could not append arguments to message.");
2398 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2399 log_error("Failed to issue method call: %s", bus_error_message(&error));
2401 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2402 ret = 4; /* According to LSB: "program or service status is unknown" */
2409 } else if (show_properties) {
2411 /* Interpret as job id */
2413 if (!(m = dbus_message_new_method_call(
2414 "org.freedesktop.systemd1",
2415 "/org/freedesktop/systemd1",
2416 "org.freedesktop.systemd1.Manager",
2418 log_error("Could not allocate message.");
2423 if (!dbus_message_append_args(m,
2424 DBUS_TYPE_UINT32, &id,
2425 DBUS_TYPE_INVALID)) {
2426 log_error("Could not append arguments to message.");
2431 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2432 log_error("Failed to issue method call: %s", bus_error_message(&error));
2438 /* Interpret as PID */
2440 if (!(m = dbus_message_new_method_call(
2441 "org.freedesktop.systemd1",
2442 "/org/freedesktop/systemd1",
2443 "org.freedesktop.systemd1.Manager",
2445 log_error("Could not allocate message.");
2450 if (!dbus_message_append_args(m,
2451 DBUS_TYPE_UINT32, &id,
2452 DBUS_TYPE_INVALID)) {
2453 log_error("Could not append arguments to message.");
2458 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2459 log_error("Failed to issue method call: %s", bus_error_message(&error));
2465 if (!dbus_message_get_args(reply, &error,
2466 DBUS_TYPE_OBJECT_PATH, &path,
2467 DBUS_TYPE_INVALID)) {
2468 log_error("Failed to parse reply: %s", bus_error_message(&error));
2473 if ((r = show_one(bus, path, show_properties, &new_line)) != 0)
2476 dbus_message_unref(m);
2477 dbus_message_unref(reply);
2483 dbus_message_unref(m);
2486 dbus_message_unref(reply);
2488 dbus_error_free(&error);
2493 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2495 DBusMessage *m = NULL, *reply = NULL;
2500 dbus_error_init(&error);
2502 log_debug("Got D-Bus request: %s.%s() on %s",
2503 dbus_message_get_interface(message),
2504 dbus_message_get_member(message),
2505 dbus_message_get_path(message));
2507 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2508 log_error("Warning! D-Bus connection terminated.");
2509 dbus_connection_close(connection);
2511 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2512 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2513 const char *id, *path;
2515 if (!dbus_message_get_args(message, &error,
2516 DBUS_TYPE_STRING, &id,
2517 DBUS_TYPE_OBJECT_PATH, &path,
2519 log_error("Failed to parse message: %s", bus_error_message(&error));
2520 else if (streq(dbus_message_get_member(message), "UnitNew"))
2521 printf("Unit %s added.\n", id);
2523 printf("Unit %s removed.\n", id);
2525 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2526 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2530 if (!dbus_message_get_args(message, &error,
2531 DBUS_TYPE_UINT32, &id,
2532 DBUS_TYPE_OBJECT_PATH, &path,
2534 log_error("Failed to parse message: %s", bus_error_message(&error));
2535 else if (streq(dbus_message_get_member(message), "JobNew"))
2536 printf("Job %u added.\n", id);
2538 printf("Job %u removed.\n", id);
2541 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2543 const char *path, *interface, *property = "Id";
2544 DBusMessageIter iter, sub;
2546 path = dbus_message_get_path(message);
2548 if (!dbus_message_get_args(message, &error,
2549 DBUS_TYPE_STRING, &interface,
2550 DBUS_TYPE_INVALID)) {
2551 log_error("Failed to parse message: %s", bus_error_message(&error));
2555 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2556 !streq(interface, "org.freedesktop.systemd1.Unit"))
2559 if (!(m = dbus_message_new_method_call(
2560 "org.freedesktop.systemd1",
2562 "org.freedesktop.DBus.Properties",
2564 log_error("Could not allocate message.");
2568 if (!dbus_message_append_args(m,
2569 DBUS_TYPE_STRING, &interface,
2570 DBUS_TYPE_STRING, &property,
2571 DBUS_TYPE_INVALID)) {
2572 log_error("Could not append arguments to message.");
2576 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2577 log_error("Failed to issue method call: %s", bus_error_message(&error));
2581 if (!dbus_message_iter_init(reply, &iter) ||
2582 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2583 log_error("Failed to parse reply.");
2587 dbus_message_iter_recurse(&iter, &sub);
2589 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2592 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2593 log_error("Failed to parse reply.");
2597 dbus_message_iter_get_basic(&sub, &id);
2598 printf("Unit %s changed.\n", id);
2602 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2603 log_error("Failed to parse reply.");
2607 dbus_message_iter_get_basic(&sub, &id);
2608 printf("Job %u changed.\n", id);
2614 dbus_message_unref(m);
2617 dbus_message_unref(reply);
2619 dbus_error_free(&error);
2620 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2624 dbus_message_unref(m);
2627 dbus_message_unref(reply);
2629 dbus_error_free(&error);
2630 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2633 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2634 DBusMessage *m = NULL, *reply = NULL;
2638 dbus_error_init(&error);
2641 dbus_bus_add_match(bus,
2643 "sender='org.freedesktop.systemd1',"
2644 "interface='org.freedesktop.systemd1.Manager',"
2645 "path='/org/freedesktop/systemd1'",
2648 if (dbus_error_is_set(&error)) {
2649 log_error("Failed to add match: %s", bus_error_message(&error));
2654 dbus_bus_add_match(bus,
2656 "sender='org.freedesktop.systemd1',"
2657 "interface='org.freedesktop.DBus.Properties',"
2658 "member='PropertiesChanged'",
2661 if (dbus_error_is_set(&error)) {
2662 log_error("Failed to add match: %s", bus_error_message(&error));
2668 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2669 log_error("Failed to add filter.");
2674 if (!(m = dbus_message_new_method_call(
2675 "org.freedesktop.systemd1",
2676 "/org/freedesktop/systemd1",
2677 "org.freedesktop.systemd1.Manager",
2679 log_error("Could not allocate message.");
2684 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2685 log_error("Failed to issue method call: %s", bus_error_message(&error));
2690 while (dbus_connection_read_write_dispatch(bus, -1))
2697 /* This is slightly dirty, since we don't undo the filter or the matches. */
2700 dbus_message_unref(m);
2703 dbus_message_unref(reply);
2705 dbus_error_free(&error);
2710 static int dump(DBusConnection *bus, char **args, unsigned n) {
2711 DBusMessage *m = NULL, *reply = NULL;
2716 dbus_error_init(&error);
2718 if (!(m = dbus_message_new_method_call(
2719 "org.freedesktop.systemd1",
2720 "/org/freedesktop/systemd1",
2721 "org.freedesktop.systemd1.Manager",
2723 log_error("Could not allocate message.");
2727 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2728 log_error("Failed to issue method call: %s", bus_error_message(&error));
2733 if (!dbus_message_get_args(reply, &error,
2734 DBUS_TYPE_STRING, &text,
2735 DBUS_TYPE_INVALID)) {
2736 log_error("Failed to parse reply: %s", bus_error_message(&error));
2741 fputs(text, stdout);
2747 dbus_message_unref(m);
2750 dbus_message_unref(reply);
2752 dbus_error_free(&error);
2757 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2758 DBusMessage *m = NULL, *reply = NULL;
2761 const char *name = "", *path, *id;
2762 dbus_bool_t cleanup = FALSE;
2763 DBusMessageIter iter, sub;
2765 *interface = "org.freedesktop.systemd1.Unit",
2768 dbus_error_init(&error);
2770 if (!(m = dbus_message_new_method_call(
2771 "org.freedesktop.systemd1",
2772 "/org/freedesktop/systemd1",
2773 "org.freedesktop.systemd1.Manager",
2774 "CreateSnapshot"))) {
2775 log_error("Could not allocate message.");
2782 if (!dbus_message_append_args(m,
2783 DBUS_TYPE_STRING, &name,
2784 DBUS_TYPE_BOOLEAN, &cleanup,
2785 DBUS_TYPE_INVALID)) {
2786 log_error("Could not append arguments to message.");
2791 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2792 log_error("Failed to issue method call: %s", bus_error_message(&error));
2797 if (!dbus_message_get_args(reply, &error,
2798 DBUS_TYPE_OBJECT_PATH, &path,
2799 DBUS_TYPE_INVALID)) {
2800 log_error("Failed to parse reply: %s", bus_error_message(&error));
2805 dbus_message_unref(m);
2806 if (!(m = dbus_message_new_method_call(
2807 "org.freedesktop.systemd1",
2809 "org.freedesktop.DBus.Properties",
2811 log_error("Could not allocate message.");
2815 if (!dbus_message_append_args(m,
2816 DBUS_TYPE_STRING, &interface,
2817 DBUS_TYPE_STRING, &property,
2818 DBUS_TYPE_INVALID)) {
2819 log_error("Could not append arguments to message.");
2824 dbus_message_unref(reply);
2825 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2826 log_error("Failed to issue method call: %s", bus_error_message(&error));
2831 if (!dbus_message_iter_init(reply, &iter) ||
2832 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2833 log_error("Failed to parse reply.");
2838 dbus_message_iter_recurse(&iter, &sub);
2840 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2841 log_error("Failed to parse reply.");
2846 dbus_message_iter_get_basic(&sub, &id);
2854 dbus_message_unref(m);
2857 dbus_message_unref(reply);
2859 dbus_error_free(&error);
2864 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2865 DBusMessage *m = NULL, *reply = NULL;
2873 dbus_error_init(&error);
2875 for (i = 1; i < n; i++) {
2876 const char *path = NULL;
2878 if (!(m = dbus_message_new_method_call(
2879 "org.freedesktop.systemd1",
2880 "/org/freedesktop/systemd1",
2881 "org.freedesktop.systemd1.Manager",
2883 log_error("Could not allocate message.");
2888 if (!dbus_message_append_args(m,
2889 DBUS_TYPE_STRING, &args[i],
2890 DBUS_TYPE_INVALID)) {
2891 log_error("Could not append arguments to message.");
2896 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2897 log_error("Failed to issue method call: %s", bus_error_message(&error));
2902 if (!dbus_message_get_args(reply, &error,
2903 DBUS_TYPE_OBJECT_PATH, &path,
2904 DBUS_TYPE_INVALID)) {
2905 log_error("Failed to parse reply: %s", bus_error_message(&error));
2910 dbus_message_unref(m);
2911 if (!(m = dbus_message_new_method_call(
2912 "org.freedesktop.systemd1",
2914 "org.freedesktop.systemd1.Snapshot",
2916 log_error("Could not allocate message.");
2921 dbus_message_unref(reply);
2922 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2923 log_error("Failed to issue method call: %s", bus_error_message(&error));
2928 dbus_message_unref(m);
2929 dbus_message_unref(reply);
2937 dbus_message_unref(m);
2940 dbus_message_unref(reply);
2942 dbus_error_free(&error);
2947 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2948 DBusMessage *m = NULL, *reply = NULL;
2953 dbus_error_init(&error);
2955 if (arg_action == ACTION_RELOAD)
2957 else if (arg_action == ACTION_REEXEC)
2958 method = "Reexecute";
2960 assert(arg_action == ACTION_SYSTEMCTL);
2963 streq(args[0], "clear-jobs") ||
2964 streq(args[0], "cancel") ? "ClearJobs" :
2965 streq(args[0], "daemon-reexec") ? "Reexecute" :
2966 streq(args[0], "reset-failed") ? "ResetFailed" :
2967 streq(args[0], "daemon-exit") ? "Exit" :
2971 if (!(m = dbus_message_new_method_call(
2972 "org.freedesktop.systemd1",
2973 "/org/freedesktop/systemd1",
2974 "org.freedesktop.systemd1.Manager",
2976 log_error("Could not allocate message.");
2980 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2982 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
2983 /* There's always a fallback possible for
2984 * legacy actions. */
2989 log_error("Failed to issue method call: %s", bus_error_message(&error));
2998 dbus_message_unref(m);
3001 dbus_message_unref(reply);
3003 dbus_error_free(&error);
3008 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3009 DBusMessage *m = NULL, *reply = NULL;
3015 dbus_error_init(&error);
3018 return daemon_reload(bus, args, n);
3020 for (i = 1; i < n; i++) {
3022 if (!(m = dbus_message_new_method_call(
3023 "org.freedesktop.systemd1",
3024 "/org/freedesktop/systemd1",
3025 "org.freedesktop.systemd1.Manager",
3026 "ResetFailedUnit"))) {
3027 log_error("Could not allocate message.");
3032 if (!dbus_message_append_args(m,
3033 DBUS_TYPE_STRING, args + i,
3034 DBUS_TYPE_INVALID)) {
3035 log_error("Could not append arguments to message.");
3040 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3041 log_error("Failed to issue method call: %s", bus_error_message(&error));
3046 dbus_message_unref(m);
3047 dbus_message_unref(reply);
3055 dbus_message_unref(m);
3058 dbus_message_unref(reply);
3060 dbus_error_free(&error);
3065 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3066 DBusMessage *m = NULL, *reply = NULL;
3068 DBusMessageIter iter, sub, sub2;
3071 *interface = "org.freedesktop.systemd1.Manager",
3072 *property = "Environment";
3074 dbus_error_init(&error);
3076 if (!(m = dbus_message_new_method_call(
3077 "org.freedesktop.systemd1",
3078 "/org/freedesktop/systemd1",
3079 "org.freedesktop.DBus.Properties",
3081 log_error("Could not allocate message.");
3085 if (!dbus_message_append_args(m,
3086 DBUS_TYPE_STRING, &interface,
3087 DBUS_TYPE_STRING, &property,
3088 DBUS_TYPE_INVALID)) {
3089 log_error("Could not append arguments to message.");
3094 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3095 log_error("Failed to issue method call: %s", bus_error_message(&error));
3100 if (!dbus_message_iter_init(reply, &iter) ||
3101 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3102 log_error("Failed to parse reply.");
3107 dbus_message_iter_recurse(&iter, &sub);
3109 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3110 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3111 log_error("Failed to parse reply.");
3116 dbus_message_iter_recurse(&sub, &sub2);
3118 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3121 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3122 log_error("Failed to parse reply.");
3127 dbus_message_iter_get_basic(&sub2, &text);
3128 printf("%s\n", text);
3130 dbus_message_iter_next(&sub2);
3137 dbus_message_unref(m);
3140 dbus_message_unref(reply);
3142 dbus_error_free(&error);
3147 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3148 DBusMessage *m = NULL, *reply = NULL;
3152 DBusMessageIter iter, sub;
3155 dbus_error_init(&error);
3157 method = streq(args[0], "set-environment")
3159 : "UnsetEnvironment";
3161 if (!(m = dbus_message_new_method_call(
3162 "org.freedesktop.systemd1",
3163 "/org/freedesktop/systemd1",
3164 "org.freedesktop.systemd1.Manager",
3167 log_error("Could not allocate message.");
3171 dbus_message_iter_init_append(m, &iter);
3173 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3174 log_error("Could not append arguments to message.");
3179 for (i = 1; i < n; i++)
3180 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3181 log_error("Could not append arguments to message.");
3186 if (!dbus_message_iter_close_container(&iter, &sub)) {
3187 log_error("Could not append arguments to message.");
3192 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3193 log_error("Failed to issue method call: %s", bus_error_message(&error));
3202 dbus_message_unref(m);
3205 dbus_message_unref(reply);
3207 dbus_error_free(&error);
3220 static Hashmap *will_install = NULL, *have_installed = NULL;
3221 static Set *remove_symlinks_to = NULL;
3223 static void install_info_free(InstallInfo *i) {
3228 strv_free(i->aliases);
3229 strv_free(i->wanted_by);
3233 static void install_info_hashmap_free(Hashmap *m) {
3236 while ((i = hashmap_steal_first(m)))
3237 install_info_free(i);
3242 static int install_info_add(const char *name) {
3246 assert(will_install);
3248 if (!unit_name_is_valid_no_type(name)) {
3249 log_warning("Unit name %s is not a valid unit name.", name);
3253 if (hashmap_get(have_installed, name) ||
3254 hashmap_get(will_install, name))
3257 if (!(i = new0(InstallInfo, 1))) {
3262 if (!(i->name = strdup(name))) {
3267 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3274 install_info_free(i);
3279 static int config_parse_also(
3280 const char *filename,
3282 const char *section,
3296 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3300 if (!(n = strndup(w, l)))
3303 if ((r = install_info_add(n)) < 0) {
3304 log_warning("Cannot install unit %s: %s", n, strerror(-r));
3315 static int mark_symlink_for_removal(const char *p) {
3320 assert(path_is_absolute(p));
3322 if (!remove_symlinks_to)
3325 if (!(n = strdup(p)))
3328 path_kill_slashes(n);
3330 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3332 return r == -EEXIST ? 0 : r;
3338 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3347 if (!(d = fdopendir(fd))) {
3348 close_nointr_nofail(fd);
3354 while ((de = readdir(d))) {
3355 bool is_dir = false, is_link = false;
3357 if (ignore_file(de->d_name))
3360 if (de->d_type == DT_LNK)
3362 else if (de->d_type == DT_DIR)
3364 else if (de->d_type == DT_UNKNOWN) {
3367 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3368 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3375 is_link = S_ISLNK(st.st_mode);
3376 is_dir = S_ISDIR(st.st_mode);
3384 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3385 log_error("Failed to open %s/%s: %m", root, de->d_name);
3392 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3393 log_error("Failed to allocate directory string.");
3394 close_nointr_nofail(nfd);
3399 /* This will close nfd, regardless whether it succeeds or not */
3400 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3406 } else if (is_link) {
3410 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3411 log_error("Failed to allocate symlink string.");
3416 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3417 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3425 if ((c = canonicalize_file_name(dest))) {
3426 /* This might fail if the destination
3427 * is already removed */
3433 path_kill_slashes(dest);
3434 if (set_get(remove_symlinks_to, dest)) {
3437 log_info("rm '%s'", p);
3439 if (unlink(p) < 0) {
3440 log_error("Cannot unlink symlink %s: %m", p);
3445 rmdir_parents(p, config_path);
3446 path_kill_slashes(p);
3448 if (!set_get(remove_symlinks_to, p)) {
3450 if ((r = mark_symlink_for_removal(p)) < 0) {
3469 static int remove_marked_symlinks(const char *config_path) {
3473 assert(config_path);
3475 if (set_size(remove_symlinks_to) <= 0)
3478 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3485 if ((cfd = dup(fd)) < 0) {
3490 /* This takes possession of cfd and closes it */
3491 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3497 close_nointr_nofail(fd);
3502 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3509 if (streq(verb, "enable")) {
3512 mkdir_parents(new_path, 0755);
3514 if (symlink(old_path, new_path) >= 0) {
3517 log_info("ln -s '%s' '%s'", old_path, new_path);
3522 if (errno != EEXIST) {
3523 log_error("Cannot link %s to %s: %m", old_path, new_path);
3527 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3529 if (errno == EINVAL) {
3530 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3534 log_error("readlink() failed: %s", strerror(-r));
3538 if (streq(dest, old_path)) {
3544 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3553 log_info("ln -s '%s' '%s'", old_path, new_path);
3555 if (symlink(old_path, new_path) >= 0)
3558 log_error("Cannot link %s to %s: %m", old_path, new_path);
3561 } else if (streq(verb, "disable")) {
3564 if ((r = mark_symlink_for_removal(old_path)) < 0)
3567 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3568 if (errno == ENOENT)
3571 if (errno == EINVAL) {
3572 log_warning("File %s not a symlink, ignoring.", old_path);
3576 log_error("readlink() failed: %s", strerror(-r));
3580 if (!streq(dest, old_path)) {
3581 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3588 if ((r = mark_symlink_for_removal(new_path)) < 0)
3592 log_info("rm '%s'", new_path);
3594 if (unlink(new_path) >= 0)
3597 log_error("Cannot unlink %s: %m", new_path);
3600 } else if (streq(verb, "is-enabled")) {
3603 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3605 if (errno == ENOENT || errno == EINVAL)
3608 log_error("readlink() failed: %s", strerror(-r));
3612 if (streq(dest, old_path)) {
3620 assert_not_reached("Unknown action.");
3623 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3625 char *alias_path = NULL;
3630 assert(config_path);
3632 STRV_FOREACH(s, i->aliases) {
3634 if (!unit_name_is_valid_no_type(*s)) {
3635 log_error("Invalid name %s.", *s);
3641 if (!(alias_path = path_make_absolute(*s, config_path))) {
3642 log_error("Out of memory");
3647 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3650 if (streq(verb, "disable"))
3651 rmdir_parents(alias_path, config_path);
3661 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3663 char *alias_path = NULL;
3668 assert(config_path);
3670 STRV_FOREACH(s, i->wanted_by) {
3671 if (!unit_name_is_valid_no_type(*s)) {
3672 log_error("Invalid name %s.", *s);
3680 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3681 log_error("Out of memory");
3686 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3689 if (streq(verb, "disable"))
3690 rmdir_parents(alias_path, config_path);
3701 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3703 const ConfigItem items[] = {
3704 { "Alias", config_parse_strv, &i->aliases, "Install" },
3705 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3706 { "Also", config_parse_also, NULL, "Install" },
3708 { NULL, NULL, NULL, NULL }
3712 char *filename = NULL;
3719 STRV_FOREACH(p, paths->unit_path) {
3722 if (!(filename = path_make_absolute(i->name, *p))) {
3723 log_error("Out of memory");
3727 /* Ensure that we don't follow symlinks */
3728 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3729 if ((f = fdopen(fd, "re")))
3732 if (errno == ELOOP) {
3733 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3738 if (errno != ENOENT) {
3739 log_error("Failed to open %s: %m", filename);
3749 log_error("Couldn't find %s.", i->name);
3755 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3762 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3765 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3768 if ((r = mark_symlink_for_removal(filename)) < 0)
3771 if ((r = remove_marked_symlinks(config_path)) < 0)
3777 static char *get_config_path(void) {
3779 if (arg_session && arg_global)
3780 return strdup(SESSION_CONFIG_UNIT_PATH);
3785 if (session_config_home(&p) < 0)
3791 return strdup(SYSTEM_CONFIG_UNIT_PATH);
3794 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3798 char *config_path = NULL;
3801 const char *verb = args[0];
3803 dbus_error_init(&error);
3806 if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3807 log_error("Failed to determine lookup paths: %s", strerror(-r));
3811 if (!(config_path = get_config_path())) {
3812 log_error("Failed to determine config path");
3817 will_install = hashmap_new(string_hash_func, string_compare_func);
3818 have_installed = hashmap_new(string_hash_func, string_compare_func);
3820 if (!will_install || !have_installed) {
3821 log_error("Failed to allocate unit sets.");
3826 if (!arg_defaults && streq(verb, "disable"))
3827 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3828 log_error("Failed to allocate symlink sets.");
3833 for (j = 1; j < n; j++)
3834 if ((r = install_info_add(args[j])) < 0) {
3835 log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
3839 while ((i = hashmap_first(will_install))) {
3842 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3844 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3852 /* In test mode and found something */
3858 if (streq(verb, "is-enabled"))
3859 r = r > 0 ? 0 : -ENOENT;
3861 /* Don't try to reload anything if the user asked us to not do this */
3863 /* Don't try to reload anything when updating a unit globally */
3865 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3866 (arg_session || sd_booted() > 0) &&
3867 /* Don't try to reload anything if we are running in a chroot environment */
3868 (arg_session || running_in_chroot() <= 0) ) {
3871 if ((q = daemon_reload(bus, args, n)) < 0)
3876 install_info_hashmap_free(will_install);
3877 install_info_hashmap_free(have_installed);
3879 set_free_free(remove_symlinks_to);
3881 lookup_paths_free(&paths);
3888 static int systemctl_help(void) {
3890 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3891 "Send control commands to or query the systemd manager.\n\n"
3892 " -h --help Show this help\n"
3893 " --version Show package version\n"
3894 " -t --type=TYPE List only units of a particular type\n"
3895 " -p --property=NAME Show only properties by this name\n"
3896 " -a --all Show all units/properties, including dead/empty ones\n"
3897 " --full Don't ellipsize unit names on output\n"
3898 " --fail When queueing a new job, fail if conflicting jobs are\n"
3900 " -q --quiet Suppress output\n"
3901 " --no-block Do not wait until operation finished\n"
3902 " --system Connect to system bus\n"
3903 " --session Connect to session bus\n"
3904 " --order When generating graph for dot, show only order\n"
3905 " --require When generating graph for dot, show only requirement\n"
3906 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3907 " --global Enable/disable unit files globally\n"
3908 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3910 " --force When enabling unit files, override existing symlinks\n"
3911 " --defaults When disabling unit files, remove default symlinks only\n\n"
3913 " list-units List units\n"
3914 " start [NAME...] Start (activate) one or more units\n"
3915 " stop [NAME...] Stop (deactivate) one or more units\n"
3916 " reload [NAME...] Reload one or more units\n"
3917 " restart [NAME...] Start or restart one or more units\n"
3918 " try-restart [NAME...] Restart one or more units if active\n"
3919 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3920 " otherwise start or restart\n"
3921 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3922 " otherwise restart if active\n"
3923 " isolate [NAME] Start one unit and stop all others\n"
3924 " is-active [NAME...] Check whether units are active\n"
3925 " status [NAME...|PID...] Show runtime status of one or more units\n"
3926 " show [NAME...|JOB...] Show properties of one or more\n"
3927 " units/jobs or the manager\n"
3928 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
3930 " enable [NAME...] Enable one or more unit files\n"
3931 " disable [NAME...] Disable one or more unit files\n"
3932 " is-enabled [NAME...] Check whether unit files are enabled\n"
3933 " load [NAME...] Load one or more units\n"
3934 " list-jobs List jobs\n"
3935 " cancel [JOB...] Cancel all, one, or more jobs\n"
3936 " monitor Monitor unit/job changes\n"
3937 " dump Dump server status\n"
3938 " dot Dump dependency graph for dot(1)\n"
3939 " snapshot [NAME] Create a snapshot\n"
3940 " delete [NAME...] Remove one or more snapshots\n"
3941 " daemon-reload Reload systemd manager configuration\n"
3942 " daemon-reexec Reexecute systemd manager\n"
3943 " daemon-exit Ask the systemd manager to quit\n"
3944 " show-environment Dump environment\n"
3945 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3946 " unset-environment [NAME...] Unset one or more environment variables\n"
3947 " halt Shut down and halt the system\n"
3948 " poweroff Shut down and power-off the system\n"
3949 " reboot Shut down and reboot the system\n"
3950 " rescue Enter system rescue mode\n"
3951 " emergency Enter system emergency mode\n"
3952 " default Enter system default mode\n",
3953 program_invocation_short_name);
3958 static int halt_help(void) {
3960 printf("%s [OPTIONS...]\n\n"
3961 "%s the system.\n\n"
3962 " --help Show this help\n"
3963 " --halt Halt the machine\n"
3964 " -p --poweroff Switch off the machine\n"
3965 " --reboot Reboot the machine\n"
3966 " -f --force Force immediate halt/power-off/reboot\n"
3967 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3968 " -d --no-wtmp Don't write wtmp record\n"
3969 " -n --no-sync Don't sync before halt/power-off/reboot\n"
3970 " --no-wall Don't send wall message before halt/power-off/reboot\n",
3971 program_invocation_short_name,
3972 arg_action == ACTION_REBOOT ? "Reboot" :
3973 arg_action == ACTION_POWEROFF ? "Power off" :
3979 static int shutdown_help(void) {
3981 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3982 "Shut down the system.\n\n"
3983 " --help Show this help\n"
3984 " -H --halt Halt the machine\n"
3985 " -P --poweroff Power-off the machine\n"
3986 " -r --reboot Reboot the machine\n"
3987 " -h Equivalent to --poweroff, overriden by --halt\n"
3988 " -k Don't halt/power-off/reboot, just send warnings\n"
3989 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3990 " -c Cancel a pending shutdown\n",
3991 program_invocation_short_name);
3996 static int telinit_help(void) {
3998 printf("%s [OPTIONS...] {COMMAND}\n\n"
3999 "Send control commands to the init daemon.\n\n"
4000 " --help Show this help\n"
4001 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4003 " 0 Power-off the machine\n"
4004 " 6 Reboot the machine\n"
4005 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4006 " 1, s, S Enter rescue mode\n"
4007 " q, Q Reload init daemon configuration\n"
4008 " u, U Reexecute init daemon\n",
4009 program_invocation_short_name);
4014 static int runlevel_help(void) {
4016 printf("%s [OPTIONS...]\n\n"
4017 "Prints the previous and current runlevel of the init system.\n\n"
4018 " --help Show this help\n",
4019 program_invocation_short_name);
4024 static int systemctl_parse_argv(int argc, char *argv[]) {
4042 static const struct option options[] = {
4043 { "help", no_argument, NULL, 'h' },
4044 { "version", no_argument, NULL, ARG_VERSION },
4045 { "type", required_argument, NULL, 't' },
4046 { "property", required_argument, NULL, 'p' },
4047 { "all", no_argument, NULL, 'a' },
4048 { "full", no_argument, NULL, ARG_FULL },
4049 { "fail", no_argument, NULL, ARG_FAIL },
4050 { "session", no_argument, NULL, ARG_SESSION },
4051 { "system", no_argument, NULL, ARG_SYSTEM },
4052 { "global", no_argument, NULL, ARG_GLOBAL },
4053 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4054 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4055 { "quiet", no_argument, NULL, 'q' },
4056 { "order", no_argument, NULL, ARG_ORDER },
4057 { "require", no_argument, NULL, ARG_REQUIRE },
4058 { "force", no_argument, NULL, ARG_FORCE },
4059 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4060 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4061 { NULL, 0, NULL, 0 }
4069 while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
4078 puts(PACKAGE_STRING);
4080 puts(SYSTEMD_FEATURES);
4090 if (!(l = strv_append(arg_property, optarg)))
4093 strv_free(arg_property);
4096 /* If the user asked for a particular
4097 * property, show it to him, even if it is
4116 arg_session = false;
4120 arg_no_block = true;
4128 arg_dot = DOT_ORDER;
4132 arg_dot = DOT_REQUIRE;
4148 arg_no_reload = true;
4157 arg_defaults = true;
4164 log_error("Unknown option code %c", c);
4172 static int halt_parse_argv(int argc, char *argv[]) {
4181 static const struct option options[] = {
4182 { "help", no_argument, NULL, ARG_HELP },
4183 { "halt", no_argument, NULL, ARG_HALT },
4184 { "poweroff", no_argument, NULL, 'p' },
4185 { "reboot", no_argument, NULL, ARG_REBOOT },
4186 { "force", no_argument, NULL, 'f' },
4187 { "wtmp-only", no_argument, NULL, 'w' },
4188 { "no-wtmp", no_argument, NULL, 'd' },
4189 { "no-sync", no_argument, NULL, 'n' },
4190 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4191 { NULL, 0, NULL, 0 }
4199 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4200 if (runlevel == '0' || runlevel == '6')
4201 arg_immediate = true;
4203 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4211 arg_action = ACTION_HALT;
4215 if (arg_action != ACTION_REBOOT)
4216 arg_action = ACTION_POWEROFF;
4220 arg_action = ACTION_REBOOT;
4224 arg_immediate = true;
4245 /* Compatibility nops */
4252 log_error("Unknown option code %c", c);
4257 if (optind < argc) {
4258 log_error("Too many arguments.");
4265 static int parse_time_spec(const char *t, usec_t *_u) {
4269 if (streq(t, "now"))
4271 else if (t[0] == '+') {
4274 if (safe_atou64(t + 1, &u) < 0)
4277 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4286 hour = strtol(t, &e, 10);
4287 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4290 minute = strtol(e+1, &e, 10);
4291 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4294 n = now(CLOCK_REALTIME);
4295 s = (time_t) (n / USEC_PER_SEC);
4298 assert_se(localtime_r(&s, &tm));
4300 tm.tm_hour = (int) hour;
4301 tm.tm_min = (int) minute;
4304 assert_se(s = mktime(&tm));
4306 *_u = (usec_t) s * USEC_PER_SEC;
4309 *_u += USEC_PER_DAY;
4315 static int shutdown_parse_argv(int argc, char *argv[]) {
4322 static const struct option options[] = {
4323 { "help", no_argument, NULL, ARG_HELP },
4324 { "halt", no_argument, NULL, 'H' },
4325 { "poweroff", no_argument, NULL, 'P' },
4326 { "reboot", no_argument, NULL, 'r' },
4327 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4328 { NULL, 0, NULL, 0 }
4336 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4344 arg_action = ACTION_HALT;
4348 arg_action = ACTION_POWEROFF;
4352 arg_action = ACTION_REBOOT;
4356 if (arg_action != ACTION_HALT)
4357 arg_action = ACTION_POWEROFF;
4370 /* Compatibility nops */
4374 arg_action = ACTION_CANCEL_SHUTDOWN;
4381 log_error("Unknown option code %c", c);
4386 if (argc > optind) {
4387 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4388 log_error("Failed to parse time specification: %s", argv[optind]);
4392 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4394 /* We skip the time argument */
4395 if (argc > optind + 1)
4396 arg_wall = argv + optind + 1;
4403 static int telinit_parse_argv(int argc, char *argv[]) {
4410 static const struct option options[] = {
4411 { "help", no_argument, NULL, ARG_HELP },
4412 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4413 { NULL, 0, NULL, 0 }
4416 static const struct {
4420 { '0', ACTION_POWEROFF },
4421 { '6', ACTION_REBOOT },
4422 { '1', ACTION_RESCUE },
4423 { '2', ACTION_RUNLEVEL2 },
4424 { '3', ACTION_RUNLEVEL3 },
4425 { '4', ACTION_RUNLEVEL4 },
4426 { '5', ACTION_RUNLEVEL5 },
4427 { 's', ACTION_RESCUE },
4428 { 'S', ACTION_RESCUE },
4429 { 'q', ACTION_RELOAD },
4430 { 'Q', ACTION_RELOAD },
4431 { 'u', ACTION_REEXEC },
4432 { 'U', ACTION_REEXEC }
4441 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4456 log_error("Unknown option code %c", c);
4461 if (optind >= argc) {
4466 if (optind + 1 < argc) {
4467 log_error("Too many arguments.");
4471 if (strlen(argv[optind]) != 1) {
4472 log_error("Expected single character argument.");
4476 for (i = 0; i < ELEMENTSOF(table); i++)
4477 if (table[i].from == argv[optind][0])
4480 if (i >= ELEMENTSOF(table)) {
4481 log_error("Unknown command %s.", argv[optind]);
4485 arg_action = table[i].to;
4492 static int runlevel_parse_argv(int argc, char *argv[]) {
4498 static const struct option options[] = {
4499 { "help", no_argument, NULL, ARG_HELP },
4500 { NULL, 0, NULL, 0 }
4508 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4519 log_error("Unknown option code %c", c);
4524 if (optind < argc) {
4525 log_error("Too many arguments.");
4532 static int parse_argv(int argc, char *argv[]) {
4536 if (program_invocation_short_name) {
4538 if (strstr(program_invocation_short_name, "halt")) {
4539 arg_action = ACTION_HALT;
4540 return halt_parse_argv(argc, argv);
4541 } else if (strstr(program_invocation_short_name, "poweroff")) {
4542 arg_action = ACTION_POWEROFF;
4543 return halt_parse_argv(argc, argv);
4544 } else if (strstr(program_invocation_short_name, "reboot")) {
4545 arg_action = ACTION_REBOOT;
4546 return halt_parse_argv(argc, argv);
4547 } else if (strstr(program_invocation_short_name, "shutdown")) {
4548 arg_action = ACTION_POWEROFF;
4549 return shutdown_parse_argv(argc, argv);
4550 } else if (strstr(program_invocation_short_name, "init")) {
4552 if (sd_booted() > 0) {
4553 arg_action = ACTION_INVALID;
4554 return telinit_parse_argv(argc, argv);
4556 /* Hmm, so some other init system is
4557 * running, we need to forward this
4558 * request to it. For now we simply
4559 * guess that it is Upstart. */
4561 execv("/lib/upstart/telinit", argv);
4563 log_error("Couldn't find an alternative telinit implementation to spawn.");
4567 } else if (strstr(program_invocation_short_name, "runlevel")) {
4568 arg_action = ACTION_RUNLEVEL;
4569 return runlevel_parse_argv(argc, argv);
4573 arg_action = ACTION_SYSTEMCTL;
4574 return systemctl_parse_argv(argc, argv);
4577 static int action_to_runlevel(void) {
4579 static const char table[_ACTION_MAX] = {
4580 [ACTION_HALT] = '0',
4581 [ACTION_POWEROFF] = '0',
4582 [ACTION_REBOOT] = '6',
4583 [ACTION_RUNLEVEL2] = '2',
4584 [ACTION_RUNLEVEL3] = '3',
4585 [ACTION_RUNLEVEL4] = '4',
4586 [ACTION_RUNLEVEL5] = '5',
4587 [ACTION_RESCUE] = '1'
4590 assert(arg_action < _ACTION_MAX);
4592 return table[arg_action];
4595 static int talk_upstart(void) {
4596 DBusMessage *m = NULL, *reply = NULL;
4598 int previous, rl, r;
4600 env1_buf[] = "RUNLEVEL=X",
4601 env2_buf[] = "PREVLEVEL=X";
4602 char *env1 = env1_buf, *env2 = env2_buf;
4603 const char *emit = "runlevel";
4604 dbus_bool_t b_false = FALSE;
4605 DBusMessageIter iter, sub;
4606 DBusConnection *bus;
4608 dbus_error_init(&error);
4610 if (!(rl = action_to_runlevel()))
4613 if (utmp_get_runlevel(&previous, NULL) < 0)
4616 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4617 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4622 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4627 if ((r = bus_check_peercred(bus)) < 0) {
4628 log_error("Failed to verify owner of bus.");
4632 if (!(m = dbus_message_new_method_call(
4633 "com.ubuntu.Upstart",
4634 "/com/ubuntu/Upstart",
4635 "com.ubuntu.Upstart0_6",
4638 log_error("Could not allocate message.");
4643 dbus_message_iter_init_append(m, &iter);
4645 env1_buf[sizeof(env1_buf)-2] = rl;
4646 env2_buf[sizeof(env2_buf)-2] = previous;
4648 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4649 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4650 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4651 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4652 !dbus_message_iter_close_container(&iter, &sub) ||
4653 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4654 log_error("Could not append arguments to message.");
4659 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4661 if (error_is_no_service(&error)) {
4666 log_error("Failed to issue method call: %s", bus_error_message(&error));
4675 dbus_message_unref(m);
4678 dbus_message_unref(reply);
4681 dbus_connection_flush(bus);
4682 dbus_connection_close(bus);
4683 dbus_connection_unref(bus);
4686 dbus_error_free(&error);
4691 static int talk_initctl(void) {
4692 struct init_request request;
4696 if (!(rl = action_to_runlevel()))
4700 request.magic = INIT_MAGIC;
4701 request.sleeptime = 0;
4702 request.cmd = INIT_CMD_RUNLVL;
4703 request.runlevel = rl;
4705 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4707 if (errno == ENOENT)
4710 log_error("Failed to open "INIT_FIFO": %m");
4715 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4716 close_nointr_nofail(fd);
4719 log_error("Failed to write to "INIT_FIFO": %m");
4720 return errno ? -errno : -EIO;
4726 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4728 static const struct {
4736 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4738 { "list-units", LESS, 1, list_units },
4739 { "list-jobs", EQUAL, 1, list_jobs },
4740 { "clear-jobs", EQUAL, 1, daemon_reload },
4741 { "load", MORE, 2, load_unit },
4742 { "cancel", MORE, 2, cancel_job },
4743 { "start", MORE, 2, start_unit },
4744 { "stop", MORE, 2, start_unit },
4745 { "reload", MORE, 2, start_unit },
4746 { "restart", MORE, 2, start_unit },
4747 { "try-restart", MORE, 2, start_unit },
4748 { "reload-or-restart", MORE, 2, start_unit },
4749 { "reload-or-try-restart", MORE, 2, start_unit },
4750 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4751 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4752 { "isolate", EQUAL, 2, start_unit },
4753 { "is-active", MORE, 2, check_unit },
4754 { "check", MORE, 2, check_unit },
4755 { "show", MORE, 1, show },
4756 { "status", MORE, 2, show },
4757 { "monitor", EQUAL, 1, monitor },
4758 { "dump", EQUAL, 1, dump },
4759 { "dot", EQUAL, 1, dot },
4760 { "snapshot", LESS, 2, snapshot },
4761 { "delete", MORE, 2, delete_snapshot },
4762 { "daemon-reload", EQUAL, 1, daemon_reload },
4763 { "daemon-reexec", EQUAL, 1, daemon_reload },
4764 { "daemon-exit", EQUAL, 1, daemon_reload },
4765 { "show-environment", EQUAL, 1, show_enviroment },
4766 { "set-environment", MORE, 2, set_environment },
4767 { "unset-environment", MORE, 2, set_environment },
4768 { "halt", EQUAL, 1, start_special },
4769 { "poweroff", EQUAL, 1, start_special },
4770 { "reboot", EQUAL, 1, start_special },
4771 { "default", EQUAL, 1, start_special },
4772 { "rescue", EQUAL, 1, start_special },
4773 { "emergency", EQUAL, 1, start_special },
4774 { "reset-failed", MORE, 1, reset_failed },
4775 { "enable", MORE, 2, enable_unit },
4776 { "disable", MORE, 2, enable_unit },
4777 { "is-enabled", MORE, 2, enable_unit }
4787 left = argc - optind;
4790 /* Special rule: no arguments means "list-units" */
4793 if (streq(argv[optind], "help")) {
4798 for (i = 0; i < ELEMENTSOF(verbs); i++)
4799 if (streq(argv[optind], verbs[i].verb))
4802 if (i >= ELEMENTSOF(verbs)) {
4803 log_error("Unknown operation %s", argv[optind]);
4808 switch (verbs[i].argc_cmp) {
4811 if (left != verbs[i].argc) {
4812 log_error("Invalid number of arguments.");
4819 if (left < verbs[i].argc) {
4820 log_error("Too few arguments.");
4827 if (left > verbs[i].argc) {
4828 log_error("Too many arguments.");
4835 assert_not_reached("Unknown comparison operator.");
4838 /* Require a bus connection for all operations but
4840 if (!streq(verbs[i].verb, "enable") &&
4841 !streq(verbs[i].verb, "disable") &&
4843 log_error("Failed to get D-Bus connection: %s", error->message);
4847 return verbs[i].dispatch(bus, argv + optind, left);
4850 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
4852 struct msghdr msghdr;
4854 union sockaddr_union sockaddr;
4855 struct shutdownd_command c;
4863 strncpy(c.wall_message, message, sizeof(c.wall_message));
4865 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4869 sockaddr.sa.sa_family = AF_UNIX;
4870 sockaddr.un.sun_path[0] = 0;
4871 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
4874 iovec.iov_base = (char*) &c;
4875 iovec.iov_len = sizeof(c);
4878 msghdr.msg_name = &sockaddr;
4879 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
4881 msghdr.msg_iov = &iovec;
4882 msghdr.msg_iovlen = 1;
4884 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
4885 close_nointr_nofail(fd);
4889 close_nointr_nofail(fd);
4893 static int reload_with_fallback(DBusConnection *bus) {
4896 /* First, try systemd via D-Bus. */
4897 if (daemon_reload(bus, NULL, 0) > 0)
4901 /* Nothing else worked, so let's try signals */
4902 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
4904 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
4905 log_error("kill() failed: %m");
4912 static int start_with_fallback(DBusConnection *bus) {
4915 /* First, try systemd via D-Bus. */
4916 if (start_unit(bus, NULL, 0) >= 0)
4920 /* Hmm, talking to systemd via D-Bus didn't work. Then
4921 * let's try to talk to Upstart via D-Bus. */
4922 if (talk_upstart() > 0)
4925 /* Nothing else worked, so let's try
4927 if (talk_initctl() > 0)
4930 log_error("Failed to talk to init daemon.");
4934 warn_wall(arg_action);
4938 static int halt_main(DBusConnection *bus) {
4941 if (geteuid() != 0) {
4942 log_error("Must be root.");
4948 char date[FORMAT_TIMESTAMP_MAX];
4950 m = strv_join(arg_wall, " ");
4951 r = send_shutdownd(arg_when,
4952 arg_action == ACTION_HALT ? 'H' :
4953 arg_action == ACTION_POWEROFF ? 'P' :
4960 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
4962 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
4963 format_timestamp(date, sizeof(date), arg_when));
4968 if (!arg_dry && !arg_immediate)
4969 return start_with_fallback(bus);
4972 if (sd_booted() > 0)
4973 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
4974 else if ((r = utmp_put_shutdown(0)) < 0)
4975 log_warning("Failed to write utmp record: %s", strerror(-r));
4984 /* Make sure C-A-D is handled by the kernel from this
4986 reboot(RB_ENABLE_CAD);
4988 switch (arg_action) {
4991 log_info("Halting.");
4992 reboot(RB_HALT_SYSTEM);
4995 case ACTION_POWEROFF:
4996 log_info("Powering off.");
4997 reboot(RB_POWER_OFF);
5001 log_info("Rebooting.");
5002 reboot(RB_AUTOBOOT);
5006 assert_not_reached("Unknown halt action.");
5009 /* We should never reach this. */
5013 static int runlevel_main(void) {
5014 int r, runlevel, previous;
5016 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5017 printf("unknown\n");
5022 previous <= 0 ? 'N' : previous,
5023 runlevel <= 0 ? 'N' : runlevel);
5028 int main(int argc, char*argv[]) {
5029 int r, retval = EXIT_FAILURE;
5030 DBusConnection *bus = NULL;
5033 dbus_error_init(&error);
5035 log_parse_environment();
5038 if ((r = parse_argv(argc, argv)) < 0)
5041 retval = EXIT_SUCCESS;
5045 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5046 * let's shortcut this */
5047 if (arg_action == ACTION_RUNLEVEL) {
5048 r = runlevel_main();
5049 retval = r < 0 ? EXIT_FAILURE : r;
5053 bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5055 switch (arg_action) {
5057 case ACTION_SYSTEMCTL:
5058 r = systemctl_main(bus, argc, argv, &error);
5062 case ACTION_POWEROFF:
5067 case ACTION_RUNLEVEL2:
5068 case ACTION_RUNLEVEL3:
5069 case ACTION_RUNLEVEL4:
5070 case ACTION_RUNLEVEL5:
5072 case ACTION_EMERGENCY:
5073 case ACTION_DEFAULT:
5074 r = start_with_fallback(bus);
5079 r = reload_with_fallback(bus);
5082 case ACTION_CANCEL_SHUTDOWN:
5083 r = send_shutdownd(0, 0, false, NULL);
5086 case ACTION_INVALID:
5087 case ACTION_RUNLEVEL:
5089 assert_not_reached("Unknown action");
5092 retval = r < 0 ? EXIT_FAILURE : r;
5097 dbus_connection_flush(bus);
5098 dbus_connection_close(bus);
5099 dbus_connection_unref(bus);
5102 dbus_error_free(&error);
5106 strv_free(arg_property);