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;
96 ACTION_CANCEL_SHUTDOWN,
98 } arg_action = ACTION_SYSTEMCTL;
105 static bool private_bus = false;
107 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
109 static bool on_tty(void) {
112 if (_unlikely_(t < 0))
113 t = isatty(STDOUT_FILENO) > 0;
118 static const char *ansi_highlight(bool b) {
123 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
126 static const char *ansi_highlight_green(bool b) {
131 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
134 static bool error_is_no_service(const DBusError *error) {
137 if (!dbus_error_is_set(error))
140 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
143 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
146 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
149 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
152 if (!dbus_error_is_set(error))
155 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
156 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
157 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
158 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
159 return EXIT_NOPERMISSION;
161 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
162 return EXIT_NOTINSTALLED;
164 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
165 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
166 return EXIT_NOTIMPLEMENTED;
168 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
169 return EXIT_NOTCONFIGURED;
177 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
182 if (dbus_message_iter_get_arg_type(iter) != type)
185 dbus_message_iter_get_basic(iter, data);
187 if (!dbus_message_iter_next(iter) != !next)
193 static void warn_wall(enum action action) {
194 static const char *table[_ACTION_MAX] = {
195 [ACTION_HALT] = "The system is going down for system halt NOW!",
196 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
197 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
198 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
199 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
200 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
209 if (!(p = strv_join(arg_wall, " "))) {
210 log_error("Failed to join strings.");
226 utmp_wall(table[action]);
231 const char *description;
232 const char *load_state;
233 const char *active_state;
234 const char *sub_state;
235 const char *following;
236 const char *unit_path;
238 const char *job_type;
239 const char *job_path;
242 static int compare_unit_info(const void *a, const void *b) {
244 const struct unit_info *u = a, *v = b;
246 d1 = strrchr(u->id, '.');
247 d2 = strrchr(v->id, '.');
252 if ((r = strcasecmp(d1, d2)) != 0)
256 return strcasecmp(u->id, v->id);
259 static bool output_show_job(const struct unit_info *u) {
262 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
263 streq(dot+1, arg_type))) &&
264 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0);
267 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
268 unsigned active_len, sub_len, job_len;
269 const struct unit_info *u;
271 active_len = sizeof("ACTIVE")-1;
272 sub_len = sizeof("SUB")-1;
273 job_len = sizeof("JOB")-1;
275 for (u = unit_infos; u < unit_infos + c; u++) {
276 if (!output_show_job(u))
279 active_len = MAX(active_len, strlen(u->active_state));
280 sub_len = MAX(sub_len, strlen(u->sub_state));
282 job_len = MAX(job_len, strlen(u->job_type));
286 printf("%-25s %-6s %-*s %-*s %-*s", "UNIT", "LOAD",
287 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
288 if (columns() >= 80+12 || arg_full)
289 printf(" %s\n", "DESCRIPTION");
294 for (u = unit_infos; u < unit_infos + c; u++) {
297 const char *on_loaded, *off_loaded;
298 const char *on_active, *off_active;
300 if (!output_show_job(u))
303 if (!streq(u->load_state, "loaded") &&
304 !streq(u->load_state, "banned")) {
305 on_loaded = ansi_highlight(true);
306 off_loaded = ansi_highlight(false);
308 on_loaded = off_loaded = "";
310 if (streq(u->active_state, "failed")) {
311 on_active = ansi_highlight(true);
312 off_active = ansi_highlight(false);
314 on_active = off_active = "";
316 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
318 printf("%-25s %s%-6s%s %s%-*s %-*s%s%n",
320 on_loaded, u->load_state, off_loaded,
321 on_active, active_len, u->active_state,
322 sub_len, u->sub_state, off_active,
327 a -= strlen(on_loaded) + strlen(off_loaded);
328 a -= strlen(on_active) + strlen(off_active);
331 printf(" %-*s", job_len, u->job_type);
335 if (a + b + 1 < columns()) {
337 printf(" %-*s", job_len, "");
340 printf(" %s", u->description);
342 printf(" %.*s", columns() - a - b - 1, u->description);
349 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
350 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
351 "SUB = The low-level unit activation state, values depend on unit type.\n"
352 "JOB = Pending job for the unit.\n");
355 printf("\n%u units listed.\n", c);
357 printf("\n%u units listed. Pass --all to see inactive units, too.\n", c);
361 static int list_units(DBusConnection *bus, char **args, unsigned n) {
362 DBusMessage *m = NULL, *reply = NULL;
365 DBusMessageIter iter, sub, sub2;
366 unsigned c = 0, n_units = 0;
367 struct unit_info *unit_infos = NULL;
369 dbus_error_init(&error);
373 if (!(m = dbus_message_new_method_call(
374 "org.freedesktop.systemd1",
375 "/org/freedesktop/systemd1",
376 "org.freedesktop.systemd1.Manager",
378 log_error("Could not allocate message.");
382 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
383 log_error("Failed to issue method call: %s", bus_error_message(&error));
388 if (!dbus_message_iter_init(reply, &iter) ||
389 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
390 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
391 log_error("Failed to parse reply.");
396 dbus_message_iter_recurse(&iter, &sub);
398 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
401 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
402 log_error("Failed to parse reply.");
410 n_units = MAX(2*c, 16);
411 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
414 log_error("Failed to allocate unit array.");
424 dbus_message_iter_recurse(&sub, &sub2);
426 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
427 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
428 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
429 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
430 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
431 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
432 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
433 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
434 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
435 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
436 log_error("Failed to parse reply.");
441 dbus_message_iter_next(&sub);
445 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
446 output_units_list(unit_infos, c);
452 dbus_message_unref(m);
455 dbus_message_unref(reply);
459 dbus_error_free(&error);
464 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
465 static const char * const colors[] = {
466 "Requires", "[color=\"black\"]",
467 "RequiresOverridable", "[color=\"black\"]",
468 "Requisite", "[color=\"darkblue\"]",
469 "RequisiteOverridable", "[color=\"darkblue\"]",
470 "Wants", "[color=\"darkgrey\"]",
471 "Conflicts", "[color=\"red\"]",
472 "ConflictedBy", "[color=\"red\"]",
473 "After", "[color=\"green\"]"
476 const char *c = NULL;
483 for (i = 0; i < ELEMENTSOF(colors); i += 2)
484 if (streq(colors[i], prop)) {
492 if (arg_dot != DOT_ALL)
493 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
496 switch (dbus_message_iter_get_arg_type(iter)) {
498 case DBUS_TYPE_ARRAY:
500 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
503 dbus_message_iter_recurse(iter, &sub);
505 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
508 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
509 dbus_message_iter_get_basic(&sub, &s);
510 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
512 dbus_message_iter_next(&sub);
522 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
523 DBusMessage *m = NULL, *reply = NULL;
524 const char *interface = "org.freedesktop.systemd1.Unit";
527 DBusMessageIter iter, sub, sub2, sub3;
532 dbus_error_init(&error);
534 if (!(m = dbus_message_new_method_call(
535 "org.freedesktop.systemd1",
537 "org.freedesktop.DBus.Properties",
539 log_error("Could not allocate message.");
544 if (!dbus_message_append_args(m,
545 DBUS_TYPE_STRING, &interface,
546 DBUS_TYPE_INVALID)) {
547 log_error("Could not append arguments to message.");
552 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
553 log_error("Failed to issue method call: %s", bus_error_message(&error));
558 if (!dbus_message_iter_init(reply, &iter) ||
559 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
560 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
561 log_error("Failed to parse reply.");
566 dbus_message_iter_recurse(&iter, &sub);
568 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
571 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
572 log_error("Failed to parse reply.");
577 dbus_message_iter_recurse(&sub, &sub2);
579 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
580 log_error("Failed to parse reply.");
585 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
586 log_error("Failed to parse reply.");
591 dbus_message_iter_recurse(&sub2, &sub3);
593 if (dot_one_property(name, prop, &sub3)) {
594 log_error("Failed to parse reply.");
599 dbus_message_iter_next(&sub);
606 dbus_message_unref(m);
609 dbus_message_unref(reply);
611 dbus_error_free(&error);
616 static int dot(DBusConnection *bus, char **args, unsigned n) {
617 DBusMessage *m = NULL, *reply = NULL;
620 DBusMessageIter iter, sub, sub2;
622 dbus_error_init(&error);
626 if (!(m = dbus_message_new_method_call(
627 "org.freedesktop.systemd1",
628 "/org/freedesktop/systemd1",
629 "org.freedesktop.systemd1.Manager",
631 log_error("Could not allocate message.");
635 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
636 log_error("Failed to issue method call: %s", bus_error_message(&error));
641 if (!dbus_message_iter_init(reply, &iter) ||
642 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
643 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
644 log_error("Failed to parse reply.");
649 printf("digraph systemd {\n");
651 dbus_message_iter_recurse(&iter, &sub);
652 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
653 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
655 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
656 log_error("Failed to parse reply.");
661 dbus_message_iter_recurse(&sub, &sub2);
663 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
664 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
665 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
666 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
667 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
668 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
669 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
670 log_error("Failed to parse reply.");
675 if ((r = dot_one(bus, id, unit_path)) < 0)
678 /* printf("\t\"%s\";\n", id); */
679 dbus_message_iter_next(&sub);
684 log_info(" Color legend: black = Requires\n"
685 " dark blue = Requisite\n"
686 " dark grey = Wants\n"
690 if (isatty(fileno(stdout)))
691 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
692 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
698 dbus_message_unref(m);
701 dbus_message_unref(reply);
703 dbus_error_free(&error);
708 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
709 DBusMessage *m = NULL, *reply = NULL;
712 DBusMessageIter iter, sub, sub2;
715 dbus_error_init(&error);
719 if (!(m = dbus_message_new_method_call(
720 "org.freedesktop.systemd1",
721 "/org/freedesktop/systemd1",
722 "org.freedesktop.systemd1.Manager",
724 log_error("Could not allocate message.");
728 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
729 log_error("Failed to issue method call: %s", bus_error_message(&error));
734 if (!dbus_message_iter_init(reply, &iter) ||
735 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
736 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
737 log_error("Failed to parse reply.");
742 dbus_message_iter_recurse(&iter, &sub);
744 if (isatty(STDOUT_FILENO))
745 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
747 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
748 const char *name, *type, *state, *job_path, *unit_path;
752 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
753 log_error("Failed to parse reply.");
758 dbus_message_iter_recurse(&sub, &sub2);
760 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
761 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
762 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
763 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
764 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
765 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
766 log_error("Failed to parse reply.");
771 e = arg_full ? NULL : ellipsize(name, 25, 33);
772 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
777 dbus_message_iter_next(&sub);
780 if (isatty(STDOUT_FILENO))
781 printf("\n%u jobs listed.\n", k);
787 dbus_message_unref(m);
790 dbus_message_unref(reply);
792 dbus_error_free(&error);
797 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
798 DBusMessage *m = NULL, *reply = NULL;
803 dbus_error_init(&error);
808 for (i = 1; i < n; i++) {
810 if (!(m = dbus_message_new_method_call(
811 "org.freedesktop.systemd1",
812 "/org/freedesktop/systemd1",
813 "org.freedesktop.systemd1.Manager",
815 log_error("Could not allocate message.");
820 if (!dbus_message_append_args(m,
821 DBUS_TYPE_STRING, &args[i],
822 DBUS_TYPE_INVALID)) {
823 log_error("Could not append arguments to message.");
828 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
829 log_error("Failed to issue method call: %s", bus_error_message(&error));
834 dbus_message_unref(m);
835 dbus_message_unref(reply);
844 dbus_message_unref(m);
847 dbus_message_unref(reply);
849 dbus_error_free(&error);
854 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
855 DBusMessage *m = NULL, *reply = NULL;
860 dbus_error_init(&error);
866 return daemon_reload(bus, args, n);
868 for (i = 1; i < n; i++) {
872 if (!(m = dbus_message_new_method_call(
873 "org.freedesktop.systemd1",
874 "/org/freedesktop/systemd1",
875 "org.freedesktop.systemd1.Manager",
877 log_error("Could not allocate message.");
882 if ((r = safe_atou(args[i], &id)) < 0) {
883 log_error("Failed to parse job id: %s", strerror(-r));
887 assert_cc(sizeof(uint32_t) == sizeof(id));
888 if (!dbus_message_append_args(m,
889 DBUS_TYPE_UINT32, &id,
890 DBUS_TYPE_INVALID)) {
891 log_error("Could not append arguments to message.");
896 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
897 log_error("Failed to issue method call: %s", bus_error_message(&error));
902 if (!dbus_message_get_args(reply, &error,
903 DBUS_TYPE_OBJECT_PATH, &path,
904 DBUS_TYPE_INVALID)) {
905 log_error("Failed to parse reply: %s", bus_error_message(&error));
910 dbus_message_unref(m);
911 if (!(m = dbus_message_new_method_call(
912 "org.freedesktop.systemd1",
914 "org.freedesktop.systemd1.Job",
916 log_error("Could not allocate message.");
921 dbus_message_unref(reply);
922 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
923 log_error("Failed to issue method call: %s", bus_error_message(&error));
928 dbus_message_unref(m);
929 dbus_message_unref(reply);
937 dbus_message_unref(m);
940 dbus_message_unref(reply);
942 dbus_error_free(&error);
947 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
948 DBusMessage *m = NULL, *reply = NULL;
949 dbus_bool_t b = FALSE;
950 DBusMessageIter iter, sub;
952 *interface = "org.freedesktop.systemd1.Unit",
953 *property = "NeedDaemonReload",
956 /* We ignore all errors here, since this is used to show a warning only */
958 if (!(m = dbus_message_new_method_call(
959 "org.freedesktop.systemd1",
960 "/org/freedesktop/systemd1",
961 "org.freedesktop.systemd1.Manager",
965 if (!dbus_message_append_args(m,
966 DBUS_TYPE_STRING, &unit,
970 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
973 if (!dbus_message_get_args(reply, NULL,
974 DBUS_TYPE_OBJECT_PATH, &path,
978 dbus_message_unref(m);
979 if (!(m = dbus_message_new_method_call(
980 "org.freedesktop.systemd1",
982 "org.freedesktop.DBus.Properties",
986 if (!dbus_message_append_args(m,
987 DBUS_TYPE_STRING, &interface,
988 DBUS_TYPE_STRING, &property,
989 DBUS_TYPE_INVALID)) {
993 dbus_message_unref(reply);
994 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
997 if (!dbus_message_iter_init(reply, &iter) ||
998 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1001 dbus_message_iter_recurse(&iter, &sub);
1003 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1006 dbus_message_iter_get_basic(&sub, &b);
1010 dbus_message_unref(m);
1013 dbus_message_unref(reply);
1018 typedef struct WaitData {
1023 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1031 dbus_error_init(&error);
1033 log_debug("Got D-Bus request: %s.%s() on %s",
1034 dbus_message_get_interface(message),
1035 dbus_message_get_member(message),
1036 dbus_message_get_path(message));
1038 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1039 log_error("Warning! D-Bus connection terminated.");
1040 dbus_connection_close(connection);
1042 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1045 dbus_bool_t success = true;
1047 if (!dbus_message_get_args(message, &error,
1048 DBUS_TYPE_UINT32, &id,
1049 DBUS_TYPE_OBJECT_PATH, &path,
1050 DBUS_TYPE_BOOLEAN, &success,
1052 log_error("Failed to parse message: %s", bus_error_message(&error));
1056 if ((p = set_remove(d->set, (char*) path)))
1064 dbus_error_free(&error);
1065 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1068 static int enable_wait_for_jobs(DBusConnection *bus) {
1076 dbus_error_init(&error);
1077 dbus_bus_add_match(bus,
1079 "sender='org.freedesktop.systemd1',"
1080 "interface='org.freedesktop.systemd1.Manager',"
1081 "member='JobRemoved',"
1082 "path='/org/freedesktop/systemd1'",
1085 if (dbus_error_is_set(&error)) {
1086 log_error("Failed to add match: %s", bus_error_message(&error));
1087 dbus_error_free(&error);
1091 /* This is slightly dirty, since we don't undo the match registrations. */
1095 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1106 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1107 log_error("Failed to add filter.");
1112 while (!set_isempty(s) &&
1113 dbus_connection_read_write_dispatch(bus, -1))
1116 if (!arg_quiet && d.failed)
1117 log_error("Job failed, see system logs for details.");
1119 r = d.failed ? -EIO : 0;
1122 /* This is slightly dirty, since we don't undo the filter registration. */
1127 static int start_unit_one(
1128 DBusConnection *bus,
1135 DBusMessage *m = NULL, *reply = NULL;
1144 assert(arg_no_block || s);
1146 if (!(m = dbus_message_new_method_call(
1147 "org.freedesktop.systemd1",
1148 "/org/freedesktop/systemd1",
1149 "org.freedesktop.systemd1.Manager",
1151 log_error("Could not allocate message.");
1156 if (!dbus_message_append_args(m,
1157 DBUS_TYPE_STRING, &name,
1158 DBUS_TYPE_STRING, &mode,
1159 DBUS_TYPE_INVALID)) {
1160 log_error("Could not append arguments to message.");
1165 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1167 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1168 /* There's always a fallback possible for
1169 * legacy actions. */
1174 log_error("Failed to issue method call: %s", bus_error_message(error));
1179 if (!dbus_message_get_args(reply, error,
1180 DBUS_TYPE_OBJECT_PATH, &path,
1181 DBUS_TYPE_INVALID)) {
1182 log_error("Failed to parse reply: %s", bus_error_message(error));
1187 if (need_daemon_reload(bus, name))
1188 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1189 arg_session ? "--session" : "--system");
1191 if (!arg_no_block) {
1194 if (!(p = strdup(path))) {
1195 log_error("Failed to duplicate path.");
1200 if ((r = set_put(s, p)) < 0) {
1202 log_error("Failed to add path to set.");
1211 dbus_message_unref(m);
1214 dbus_message_unref(reply);
1219 static enum action verb_to_action(const char *verb) {
1220 if (streq(verb, "halt"))
1222 else if (streq(verb, "poweroff"))
1223 return ACTION_POWEROFF;
1224 else if (streq(verb, "reboot"))
1225 return ACTION_REBOOT;
1226 else if (streq(verb, "kexec"))
1227 return ACTION_KEXEC;
1228 else if (streq(verb, "rescue"))
1229 return ACTION_RESCUE;
1230 else if (streq(verb, "emergency"))
1231 return ACTION_EMERGENCY;
1232 else if (streq(verb, "default"))
1233 return ACTION_DEFAULT;
1234 else if (streq(verb, "exit"))
1237 return ACTION_INVALID;
1240 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1242 static const char * const table[_ACTION_MAX] = {
1243 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1244 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1245 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1246 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1247 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1248 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1249 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1250 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1251 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1252 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1253 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1254 [ACTION_EXIT] = SPECIAL_EXIT_TARGET
1259 const char *method, *mode, *one_name;
1263 dbus_error_init(&error);
1267 if (arg_action == ACTION_SYSTEMCTL) {
1269 streq(args[0], "stop") ? "StopUnit" :
1270 streq(args[0], "reload") ? "ReloadUnit" :
1271 streq(args[0], "restart") ? "RestartUnit" :
1272 streq(args[0], "try-restart") ||
1273 streq(args[0], "condrestart") ? "TryRestartUnit" :
1274 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1275 streq(args[0], "reload-or-try-restart") ||
1276 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1280 (streq(args[0], "isolate") ||
1281 streq(args[0], "rescue") ||
1282 streq(args[0], "emergency")) ? "isolate" :
1286 one_name = table[verb_to_action(args[0])];
1289 assert(arg_action < ELEMENTSOF(table));
1290 assert(table[arg_action]);
1292 method = "StartUnit";
1294 mode = (arg_action == ACTION_EMERGENCY ||
1295 arg_action == ACTION_RESCUE ||
1296 arg_action == ACTION_RUNLEVEL2 ||
1297 arg_action == ACTION_RUNLEVEL3 ||
1298 arg_action == ACTION_RUNLEVEL4 ||
1299 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1301 one_name = table[arg_action];
1304 if (!arg_no_block) {
1305 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1306 log_error("Could not watch jobs: %s", strerror(-ret));
1310 if (!(s = set_new(string_hash_func, string_compare_func))) {
1311 log_error("Failed to allocate set.");
1318 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1321 for (i = 1; i < n; i++)
1322 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1323 ret = translate_bus_error_to_exit_status(r, &error);
1324 dbus_error_free(&error);
1329 if ((r = wait_for_jobs(bus, s)) < 0) {
1338 dbus_error_free(&error);
1343 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1350 (streq(args[0], "halt") ||
1351 streq(args[0], "poweroff") ||
1352 streq(args[0], "reboot") ||
1353 streq(args[0], "kexec") ||
1354 streq(args[0], "exit")))
1355 return daemon_reload(bus, args, n);
1357 r = start_unit(bus, args, n);
1360 warn_wall(verb_to_action(args[0]));
1365 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1366 DBusMessage *m = NULL, *reply = NULL;
1368 *interface = "org.freedesktop.systemd1.Unit",
1369 *property = "ActiveState";
1370 int r = 3; /* According to LSB: "program is not running" */
1377 dbus_error_init(&error);
1379 for (i = 1; i < n; i++) {
1380 const char *path = NULL;
1382 DBusMessageIter iter, sub;
1384 if (!(m = dbus_message_new_method_call(
1385 "org.freedesktop.systemd1",
1386 "/org/freedesktop/systemd1",
1387 "org.freedesktop.systemd1.Manager",
1389 log_error("Could not allocate message.");
1394 if (!dbus_message_append_args(m,
1395 DBUS_TYPE_STRING, &args[i],
1396 DBUS_TYPE_INVALID)) {
1397 log_error("Could not append arguments to message.");
1402 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1404 /* Hmm, cannot figure out anything about this unit... */
1408 dbus_error_free(&error);
1412 if (!dbus_message_get_args(reply, &error,
1413 DBUS_TYPE_OBJECT_PATH, &path,
1414 DBUS_TYPE_INVALID)) {
1415 log_error("Failed to parse reply: %s", bus_error_message(&error));
1420 dbus_message_unref(m);
1421 if (!(m = dbus_message_new_method_call(
1422 "org.freedesktop.systemd1",
1424 "org.freedesktop.DBus.Properties",
1426 log_error("Could not allocate message.");
1431 if (!dbus_message_append_args(m,
1432 DBUS_TYPE_STRING, &interface,
1433 DBUS_TYPE_STRING, &property,
1434 DBUS_TYPE_INVALID)) {
1435 log_error("Could not append arguments to message.");
1440 dbus_message_unref(reply);
1441 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1442 log_error("Failed to issue method call: %s", bus_error_message(&error));
1447 if (!dbus_message_iter_init(reply, &iter) ||
1448 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1449 log_error("Failed to parse reply.");
1454 dbus_message_iter_recurse(&iter, &sub);
1456 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1457 log_error("Failed to parse reply.");
1462 dbus_message_iter_get_basic(&sub, &state);
1467 if (streq(state, "active") || streq(state, "reloading"))
1470 dbus_message_unref(m);
1471 dbus_message_unref(reply);
1477 dbus_message_unref(m);
1480 dbus_message_unref(reply);
1482 dbus_error_free(&error);
1487 typedef struct ExecStatusInfo {
1493 usec_t start_timestamp;
1494 usec_t exit_timestamp;
1499 LIST_FIELDS(struct ExecStatusInfo, exec);
1502 static void exec_status_info_free(ExecStatusInfo *i) {
1510 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1511 uint64_t start_timestamp, exit_timestamp;
1512 DBusMessageIter sub2, sub3;
1516 int32_t code, status;
1522 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1525 dbus_message_iter_recurse(sub, &sub2);
1527 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1530 if (!(i->path = strdup(path)))
1533 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1534 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1538 dbus_message_iter_recurse(&sub2, &sub3);
1539 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1540 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1541 dbus_message_iter_next(&sub3);
1546 if (!(i->argv = new0(char*, n+1)))
1550 dbus_message_iter_recurse(&sub2, &sub3);
1551 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1554 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1555 dbus_message_iter_get_basic(&sub3, &s);
1556 dbus_message_iter_next(&sub3);
1558 if (!(i->argv[n++] = strdup(s)))
1562 if (!dbus_message_iter_next(&sub2) ||
1563 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1564 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1565 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1566 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1567 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1568 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1572 i->start_timestamp = (usec_t) start_timestamp;
1573 i->exit_timestamp = (usec_t) exit_timestamp;
1574 i->pid = (pid_t) pid;
1581 typedef struct UnitStatusInfo {
1583 const char *load_state;
1584 const char *active_state;
1585 const char *sub_state;
1587 const char *description;
1588 const char *following;
1591 const char *default_control_group;
1593 usec_t inactive_exit_timestamp;
1594 usec_t active_enter_timestamp;
1595 usec_t active_exit_timestamp;
1596 usec_t inactive_enter_timestamp;
1598 bool need_daemon_reload;
1603 const char *status_text;
1605 #ifdef HAVE_SYSV_COMPAT
1609 usec_t start_timestamp;
1610 usec_t exit_timestamp;
1612 int exit_code, exit_status;
1615 unsigned n_accepted;
1616 unsigned n_connections;
1620 const char *sysfs_path;
1622 /* Mount, Automount */
1628 LIST_HEAD(ExecStatusInfo, exec);
1631 static void print_status_info(UnitStatusInfo *i) {
1633 const char *on, *off, *ss;
1635 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1636 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1640 /* This shows pretty information about a unit. See
1641 * print_property() for a low-level property printer */
1643 printf("%s", strna(i->id));
1645 if (i->description && !streq_ptr(i->id, i->description))
1646 printf(" - %s", i->description);
1651 printf("\t Follow: unit currently follows state of %s\n", i->following);
1653 if (streq_ptr(i->load_state, "failed") ||
1654 streq_ptr(i->load_state, "banned")) {
1655 on = ansi_highlight(true);
1656 off = ansi_highlight(false);
1661 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1663 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1665 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1667 if (streq_ptr(i->active_state, "failed")) {
1668 on = ansi_highlight(true);
1669 off = ansi_highlight(false);
1670 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1671 on = ansi_highlight_green(true);
1672 off = ansi_highlight_green(false);
1677 printf("\t Active: %s%s (%s)%s",
1679 strna(i->active_state),
1683 printf("\t Active: %s%s%s",
1685 strna(i->active_state),
1688 timestamp = (streq_ptr(i->active_state, "active") ||
1689 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1690 (streq_ptr(i->active_state, "inactive") ||
1691 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1692 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1693 i->active_exit_timestamp;
1695 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1696 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1699 printf(" since %s; %s\n", s2, s1);
1701 printf(" since %s\n", s2);
1706 printf("\t Device: %s\n", i->sysfs_path);
1708 printf("\t Where: %s\n", i->where);
1710 printf("\t What: %s\n", i->what);
1713 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1715 LIST_FOREACH(exec, p, i->exec) {
1718 /* Only show exited processes here */
1722 t = strv_join(p->argv, " ");
1723 printf("\t Process: %u (%s, code=%s, ", p->pid, strna(t), sigchld_code_to_string(p->code));
1726 if (p->code == CLD_EXITED) {
1729 printf("status=%i", p->status);
1731 #ifdef HAVE_SYSV_COMPAT
1732 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1734 if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1739 printf("signal=%s", signal_to_string(p->status));
1742 if (i->main_pid == p->pid &&
1743 i->start_timestamp == p->start_timestamp &&
1744 i->exit_timestamp == p->start_timestamp)
1745 /* Let's not show this twice */
1748 if (p->pid == i->control_pid)
1752 if (i->main_pid > 0 || i->control_pid > 0) {
1755 if (i->main_pid > 0) {
1756 printf("Main PID: %u", (unsigned) i->main_pid);
1760 get_process_name(i->main_pid, &t);
1765 } else if (i->exit_code > 0) {
1766 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1768 if (i->exit_code == CLD_EXITED) {
1771 printf("status=%i", i->exit_status);
1773 #ifdef HAVE_SYSV_COMPAT
1774 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1776 if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
1781 printf("signal=%s", signal_to_string(i->exit_status));
1786 if (i->main_pid > 0 && i->control_pid > 0)
1789 if (i->control_pid > 0) {
1792 printf(" Control: %u", (unsigned) i->control_pid);
1794 get_process_name(i->control_pid, &t);
1805 printf("\t Status: \"%s\"\n", i->status_text);
1807 if (i->default_control_group) {
1810 printf("\t CGroup: %s\n", i->default_control_group);
1812 if ((c = columns()) > 18)
1817 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
1820 if (i->need_daemon_reload)
1821 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1822 ansi_highlight(true),
1823 ansi_highlight(false),
1824 arg_session ? "--session" : "--system");
1827 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1829 switch (dbus_message_iter_get_arg_type(iter)) {
1831 case DBUS_TYPE_STRING: {
1834 dbus_message_iter_get_basic(iter, &s);
1837 if (streq(name, "Id"))
1839 else if (streq(name, "LoadState"))
1841 else if (streq(name, "ActiveState"))
1842 i->active_state = s;
1843 else if (streq(name, "SubState"))
1845 else if (streq(name, "Description"))
1847 else if (streq(name, "FragmentPath"))
1849 #ifdef HAVE_SYSV_COMPAT
1850 else if (streq(name, "SysVPath")) {
1855 else if (streq(name, "DefaultControlGroup"))
1856 i->default_control_group = s;
1857 else if (streq(name, "StatusText"))
1859 else if (streq(name, "SysFSPath"))
1861 else if (streq(name, "Where"))
1863 else if (streq(name, "What"))
1865 else if (streq(name, "Following"))
1872 case DBUS_TYPE_BOOLEAN: {
1875 dbus_message_iter_get_basic(iter, &b);
1877 if (streq(name, "Accept"))
1879 else if (streq(name, "NeedDaemonReload"))
1880 i->need_daemon_reload = b;
1885 case DBUS_TYPE_UINT32: {
1888 dbus_message_iter_get_basic(iter, &u);
1890 if (streq(name, "MainPID")) {
1892 i->main_pid = (pid_t) u;
1895 } else if (streq(name, "ControlPID"))
1896 i->control_pid = (pid_t) u;
1897 else if (streq(name, "ExecMainPID")) {
1899 i->main_pid = (pid_t) u;
1900 } else if (streq(name, "NAccepted"))
1902 else if (streq(name, "NConnections"))
1903 i->n_connections = u;
1908 case DBUS_TYPE_INT32: {
1911 dbus_message_iter_get_basic(iter, &j);
1913 if (streq(name, "ExecMainCode"))
1914 i->exit_code = (int) j;
1915 else if (streq(name, "ExecMainStatus"))
1916 i->exit_status = (int) j;
1921 case DBUS_TYPE_UINT64: {
1924 dbus_message_iter_get_basic(iter, &u);
1926 if (streq(name, "ExecMainStartTimestamp"))
1927 i->start_timestamp = (usec_t) u;
1928 else if (streq(name, "ExecMainExitTimestamp"))
1929 i->exit_timestamp = (usec_t) u;
1930 else if (streq(name, "ActiveEnterTimestamp"))
1931 i->active_enter_timestamp = (usec_t) u;
1932 else if (streq(name, "InactiveEnterTimestamp"))
1933 i->inactive_enter_timestamp = (usec_t) u;
1934 else if (streq(name, "InactiveExitTimestamp"))
1935 i->inactive_exit_timestamp = (usec_t) u;
1936 else if (streq(name, "ActiveExitTimestamp"))
1937 i->active_exit_timestamp = (usec_t) u;
1942 case DBUS_TYPE_ARRAY: {
1944 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
1945 startswith(name, "Exec")) {
1946 DBusMessageIter sub;
1948 dbus_message_iter_recurse(iter, &sub);
1949 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1950 ExecStatusInfo *info;
1953 if (!(info = new0(ExecStatusInfo, 1)))
1956 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
1961 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
1963 dbus_message_iter_next(&sub);
1974 static int print_property(const char *name, DBusMessageIter *iter) {
1978 /* This is a low-level property printer, see
1979 * print_status_info() for the nicer output */
1981 if (arg_property && !strv_find(arg_property, name))
1984 switch (dbus_message_iter_get_arg_type(iter)) {
1986 case DBUS_TYPE_STRING: {
1988 dbus_message_iter_get_basic(iter, &s);
1990 if (arg_all || s[0])
1991 printf("%s=%s\n", name, s);
1996 case DBUS_TYPE_BOOLEAN: {
1998 dbus_message_iter_get_basic(iter, &b);
1999 printf("%s=%s\n", name, yes_no(b));
2004 case DBUS_TYPE_UINT64: {
2006 dbus_message_iter_get_basic(iter, &u);
2008 /* Yes, heuristics! But we can change this check
2009 * should it turn out to not be sufficient */
2011 if (strstr(name, "Timestamp")) {
2012 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
2014 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
2015 printf("%s=%s\n", name, strempty(t));
2016 } else if (strstr(name, "USec")) {
2017 char timespan[FORMAT_TIMESPAN_MAX];
2019 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
2021 printf("%s=%llu\n", name, (unsigned long long) u);
2026 case DBUS_TYPE_UINT32: {
2028 dbus_message_iter_get_basic(iter, &u);
2030 if (strstr(name, "UMask") || strstr(name, "Mode"))
2031 printf("%s=%04o\n", name, u);
2033 printf("%s=%u\n", name, (unsigned) u);
2038 case DBUS_TYPE_INT32: {
2040 dbus_message_iter_get_basic(iter, &i);
2042 printf("%s=%i\n", name, (int) i);
2046 case DBUS_TYPE_DOUBLE: {
2048 dbus_message_iter_get_basic(iter, &d);
2050 printf("%s=%g\n", name, d);
2054 case DBUS_TYPE_STRUCT: {
2055 DBusMessageIter sub;
2056 dbus_message_iter_recurse(iter, &sub);
2058 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2061 dbus_message_iter_get_basic(&sub, &u);
2064 printf("%s=%u\n", name, (unsigned) u);
2066 printf("%s=\n", name);
2069 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2072 dbus_message_iter_get_basic(&sub, &s);
2074 if (arg_all || s[0])
2075 printf("%s=%s\n", name, s);
2083 case DBUS_TYPE_ARRAY:
2085 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2086 DBusMessageIter sub;
2089 dbus_message_iter_recurse(iter, &sub);
2091 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2092 printf("%s=", name);
2094 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2097 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2098 dbus_message_iter_get_basic(&sub, &s);
2099 printf("%s%s", space ? " " : "", s);
2102 dbus_message_iter_next(&sub);
2110 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2111 DBusMessageIter sub;
2113 dbus_message_iter_recurse(iter, &sub);
2115 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2116 printf("%s=", name);
2118 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2121 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2122 dbus_message_iter_get_basic(&sub, &u);
2125 dbus_message_iter_next(&sub);
2133 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2134 DBusMessageIter sub, sub2;
2136 dbus_message_iter_recurse(iter, &sub);
2137 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2138 const char *type, *path;
2140 dbus_message_iter_recurse(&sub, &sub2);
2142 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2143 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2144 printf("%s=%s\n", type, path);
2146 dbus_message_iter_next(&sub);
2151 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2152 DBusMessageIter sub, sub2;
2154 dbus_message_iter_recurse(iter, &sub);
2155 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2157 uint64_t value, next_elapse;
2159 dbus_message_iter_recurse(&sub, &sub2);
2161 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2162 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2163 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2164 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2166 printf("%s={ value=%s ; next_elapse=%s }\n",
2168 format_timespan(timespan1, sizeof(timespan1), value),
2169 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2172 dbus_message_iter_next(&sub);
2177 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2178 DBusMessageIter sub;
2180 dbus_message_iter_recurse(iter, &sub);
2181 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2182 ExecStatusInfo info;
2185 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2186 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2189 t = strv_join(info.argv, " ");
2191 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2195 yes_no(info.ignore),
2196 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2197 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2198 (unsigned) info. pid,
2199 sigchld_code_to_string(info.code),
2201 info.code == CLD_EXITED ? "" : "/",
2202 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2208 strv_free(info.argv);
2210 dbus_message_iter_next(&sub);
2220 printf("%s=[unprintable]\n", name);
2225 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2226 DBusMessage *m = NULL, *reply = NULL;
2227 const char *interface = "";
2230 DBusMessageIter iter, sub, sub2, sub3;
2231 UnitStatusInfo info;
2239 dbus_error_init(&error);
2241 if (!(m = dbus_message_new_method_call(
2242 "org.freedesktop.systemd1",
2244 "org.freedesktop.DBus.Properties",
2246 log_error("Could not allocate message.");
2251 if (!dbus_message_append_args(m,
2252 DBUS_TYPE_STRING, &interface,
2253 DBUS_TYPE_INVALID)) {
2254 log_error("Could not append arguments to message.");
2259 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2260 log_error("Failed to issue method call: %s", bus_error_message(&error));
2265 if (!dbus_message_iter_init(reply, &iter) ||
2266 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2267 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2268 log_error("Failed to parse reply.");
2273 dbus_message_iter_recurse(&iter, &sub);
2280 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2283 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2284 log_error("Failed to parse reply.");
2289 dbus_message_iter_recurse(&sub, &sub2);
2291 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2292 log_error("Failed to parse reply.");
2297 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2298 log_error("Failed to parse reply.");
2303 dbus_message_iter_recurse(&sub2, &sub3);
2305 if (show_properties)
2306 r = print_property(name, &sub3);
2308 r = status_property(name, &sub3, &info);
2311 log_error("Failed to parse reply.");
2316 dbus_message_iter_next(&sub);
2321 if (!show_properties)
2322 print_status_info(&info);
2324 if (!streq_ptr(info.active_state, "active") &&
2325 !streq_ptr(info.active_state, "reloading"))
2326 /* According to LSB: "program not running" */
2329 while ((p = info.exec)) {
2330 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2331 exec_status_info_free(p);
2336 dbus_message_unref(m);
2339 dbus_message_unref(reply);
2341 dbus_error_free(&error);
2346 static int show(DBusConnection *bus, char **args, unsigned n) {
2347 DBusMessage *m = NULL, *reply = NULL;
2351 bool show_properties, new_line = false;
2356 dbus_error_init(&error);
2358 show_properties = !streq(args[0], "status");
2360 if (show_properties && n <= 1) {
2361 /* If not argument is specified inspect the manager
2364 ret = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2368 for (i = 1; i < n; i++) {
2369 const char *path = NULL;
2372 if (safe_atou32(args[i], &id) < 0) {
2374 /* Interpret as unit name */
2376 if (!(m = dbus_message_new_method_call(
2377 "org.freedesktop.systemd1",
2378 "/org/freedesktop/systemd1",
2379 "org.freedesktop.systemd1.Manager",
2381 log_error("Could not allocate message.");
2386 if (!dbus_message_append_args(m,
2387 DBUS_TYPE_STRING, &args[i],
2388 DBUS_TYPE_INVALID)) {
2389 log_error("Could not append arguments to message.");
2394 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2396 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2397 log_error("Failed to issue method call: %s", bus_error_message(&error));
2402 dbus_error_free(&error);
2404 dbus_message_unref(m);
2405 if (!(m = dbus_message_new_method_call(
2406 "org.freedesktop.systemd1",
2407 "/org/freedesktop/systemd1",
2408 "org.freedesktop.systemd1.Manager",
2410 log_error("Could not allocate message.");
2415 if (!dbus_message_append_args(m,
2416 DBUS_TYPE_STRING, &args[i],
2417 DBUS_TYPE_INVALID)) {
2418 log_error("Could not append arguments to message.");
2423 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2424 log_error("Failed to issue method call: %s", bus_error_message(&error));
2426 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2427 ret = 4; /* According to LSB: "program or service status is unknown" */
2434 } else if (show_properties) {
2436 /* Interpret as job id */
2438 if (!(m = dbus_message_new_method_call(
2439 "org.freedesktop.systemd1",
2440 "/org/freedesktop/systemd1",
2441 "org.freedesktop.systemd1.Manager",
2443 log_error("Could not allocate message.");
2448 if (!dbus_message_append_args(m,
2449 DBUS_TYPE_UINT32, &id,
2450 DBUS_TYPE_INVALID)) {
2451 log_error("Could not append arguments to message.");
2456 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2457 log_error("Failed to issue method call: %s", bus_error_message(&error));
2463 /* Interpret as PID */
2465 if (!(m = dbus_message_new_method_call(
2466 "org.freedesktop.systemd1",
2467 "/org/freedesktop/systemd1",
2468 "org.freedesktop.systemd1.Manager",
2470 log_error("Could not allocate message.");
2475 if (!dbus_message_append_args(m,
2476 DBUS_TYPE_UINT32, &id,
2477 DBUS_TYPE_INVALID)) {
2478 log_error("Could not append arguments to message.");
2483 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2484 log_error("Failed to issue method call: %s", bus_error_message(&error));
2490 if (!dbus_message_get_args(reply, &error,
2491 DBUS_TYPE_OBJECT_PATH, &path,
2492 DBUS_TYPE_INVALID)) {
2493 log_error("Failed to parse reply: %s", bus_error_message(&error));
2498 if ((r = show_one(bus, path, show_properties, &new_line)) != 0)
2501 dbus_message_unref(m);
2502 dbus_message_unref(reply);
2508 dbus_message_unref(m);
2511 dbus_message_unref(reply);
2513 dbus_error_free(&error);
2518 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2520 DBusMessage *m = NULL, *reply = NULL;
2525 dbus_error_init(&error);
2527 log_debug("Got D-Bus request: %s.%s() on %s",
2528 dbus_message_get_interface(message),
2529 dbus_message_get_member(message),
2530 dbus_message_get_path(message));
2532 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2533 log_error("Warning! D-Bus connection terminated.");
2534 dbus_connection_close(connection);
2536 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2537 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2538 const char *id, *path;
2540 if (!dbus_message_get_args(message, &error,
2541 DBUS_TYPE_STRING, &id,
2542 DBUS_TYPE_OBJECT_PATH, &path,
2544 log_error("Failed to parse message: %s", bus_error_message(&error));
2545 else if (streq(dbus_message_get_member(message), "UnitNew"))
2546 printf("Unit %s added.\n", id);
2548 printf("Unit %s removed.\n", id);
2550 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2551 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2555 if (!dbus_message_get_args(message, &error,
2556 DBUS_TYPE_UINT32, &id,
2557 DBUS_TYPE_OBJECT_PATH, &path,
2559 log_error("Failed to parse message: %s", bus_error_message(&error));
2560 else if (streq(dbus_message_get_member(message), "JobNew"))
2561 printf("Job %u added.\n", id);
2563 printf("Job %u removed.\n", id);
2566 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2568 const char *path, *interface, *property = "Id";
2569 DBusMessageIter iter, sub;
2571 path = dbus_message_get_path(message);
2573 if (!dbus_message_get_args(message, &error,
2574 DBUS_TYPE_STRING, &interface,
2575 DBUS_TYPE_INVALID)) {
2576 log_error("Failed to parse message: %s", bus_error_message(&error));
2580 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2581 !streq(interface, "org.freedesktop.systemd1.Unit"))
2584 if (!(m = dbus_message_new_method_call(
2585 "org.freedesktop.systemd1",
2587 "org.freedesktop.DBus.Properties",
2589 log_error("Could not allocate message.");
2593 if (!dbus_message_append_args(m,
2594 DBUS_TYPE_STRING, &interface,
2595 DBUS_TYPE_STRING, &property,
2596 DBUS_TYPE_INVALID)) {
2597 log_error("Could not append arguments to message.");
2601 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2602 log_error("Failed to issue method call: %s", bus_error_message(&error));
2606 if (!dbus_message_iter_init(reply, &iter) ||
2607 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2608 log_error("Failed to parse reply.");
2612 dbus_message_iter_recurse(&iter, &sub);
2614 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2617 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2618 log_error("Failed to parse reply.");
2622 dbus_message_iter_get_basic(&sub, &id);
2623 printf("Unit %s changed.\n", id);
2627 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2628 log_error("Failed to parse reply.");
2632 dbus_message_iter_get_basic(&sub, &id);
2633 printf("Job %u changed.\n", id);
2639 dbus_message_unref(m);
2642 dbus_message_unref(reply);
2644 dbus_error_free(&error);
2645 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2649 dbus_message_unref(m);
2652 dbus_message_unref(reply);
2654 dbus_error_free(&error);
2655 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2658 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2659 DBusMessage *m = NULL, *reply = NULL;
2663 dbus_error_init(&error);
2666 dbus_bus_add_match(bus,
2668 "sender='org.freedesktop.systemd1',"
2669 "interface='org.freedesktop.systemd1.Manager',"
2670 "path='/org/freedesktop/systemd1'",
2673 if (dbus_error_is_set(&error)) {
2674 log_error("Failed to add match: %s", bus_error_message(&error));
2679 dbus_bus_add_match(bus,
2681 "sender='org.freedesktop.systemd1',"
2682 "interface='org.freedesktop.DBus.Properties',"
2683 "member='PropertiesChanged'",
2686 if (dbus_error_is_set(&error)) {
2687 log_error("Failed to add match: %s", bus_error_message(&error));
2693 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2694 log_error("Failed to add filter.");
2699 if (!(m = dbus_message_new_method_call(
2700 "org.freedesktop.systemd1",
2701 "/org/freedesktop/systemd1",
2702 "org.freedesktop.systemd1.Manager",
2704 log_error("Could not allocate message.");
2709 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2710 log_error("Failed to issue method call: %s", bus_error_message(&error));
2715 while (dbus_connection_read_write_dispatch(bus, -1))
2722 /* This is slightly dirty, since we don't undo the filter or the matches. */
2725 dbus_message_unref(m);
2728 dbus_message_unref(reply);
2730 dbus_error_free(&error);
2735 static int dump(DBusConnection *bus, char **args, unsigned n) {
2736 DBusMessage *m = NULL, *reply = NULL;
2741 dbus_error_init(&error);
2743 if (!(m = dbus_message_new_method_call(
2744 "org.freedesktop.systemd1",
2745 "/org/freedesktop/systemd1",
2746 "org.freedesktop.systemd1.Manager",
2748 log_error("Could not allocate message.");
2752 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2753 log_error("Failed to issue method call: %s", bus_error_message(&error));
2758 if (!dbus_message_get_args(reply, &error,
2759 DBUS_TYPE_STRING, &text,
2760 DBUS_TYPE_INVALID)) {
2761 log_error("Failed to parse reply: %s", bus_error_message(&error));
2766 fputs(text, stdout);
2772 dbus_message_unref(m);
2775 dbus_message_unref(reply);
2777 dbus_error_free(&error);
2782 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2783 DBusMessage *m = NULL, *reply = NULL;
2786 const char *name = "", *path, *id;
2787 dbus_bool_t cleanup = FALSE;
2788 DBusMessageIter iter, sub;
2790 *interface = "org.freedesktop.systemd1.Unit",
2793 dbus_error_init(&error);
2795 if (!(m = dbus_message_new_method_call(
2796 "org.freedesktop.systemd1",
2797 "/org/freedesktop/systemd1",
2798 "org.freedesktop.systemd1.Manager",
2799 "CreateSnapshot"))) {
2800 log_error("Could not allocate message.");
2807 if (!dbus_message_append_args(m,
2808 DBUS_TYPE_STRING, &name,
2809 DBUS_TYPE_BOOLEAN, &cleanup,
2810 DBUS_TYPE_INVALID)) {
2811 log_error("Could not append arguments to message.");
2816 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2817 log_error("Failed to issue method call: %s", bus_error_message(&error));
2822 if (!dbus_message_get_args(reply, &error,
2823 DBUS_TYPE_OBJECT_PATH, &path,
2824 DBUS_TYPE_INVALID)) {
2825 log_error("Failed to parse reply: %s", bus_error_message(&error));
2830 dbus_message_unref(m);
2831 if (!(m = dbus_message_new_method_call(
2832 "org.freedesktop.systemd1",
2834 "org.freedesktop.DBus.Properties",
2836 log_error("Could not allocate message.");
2840 if (!dbus_message_append_args(m,
2841 DBUS_TYPE_STRING, &interface,
2842 DBUS_TYPE_STRING, &property,
2843 DBUS_TYPE_INVALID)) {
2844 log_error("Could not append arguments to message.");
2849 dbus_message_unref(reply);
2850 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2851 log_error("Failed to issue method call: %s", bus_error_message(&error));
2856 if (!dbus_message_iter_init(reply, &iter) ||
2857 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2858 log_error("Failed to parse reply.");
2863 dbus_message_iter_recurse(&iter, &sub);
2865 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2866 log_error("Failed to parse reply.");
2871 dbus_message_iter_get_basic(&sub, &id);
2879 dbus_message_unref(m);
2882 dbus_message_unref(reply);
2884 dbus_error_free(&error);
2889 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2890 DBusMessage *m = NULL, *reply = NULL;
2898 dbus_error_init(&error);
2900 for (i = 1; i < n; i++) {
2901 const char *path = NULL;
2903 if (!(m = dbus_message_new_method_call(
2904 "org.freedesktop.systemd1",
2905 "/org/freedesktop/systemd1",
2906 "org.freedesktop.systemd1.Manager",
2908 log_error("Could not allocate message.");
2913 if (!dbus_message_append_args(m,
2914 DBUS_TYPE_STRING, &args[i],
2915 DBUS_TYPE_INVALID)) {
2916 log_error("Could not append arguments to message.");
2921 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2922 log_error("Failed to issue method call: %s", bus_error_message(&error));
2927 if (!dbus_message_get_args(reply, &error,
2928 DBUS_TYPE_OBJECT_PATH, &path,
2929 DBUS_TYPE_INVALID)) {
2930 log_error("Failed to parse reply: %s", bus_error_message(&error));
2935 dbus_message_unref(m);
2936 if (!(m = dbus_message_new_method_call(
2937 "org.freedesktop.systemd1",
2939 "org.freedesktop.systemd1.Snapshot",
2941 log_error("Could not allocate message.");
2946 dbus_message_unref(reply);
2947 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2948 log_error("Failed to issue method call: %s", bus_error_message(&error));
2953 dbus_message_unref(m);
2954 dbus_message_unref(reply);
2962 dbus_message_unref(m);
2965 dbus_message_unref(reply);
2967 dbus_error_free(&error);
2972 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2973 DBusMessage *m = NULL, *reply = NULL;
2978 dbus_error_init(&error);
2980 if (arg_action == ACTION_RELOAD)
2982 else if (arg_action == ACTION_REEXEC)
2983 method = "Reexecute";
2985 assert(arg_action == ACTION_SYSTEMCTL);
2988 streq(args[0], "clear-jobs") ||
2989 streq(args[0], "cancel") ? "ClearJobs" :
2990 streq(args[0], "daemon-reexec") ? "Reexecute" :
2991 streq(args[0], "reset-failed") ? "ResetFailed" :
2992 streq(args[0], "halt") ? "Halt" :
2993 streq(args[0], "poweroff") ? "PowerOff" :
2994 streq(args[0], "reboot") ? "Reboot" :
2995 streq(args[0], "kexec") ? "KExec" :
2996 streq(args[0], "exit") ? "Exit" :
2997 /* "daemon-reload" */ "Reload";
3000 if (!(m = dbus_message_new_method_call(
3001 "org.freedesktop.systemd1",
3002 "/org/freedesktop/systemd1",
3003 "org.freedesktop.systemd1.Manager",
3005 log_error("Could not allocate message.");
3009 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3011 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3012 /* There's always a fallback possible for
3013 * legacy actions. */
3018 log_error("Failed to issue method call: %s", bus_error_message(&error));
3027 dbus_message_unref(m);
3030 dbus_message_unref(reply);
3032 dbus_error_free(&error);
3037 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3038 DBusMessage *m = NULL, *reply = NULL;
3044 dbus_error_init(&error);
3047 return daemon_reload(bus, args, n);
3049 for (i = 1; i < n; i++) {
3051 if (!(m = dbus_message_new_method_call(
3052 "org.freedesktop.systemd1",
3053 "/org/freedesktop/systemd1",
3054 "org.freedesktop.systemd1.Manager",
3055 "ResetFailedUnit"))) {
3056 log_error("Could not allocate message.");
3061 if (!dbus_message_append_args(m,
3062 DBUS_TYPE_STRING, args + i,
3063 DBUS_TYPE_INVALID)) {
3064 log_error("Could not append arguments to message.");
3069 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3070 log_error("Failed to issue method call: %s", bus_error_message(&error));
3075 dbus_message_unref(m);
3076 dbus_message_unref(reply);
3084 dbus_message_unref(m);
3087 dbus_message_unref(reply);
3089 dbus_error_free(&error);
3094 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3095 DBusMessage *m = NULL, *reply = NULL;
3097 DBusMessageIter iter, sub, sub2;
3100 *interface = "org.freedesktop.systemd1.Manager",
3101 *property = "Environment";
3103 dbus_error_init(&error);
3105 if (!(m = dbus_message_new_method_call(
3106 "org.freedesktop.systemd1",
3107 "/org/freedesktop/systemd1",
3108 "org.freedesktop.DBus.Properties",
3110 log_error("Could not allocate message.");
3114 if (!dbus_message_append_args(m,
3115 DBUS_TYPE_STRING, &interface,
3116 DBUS_TYPE_STRING, &property,
3117 DBUS_TYPE_INVALID)) {
3118 log_error("Could not append arguments to message.");
3123 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3124 log_error("Failed to issue method call: %s", bus_error_message(&error));
3129 if (!dbus_message_iter_init(reply, &iter) ||
3130 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3131 log_error("Failed to parse reply.");
3136 dbus_message_iter_recurse(&iter, &sub);
3138 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3139 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3140 log_error("Failed to parse reply.");
3145 dbus_message_iter_recurse(&sub, &sub2);
3147 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3150 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3151 log_error("Failed to parse reply.");
3156 dbus_message_iter_get_basic(&sub2, &text);
3157 printf("%s\n", text);
3159 dbus_message_iter_next(&sub2);
3166 dbus_message_unref(m);
3169 dbus_message_unref(reply);
3171 dbus_error_free(&error);
3176 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3177 DBusMessage *m = NULL, *reply = NULL;
3181 DBusMessageIter iter, sub;
3184 dbus_error_init(&error);
3186 method = streq(args[0], "set-environment")
3188 : "UnsetEnvironment";
3190 if (!(m = dbus_message_new_method_call(
3191 "org.freedesktop.systemd1",
3192 "/org/freedesktop/systemd1",
3193 "org.freedesktop.systemd1.Manager",
3196 log_error("Could not allocate message.");
3200 dbus_message_iter_init_append(m, &iter);
3202 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3203 log_error("Could not append arguments to message.");
3208 for (i = 1; i < n; i++)
3209 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3210 log_error("Could not append arguments to message.");
3215 if (!dbus_message_iter_close_container(&iter, &sub)) {
3216 log_error("Could not append arguments to message.");
3221 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3222 log_error("Failed to issue method call: %s", bus_error_message(&error));
3231 dbus_message_unref(m);
3234 dbus_message_unref(reply);
3236 dbus_error_free(&error);
3249 static Hashmap *will_install = NULL, *have_installed = NULL;
3250 static Set *remove_symlinks_to = NULL;
3251 static unsigned n_symlinks = 0;
3253 static void install_info_free(InstallInfo *i) {
3258 strv_free(i->aliases);
3259 strv_free(i->wanted_by);
3263 static void install_info_hashmap_free(Hashmap *m) {
3266 while ((i = hashmap_steal_first(m)))
3267 install_info_free(i);
3272 static int install_info_add(const char *name) {
3276 assert(will_install);
3278 if (!unit_name_is_valid_no_type(name, true)) {
3279 log_warning("Unit name %s is not a valid unit name.", name);
3283 if (hashmap_get(have_installed, name) ||
3284 hashmap_get(will_install, name))
3287 if (!(i = new0(InstallInfo, 1))) {
3292 if (!(i->name = strdup(name))) {
3297 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3304 install_info_free(i);
3309 static int config_parse_also(
3310 const char *filename,
3312 const char *section,
3326 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3330 if (!(n = strndup(w, l)))
3333 if ((r = install_info_add(n)) < 0) {
3334 log_warning("Cannot install unit %s: %s", n, strerror(-r));
3345 static int mark_symlink_for_removal(const char *p) {
3350 assert(path_is_absolute(p));
3352 if (!remove_symlinks_to)
3355 if (!(n = strdup(p)))
3358 path_kill_slashes(n);
3360 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3362 return r == -EEXIST ? 0 : r;
3368 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3377 if (!(d = fdopendir(fd))) {
3378 close_nointr_nofail(fd);
3384 while ((de = readdir(d))) {
3385 bool is_dir = false, is_link = false;
3387 if (ignore_file(de->d_name))
3390 if (de->d_type == DT_LNK)
3392 else if (de->d_type == DT_DIR)
3394 else if (de->d_type == DT_UNKNOWN) {
3397 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3398 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3405 is_link = S_ISLNK(st.st_mode);
3406 is_dir = S_ISDIR(st.st_mode);
3414 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3415 log_error("Failed to open %s/%s: %m", root, de->d_name);
3422 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3423 log_error("Failed to allocate directory string.");
3424 close_nointr_nofail(nfd);
3429 /* This will close nfd, regardless whether it succeeds or not */
3430 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3436 } else if (is_link) {
3440 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3441 log_error("Failed to allocate symlink string.");
3446 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3447 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3455 if ((c = canonicalize_file_name(dest))) {
3456 /* This might fail if the destination
3457 * is already removed */
3463 path_kill_slashes(dest);
3464 if (set_get(remove_symlinks_to, dest)) {
3467 log_info("rm '%s'", p);
3469 if (unlink(p) < 0) {
3470 log_error("Cannot unlink symlink %s: %m", p);
3475 rmdir_parents(p, config_path);
3476 path_kill_slashes(p);
3478 if (!set_get(remove_symlinks_to, p)) {
3480 if ((r = mark_symlink_for_removal(p)) < 0) {
3499 static int remove_marked_symlinks(const char *config_path) {
3503 assert(config_path);
3505 if (set_size(remove_symlinks_to) <= 0)
3508 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3515 if ((cfd = dup(fd)) < 0) {
3520 /* This takes possession of cfd and closes it */
3521 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3527 close_nointr_nofail(fd);
3532 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3539 if (streq(verb, "enable")) {
3542 mkdir_parents(new_path, 0755);
3544 if (symlink(old_path, new_path) >= 0) {
3547 log_info("ln -s '%s' '%s'", old_path, new_path);
3552 if (errno != EEXIST) {
3553 log_error("Cannot link %s to %s: %m", old_path, new_path);
3557 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3559 if (errno == EINVAL) {
3560 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3564 log_error("readlink() failed: %s", strerror(-r));
3568 if (streq(dest, old_path)) {
3574 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3583 log_info("ln -s '%s' '%s'", old_path, new_path);
3585 if (symlink(old_path, new_path) >= 0)
3588 log_error("Cannot link %s to %s: %m", old_path, new_path);
3591 } else if (streq(verb, "disable")) {
3594 if ((r = mark_symlink_for_removal(old_path)) < 0)
3597 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3598 if (errno == ENOENT)
3601 if (errno == EINVAL) {
3602 log_warning("File %s not a symlink, ignoring.", old_path);
3606 log_error("readlink() failed: %s", strerror(-r));
3610 if (!streq(dest, old_path)) {
3611 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3618 if ((r = mark_symlink_for_removal(new_path)) < 0)
3622 log_info("rm '%s'", new_path);
3624 if (unlink(new_path) >= 0)
3627 log_error("Cannot unlink %s: %m", new_path);
3630 } else if (streq(verb, "is-enabled")) {
3633 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3635 if (errno == ENOENT || errno == EINVAL)
3638 log_error("readlink() failed: %s", strerror(-r));
3642 if (streq(dest, old_path)) {
3650 assert_not_reached("Unknown action.");
3653 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3655 char *alias_path = NULL;
3660 assert(config_path);
3662 STRV_FOREACH(s, i->aliases) {
3665 if (!(alias_path = path_make_absolute(*s, config_path))) {
3666 log_error("Out of memory");
3671 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3674 if (streq(verb, "disable"))
3675 rmdir_parents(alias_path, config_path);
3685 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3687 char *alias_path = NULL;
3692 assert(config_path);
3694 STRV_FOREACH(s, i->wanted_by) {
3695 if (!unit_name_is_valid_no_type(*s, true)) {
3696 log_error("Invalid name %s.", *s);
3704 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3705 log_error("Out of memory");
3710 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3713 if (streq(verb, "disable"))
3714 rmdir_parents(alias_path, config_path);
3725 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3727 const ConfigItem items[] = {
3728 { "Alias", config_parse_strv, &i->aliases, "Install" },
3729 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3730 { "Also", config_parse_also, NULL, "Install" },
3732 { NULL, NULL, NULL, NULL }
3736 char *filename = NULL;
3743 STRV_FOREACH(p, paths->unit_path) {
3746 if (!(filename = path_make_absolute(i->name, *p))) {
3747 log_error("Out of memory");
3751 /* Ensure that we don't follow symlinks */
3752 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3753 if ((f = fdopen(fd, "re")))
3756 if (errno == ELOOP) {
3757 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3762 if (errno != ENOENT) {
3763 log_error("Failed to open %s: %m", filename);
3773 log_error("Couldn't find %s.", i->name);
3779 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3784 n_symlinks += strv_length(i->aliases);
3785 n_symlinks += strv_length(i->wanted_by);
3789 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3792 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3795 if ((r = mark_symlink_for_removal(filename)) < 0)
3798 if ((r = remove_marked_symlinks(config_path)) < 0)
3804 static char *get_config_path(void) {
3806 if (arg_session && arg_global)
3807 return strdup(SESSION_CONFIG_UNIT_PATH);
3812 if (session_config_home(&p) < 0)
3818 return strdup(SYSTEM_CONFIG_UNIT_PATH);
3821 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3825 char *config_path = NULL;
3828 const char *verb = args[0];
3830 dbus_error_init(&error);
3833 if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3834 log_error("Failed to determine lookup paths: %s", strerror(-r));
3838 if (!(config_path = get_config_path())) {
3839 log_error("Failed to determine config path");
3844 will_install = hashmap_new(string_hash_func, string_compare_func);
3845 have_installed = hashmap_new(string_hash_func, string_compare_func);
3847 if (!will_install || !have_installed) {
3848 log_error("Failed to allocate unit sets.");
3853 if (!arg_defaults && streq(verb, "disable"))
3854 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3855 log_error("Failed to allocate symlink sets.");
3860 for (j = 1; j < n; j++)
3861 if ((r = install_info_add(args[j])) < 0) {
3862 log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
3866 while ((i = hashmap_first(will_install))) {
3869 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3871 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3879 /* In test mode and found something */
3885 if (streq(verb, "is-enabled"))
3886 r = r > 0 ? 0 : -ENOENT;
3888 if (n_symlinks <= 0)
3889 log_warning("Unit files contain no applicable installation information. Ignoring.");
3892 /* Don't try to reload anything if the user asked us to not do this */
3894 /* Don't try to reload anything when updating a unit globally */
3896 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3897 (arg_session || sd_booted() > 0) &&
3898 /* Don't try to reload anything if we are running in a chroot environment */
3899 (arg_session || running_in_chroot() <= 0) ) {
3902 if ((q = daemon_reload(bus, args, n)) < 0)
3908 install_info_hashmap_free(will_install);
3909 install_info_hashmap_free(have_installed);
3911 set_free_free(remove_symlinks_to);
3913 lookup_paths_free(&paths);
3920 static int systemctl_help(void) {
3922 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3923 "Send control commands to or query the systemd manager.\n\n"
3924 " -h --help Show this help\n"
3925 " --version Show package version\n"
3926 " -t --type=TYPE List only units of a particular type\n"
3927 " -p --property=NAME Show only properties by this name\n"
3928 " -a --all Show all units/properties, including dead/empty ones\n"
3929 " --full Don't ellipsize unit names on output\n"
3930 " --fail When queueing a new job, fail if conflicting jobs are\n"
3932 " -q --quiet Suppress output\n"
3933 " --no-block Do not wait until operation finished\n"
3934 " --system Connect to system bus\n"
3935 " --session Connect to session bus\n"
3936 " --order When generating graph for dot, show only order\n"
3937 " --require When generating graph for dot, show only requirement\n"
3938 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3939 " --global Enable/disable unit files globally\n"
3940 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3942 " --force When enabling unit files, override existing symlinks\n"
3943 " When shutting down, execute action immediately\n"
3944 " --defaults When disabling unit files, remove default symlinks only\n\n"
3946 " list-units List units\n"
3947 " start [NAME...] Start (activate) one or more units\n"
3948 " stop [NAME...] Stop (deactivate) one or more units\n"
3949 " reload [NAME...] Reload one or more units\n"
3950 " restart [NAME...] Start or restart one or more units\n"
3951 " try-restart [NAME...] Restart one or more units if active\n"
3952 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3953 " otherwise start or restart\n"
3954 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3955 " otherwise restart if active\n"
3956 " isolate [NAME] Start one unit and stop all others\n"
3957 " is-active [NAME...] Check whether units are active\n"
3958 " status [NAME...|PID...] Show runtime status of one or more units\n"
3959 " show [NAME...|JOB...] Show properties of one or more\n"
3960 " units/jobs or the manager\n"
3961 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
3963 " enable [NAME...] Enable one or more unit files\n"
3964 " disable [NAME...] Disable one or more unit files\n"
3965 " is-enabled [NAME...] Check whether unit files are enabled\n"
3966 " load [NAME...] Load one or more units\n"
3967 " list-jobs List jobs\n"
3968 " cancel [JOB...] Cancel all, one, or more jobs\n"
3969 " monitor Monitor unit/job changes\n"
3970 " dump Dump server status\n"
3971 " dot Dump dependency graph for dot(1)\n"
3972 " snapshot [NAME] Create a snapshot\n"
3973 " delete [NAME...] Remove one or more snapshots\n"
3974 " daemon-reload Reload systemd manager configuration\n"
3975 " daemon-reexec Reexecute systemd manager\n"
3976 " show-environment Dump environment\n"
3977 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3978 " unset-environment [NAME...] Unset one or more environment variables\n"
3979 " default Enter system default mode\n"
3980 " rescue Enter system rescue mode\n"
3981 " emergency Enter system emergency mode\n"
3982 " halt Shut down and halt the system\n"
3983 " poweroff Shut down and power-off the system\n"
3984 " reboot Shut down and reboot the system\n"
3985 " kexec Shut down and reboot the system with kexec\n"
3986 " exit Ask for session termination\n",
3987 program_invocation_short_name);
3992 static int halt_help(void) {
3994 printf("%s [OPTIONS...]\n\n"
3995 "%s the system.\n\n"
3996 " --help Show this help\n"
3997 " --halt Halt the machine\n"
3998 " -p --poweroff Switch off the machine\n"
3999 " --reboot Reboot the machine\n"
4000 " -f --force Force immediate halt/power-off/reboot\n"
4001 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4002 " -d --no-wtmp Don't write wtmp record\n"
4003 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4004 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4005 program_invocation_short_name,
4006 arg_action == ACTION_REBOOT ? "Reboot" :
4007 arg_action == ACTION_POWEROFF ? "Power off" :
4013 static int shutdown_help(void) {
4015 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4016 "Shut down the system.\n\n"
4017 " --help Show this help\n"
4018 " -H --halt Halt the machine\n"
4019 " -P --poweroff Power-off the machine\n"
4020 " -r --reboot Reboot the machine\n"
4021 " -h Equivalent to --poweroff, overriden by --halt\n"
4022 " -k Don't halt/power-off/reboot, just send warnings\n"
4023 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4024 " -c Cancel a pending shutdown\n",
4025 program_invocation_short_name);
4030 static int telinit_help(void) {
4032 printf("%s [OPTIONS...] {COMMAND}\n\n"
4033 "Send control commands to the init daemon.\n\n"
4034 " --help Show this help\n"
4035 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4037 " 0 Power-off the machine\n"
4038 " 6 Reboot the machine\n"
4039 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4040 " 1, s, S Enter rescue mode\n"
4041 " q, Q Reload init daemon configuration\n"
4042 " u, U Reexecute init daemon\n",
4043 program_invocation_short_name);
4048 static int runlevel_help(void) {
4050 printf("%s [OPTIONS...]\n\n"
4051 "Prints the previous and current runlevel of the init system.\n\n"
4052 " --help Show this help\n",
4053 program_invocation_short_name);
4058 static int systemctl_parse_argv(int argc, char *argv[]) {
4076 static const struct option options[] = {
4077 { "help", no_argument, NULL, 'h' },
4078 { "version", no_argument, NULL, ARG_VERSION },
4079 { "type", required_argument, NULL, 't' },
4080 { "property", required_argument, NULL, 'p' },
4081 { "all", no_argument, NULL, 'a' },
4082 { "full", no_argument, NULL, ARG_FULL },
4083 { "fail", no_argument, NULL, ARG_FAIL },
4084 { "session", no_argument, NULL, ARG_SESSION },
4085 { "system", no_argument, NULL, ARG_SYSTEM },
4086 { "global", no_argument, NULL, ARG_GLOBAL },
4087 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4088 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4089 { "quiet", no_argument, NULL, 'q' },
4090 { "order", no_argument, NULL, ARG_ORDER },
4091 { "require", no_argument, NULL, ARG_REQUIRE },
4092 { "force", no_argument, NULL, ARG_FORCE },
4093 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4094 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4095 { NULL, 0, NULL, 0 }
4103 while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
4112 puts(PACKAGE_STRING);
4114 puts(SYSTEMD_FEATURES);
4124 if (!(l = strv_append(arg_property, optarg)))
4127 strv_free(arg_property);
4130 /* If the user asked for a particular
4131 * property, show it to him, even if it is
4150 arg_session = false;
4154 arg_no_block = true;
4162 arg_dot = DOT_ORDER;
4166 arg_dot = DOT_REQUIRE;
4182 arg_no_reload = true;
4191 arg_defaults = true;
4198 log_error("Unknown option code %c", c);
4206 static int halt_parse_argv(int argc, char *argv[]) {
4215 static const struct option options[] = {
4216 { "help", no_argument, NULL, ARG_HELP },
4217 { "halt", no_argument, NULL, ARG_HALT },
4218 { "poweroff", no_argument, NULL, 'p' },
4219 { "reboot", no_argument, NULL, ARG_REBOOT },
4220 { "force", no_argument, NULL, 'f' },
4221 { "wtmp-only", no_argument, NULL, 'w' },
4222 { "no-wtmp", no_argument, NULL, 'd' },
4223 { "no-sync", no_argument, NULL, 'n' },
4224 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4225 { NULL, 0, NULL, 0 }
4233 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4234 if (runlevel == '0' || runlevel == '6')
4235 arg_immediate = true;
4237 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4245 arg_action = ACTION_HALT;
4249 if (arg_action != ACTION_REBOOT)
4250 arg_action = ACTION_POWEROFF;
4254 arg_action = ACTION_REBOOT;
4258 arg_immediate = true;
4279 /* Compatibility nops */
4286 log_error("Unknown option code %c", c);
4291 if (optind < argc) {
4292 log_error("Too many arguments.");
4299 static int parse_time_spec(const char *t, usec_t *_u) {
4303 if (streq(t, "now"))
4305 else if (t[0] == '+') {
4308 if (safe_atou64(t + 1, &u) < 0)
4311 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4320 hour = strtol(t, &e, 10);
4321 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4324 minute = strtol(e+1, &e, 10);
4325 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4328 n = now(CLOCK_REALTIME);
4329 s = (time_t) (n / USEC_PER_SEC);
4332 assert_se(localtime_r(&s, &tm));
4334 tm.tm_hour = (int) hour;
4335 tm.tm_min = (int) minute;
4338 assert_se(s = mktime(&tm));
4340 *_u = (usec_t) s * USEC_PER_SEC;
4343 *_u += USEC_PER_DAY;
4349 static int shutdown_parse_argv(int argc, char *argv[]) {
4356 static const struct option options[] = {
4357 { "help", no_argument, NULL, ARG_HELP },
4358 { "halt", no_argument, NULL, 'H' },
4359 { "poweroff", no_argument, NULL, 'P' },
4360 { "reboot", no_argument, NULL, 'r' },
4361 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4362 { NULL, 0, NULL, 0 }
4370 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4378 arg_action = ACTION_HALT;
4382 arg_action = ACTION_POWEROFF;
4386 arg_action = ACTION_REBOOT;
4390 if (arg_action != ACTION_HALT)
4391 arg_action = ACTION_POWEROFF;
4404 /* Compatibility nops */
4408 arg_action = ACTION_CANCEL_SHUTDOWN;
4415 log_error("Unknown option code %c", c);
4420 if (argc > optind) {
4421 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4422 log_error("Failed to parse time specification: %s", argv[optind]);
4426 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4428 /* We skip the time argument */
4429 if (argc > optind + 1)
4430 arg_wall = argv + optind + 1;
4437 static int telinit_parse_argv(int argc, char *argv[]) {
4444 static const struct option options[] = {
4445 { "help", no_argument, NULL, ARG_HELP },
4446 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4447 { NULL, 0, NULL, 0 }
4450 static const struct {
4454 { '0', ACTION_POWEROFF },
4455 { '6', ACTION_REBOOT },
4456 { '1', ACTION_RESCUE },
4457 { '2', ACTION_RUNLEVEL2 },
4458 { '3', ACTION_RUNLEVEL3 },
4459 { '4', ACTION_RUNLEVEL4 },
4460 { '5', ACTION_RUNLEVEL5 },
4461 { 's', ACTION_RESCUE },
4462 { 'S', ACTION_RESCUE },
4463 { 'q', ACTION_RELOAD },
4464 { 'Q', ACTION_RELOAD },
4465 { 'u', ACTION_REEXEC },
4466 { 'U', ACTION_REEXEC }
4475 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4490 log_error("Unknown option code %c", c);
4495 if (optind >= argc) {
4500 if (optind + 1 < argc) {
4501 log_error("Too many arguments.");
4505 if (strlen(argv[optind]) != 1) {
4506 log_error("Expected single character argument.");
4510 for (i = 0; i < ELEMENTSOF(table); i++)
4511 if (table[i].from == argv[optind][0])
4514 if (i >= ELEMENTSOF(table)) {
4515 log_error("Unknown command %s.", argv[optind]);
4519 arg_action = table[i].to;
4526 static int runlevel_parse_argv(int argc, char *argv[]) {
4532 static const struct option options[] = {
4533 { "help", no_argument, NULL, ARG_HELP },
4534 { NULL, 0, NULL, 0 }
4542 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4553 log_error("Unknown option code %c", c);
4558 if (optind < argc) {
4559 log_error("Too many arguments.");
4566 static int parse_argv(int argc, char *argv[]) {
4570 if (program_invocation_short_name) {
4572 if (strstr(program_invocation_short_name, "halt")) {
4573 arg_action = ACTION_HALT;
4574 return halt_parse_argv(argc, argv);
4575 } else if (strstr(program_invocation_short_name, "poweroff")) {
4576 arg_action = ACTION_POWEROFF;
4577 return halt_parse_argv(argc, argv);
4578 } else if (strstr(program_invocation_short_name, "reboot")) {
4579 arg_action = ACTION_REBOOT;
4580 return halt_parse_argv(argc, argv);
4581 } else if (strstr(program_invocation_short_name, "shutdown")) {
4582 arg_action = ACTION_POWEROFF;
4583 return shutdown_parse_argv(argc, argv);
4584 } else if (strstr(program_invocation_short_name, "init")) {
4586 if (sd_booted() > 0) {
4587 arg_action = ACTION_INVALID;
4588 return telinit_parse_argv(argc, argv);
4590 /* Hmm, so some other init system is
4591 * running, we need to forward this
4592 * request to it. For now we simply
4593 * guess that it is Upstart. */
4595 execv("/lib/upstart/telinit", argv);
4597 log_error("Couldn't find an alternative telinit implementation to spawn.");
4601 } else if (strstr(program_invocation_short_name, "runlevel")) {
4602 arg_action = ACTION_RUNLEVEL;
4603 return runlevel_parse_argv(argc, argv);
4607 arg_action = ACTION_SYSTEMCTL;
4608 return systemctl_parse_argv(argc, argv);
4611 static int action_to_runlevel(void) {
4613 static const char table[_ACTION_MAX] = {
4614 [ACTION_HALT] = '0',
4615 [ACTION_POWEROFF] = '0',
4616 [ACTION_REBOOT] = '6',
4617 [ACTION_RUNLEVEL2] = '2',
4618 [ACTION_RUNLEVEL3] = '3',
4619 [ACTION_RUNLEVEL4] = '4',
4620 [ACTION_RUNLEVEL5] = '5',
4621 [ACTION_RESCUE] = '1'
4624 assert(arg_action < _ACTION_MAX);
4626 return table[arg_action];
4629 static int talk_upstart(void) {
4630 DBusMessage *m = NULL, *reply = NULL;
4632 int previous, rl, r;
4634 env1_buf[] = "RUNLEVEL=X",
4635 env2_buf[] = "PREVLEVEL=X";
4636 char *env1 = env1_buf, *env2 = env2_buf;
4637 const char *emit = "runlevel";
4638 dbus_bool_t b_false = FALSE;
4639 DBusMessageIter iter, sub;
4640 DBusConnection *bus;
4642 dbus_error_init(&error);
4644 if (!(rl = action_to_runlevel()))
4647 if (utmp_get_runlevel(&previous, NULL) < 0)
4650 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4651 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4656 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4661 if ((r = bus_check_peercred(bus)) < 0) {
4662 log_error("Failed to verify owner of bus.");
4666 if (!(m = dbus_message_new_method_call(
4667 "com.ubuntu.Upstart",
4668 "/com/ubuntu/Upstart",
4669 "com.ubuntu.Upstart0_6",
4672 log_error("Could not allocate message.");
4677 dbus_message_iter_init_append(m, &iter);
4679 env1_buf[sizeof(env1_buf)-2] = rl;
4680 env2_buf[sizeof(env2_buf)-2] = previous;
4682 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4683 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4684 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4685 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4686 !dbus_message_iter_close_container(&iter, &sub) ||
4687 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4688 log_error("Could not append arguments to message.");
4693 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4695 if (error_is_no_service(&error)) {
4700 log_error("Failed to issue method call: %s", bus_error_message(&error));
4709 dbus_message_unref(m);
4712 dbus_message_unref(reply);
4715 dbus_connection_flush(bus);
4716 dbus_connection_close(bus);
4717 dbus_connection_unref(bus);
4720 dbus_error_free(&error);
4725 static int talk_initctl(void) {
4726 struct init_request request;
4730 if (!(rl = action_to_runlevel()))
4734 request.magic = INIT_MAGIC;
4735 request.sleeptime = 0;
4736 request.cmd = INIT_CMD_RUNLVL;
4737 request.runlevel = rl;
4739 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4741 if (errno == ENOENT)
4744 log_error("Failed to open "INIT_FIFO": %m");
4749 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4750 close_nointr_nofail(fd);
4753 log_error("Failed to write to "INIT_FIFO": %m");
4754 return errno ? -errno : -EIO;
4760 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4762 static const struct {
4770 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4772 { "list-units", LESS, 1, list_units },
4773 { "list-jobs", EQUAL, 1, list_jobs },
4774 { "clear-jobs", EQUAL, 1, daemon_reload },
4775 { "load", MORE, 2, load_unit },
4776 { "cancel", MORE, 2, cancel_job },
4777 { "start", MORE, 2, start_unit },
4778 { "stop", MORE, 2, start_unit },
4779 { "reload", MORE, 2, start_unit },
4780 { "restart", MORE, 2, start_unit },
4781 { "try-restart", MORE, 2, start_unit },
4782 { "reload-or-restart", MORE, 2, start_unit },
4783 { "reload-or-try-restart", MORE, 2, start_unit },
4784 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4785 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4786 { "isolate", EQUAL, 2, start_unit },
4787 { "is-active", MORE, 2, check_unit },
4788 { "check", MORE, 2, check_unit },
4789 { "show", MORE, 1, show },
4790 { "status", MORE, 2, show },
4791 { "monitor", EQUAL, 1, monitor },
4792 { "dump", EQUAL, 1, dump },
4793 { "dot", EQUAL, 1, dot },
4794 { "snapshot", LESS, 2, snapshot },
4795 { "delete", MORE, 2, delete_snapshot },
4796 { "daemon-reload", EQUAL, 1, daemon_reload },
4797 { "daemon-reexec", EQUAL, 1, daemon_reload },
4798 { "show-environment", EQUAL, 1, show_enviroment },
4799 { "set-environment", MORE, 2, set_environment },
4800 { "unset-environment", MORE, 2, set_environment },
4801 { "halt", EQUAL, 1, start_special },
4802 { "poweroff", EQUAL, 1, start_special },
4803 { "reboot", EQUAL, 1, start_special },
4804 { "kexec", EQUAL, 1, start_special },
4805 { "default", EQUAL, 1, start_special },
4806 { "rescue", EQUAL, 1, start_special },
4807 { "emergency", EQUAL, 1, start_special },
4808 { "exit", EQUAL, 1, start_special },
4809 { "reset-failed", MORE, 1, reset_failed },
4810 { "enable", MORE, 2, enable_unit },
4811 { "disable", MORE, 2, enable_unit },
4812 { "is-enabled", MORE, 2, enable_unit }
4822 left = argc - optind;
4825 /* Special rule: no arguments means "list-units" */
4828 if (streq(argv[optind], "help")) {
4833 for (i = 0; i < ELEMENTSOF(verbs); i++)
4834 if (streq(argv[optind], verbs[i].verb))
4837 if (i >= ELEMENTSOF(verbs)) {
4838 log_error("Unknown operation %s", argv[optind]);
4843 switch (verbs[i].argc_cmp) {
4846 if (left != verbs[i].argc) {
4847 log_error("Invalid number of arguments.");
4854 if (left < verbs[i].argc) {
4855 log_error("Too few arguments.");
4862 if (left > verbs[i].argc) {
4863 log_error("Too many arguments.");
4870 assert_not_reached("Unknown comparison operator.");
4873 /* Require a bus connection for all operations but
4875 if (!streq(verbs[i].verb, "enable") &&
4876 !streq(verbs[i].verb, "disable") &&
4878 log_error("Failed to get D-Bus connection: %s", error->message);
4882 return verbs[i].dispatch(bus, argv + optind, left);
4885 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
4887 struct msghdr msghdr;
4889 union sockaddr_union sockaddr;
4890 struct shutdownd_command c;
4898 strncpy(c.wall_message, message, sizeof(c.wall_message));
4900 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4904 sockaddr.sa.sa_family = AF_UNIX;
4905 sockaddr.un.sun_path[0] = 0;
4906 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
4909 iovec.iov_base = (char*) &c;
4910 iovec.iov_len = sizeof(c);
4913 msghdr.msg_name = &sockaddr;
4914 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
4916 msghdr.msg_iov = &iovec;
4917 msghdr.msg_iovlen = 1;
4919 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
4920 close_nointr_nofail(fd);
4924 close_nointr_nofail(fd);
4928 static int reload_with_fallback(DBusConnection *bus) {
4931 /* First, try systemd via D-Bus. */
4932 if (daemon_reload(bus, NULL, 0) > 0)
4936 /* Nothing else worked, so let's try signals */
4937 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
4939 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
4940 log_error("kill() failed: %m");
4947 static int start_with_fallback(DBusConnection *bus) {
4950 /* First, try systemd via D-Bus. */
4951 if (start_unit(bus, NULL, 0) >= 0)
4955 /* Hmm, talking to systemd via D-Bus didn't work. Then
4956 * let's try to talk to Upstart via D-Bus. */
4957 if (talk_upstart() > 0)
4960 /* Nothing else worked, so let's try
4962 if (talk_initctl() > 0)
4965 log_error("Failed to talk to init daemon.");
4969 warn_wall(arg_action);
4973 static int halt_main(DBusConnection *bus) {
4976 if (geteuid() != 0) {
4977 log_error("Must be root.");
4983 char date[FORMAT_TIMESTAMP_MAX];
4985 m = strv_join(arg_wall, " ");
4986 r = send_shutdownd(arg_when,
4987 arg_action == ACTION_HALT ? 'H' :
4988 arg_action == ACTION_POWEROFF ? 'P' :
4995 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
4997 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
4998 format_timestamp(date, sizeof(date), arg_when));
5003 if (!arg_dry && !arg_immediate)
5004 return start_with_fallback(bus);
5007 if (sd_booted() > 0)
5008 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5009 else if ((r = utmp_put_shutdown(0)) < 0)
5010 log_warning("Failed to write utmp record: %s", strerror(-r));
5019 /* Make sure C-A-D is handled by the kernel from this
5021 reboot(RB_ENABLE_CAD);
5023 switch (arg_action) {
5026 log_info("Halting.");
5027 reboot(RB_HALT_SYSTEM);
5030 case ACTION_POWEROFF:
5031 log_info("Powering off.");
5032 reboot(RB_POWER_OFF);
5036 log_info("Rebooting.");
5037 reboot(RB_AUTOBOOT);
5041 assert_not_reached("Unknown halt action.");
5044 /* We should never reach this. */
5048 static int runlevel_main(void) {
5049 int r, runlevel, previous;
5051 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5052 printf("unknown\n");
5057 previous <= 0 ? 'N' : previous,
5058 runlevel <= 0 ? 'N' : runlevel);
5063 int main(int argc, char*argv[]) {
5064 int r, retval = EXIT_FAILURE;
5065 DBusConnection *bus = NULL;
5068 dbus_error_init(&error);
5070 log_parse_environment();
5073 if ((r = parse_argv(argc, argv)) < 0)
5076 retval = EXIT_SUCCESS;
5080 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5081 * let's shortcut this */
5082 if (arg_action == ACTION_RUNLEVEL) {
5083 r = runlevel_main();
5084 retval = r < 0 ? EXIT_FAILURE : r;
5088 bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5090 switch (arg_action) {
5092 case ACTION_SYSTEMCTL:
5093 r = systemctl_main(bus, argc, argv, &error);
5097 case ACTION_POWEROFF:
5102 case ACTION_RUNLEVEL2:
5103 case ACTION_RUNLEVEL3:
5104 case ACTION_RUNLEVEL4:
5105 case ACTION_RUNLEVEL5:
5107 case ACTION_EMERGENCY:
5108 case ACTION_DEFAULT:
5109 r = start_with_fallback(bus);
5114 r = reload_with_fallback(bus);
5117 case ACTION_CANCEL_SHUTDOWN:
5118 r = send_shutdownd(0, 0, false, NULL);
5121 case ACTION_INVALID:
5122 case ACTION_RUNLEVEL:
5124 assert_not_reached("Unknown action");
5127 retval = r < 0 ? EXIT_FAILURE : r;
5132 dbus_connection_flush(bus);
5133 dbus_connection_close(bus);
5134 dbus_connection_unref(bus);
5137 dbus_error_free(&error);
5141 strv_free(arg_property);