1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <sys/reboot.h>
28 #include <sys/ioctl.h>
32 #include <sys/socket.h>
35 #include <dbus/dbus.h>
41 #include "utmp-wtmp.h"
45 #include "dbus-common.h"
46 #include "cgroup-show.h"
47 #include "cgroup-util.h"
49 #include "path-lookup.h"
50 #include "conf-parser.h"
51 #include "sd-daemon.h"
52 #include "shutdownd.h"
53 #include "exit-status.h"
54 #include "bus-errors.h"
56 #include "unit-name.h"
58 static const char *arg_type = NULL;
59 static char **arg_property = NULL;
60 static bool arg_all = false;
61 static bool arg_fail = false;
62 static bool arg_session = false;
63 static bool arg_global = false;
64 static bool arg_immediate = false;
65 static bool arg_no_block = false;
66 static bool arg_no_wtmp = false;
67 static bool arg_no_sync = false;
68 static bool arg_no_wall = false;
69 static bool arg_no_reload = false;
70 static bool arg_dry = false;
71 static bool arg_quiet = false;
72 static bool arg_full = false;
73 static bool arg_force = false;
74 static bool arg_defaults = false;
75 static char **arg_wall = NULL;
76 static usec_t arg_when = 0;
93 ACTION_CANCEL_SHUTDOWN,
95 } arg_action = ACTION_SYSTEMCTL;
102 static bool private_bus = false;
104 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
106 static bool on_tty(void) {
109 if (_unlikely_(t < 0))
110 t = isatty(STDOUT_FILENO) > 0;
115 static const char *ansi_highlight(bool b) {
120 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
123 static const char *ansi_highlight_green(bool b) {
128 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
131 static bool error_is_no_service(const DBusError *error) {
134 if (!dbus_error_is_set(error))
137 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
140 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
143 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
146 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
149 if (!dbus_error_is_set(error))
152 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
153 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
154 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
155 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
156 return EXIT_NOPERMISSION;
158 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
159 return EXIT_NOTINSTALLED;
161 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
162 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
163 return EXIT_NOTIMPLEMENTED;
165 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
166 return EXIT_NOTCONFIGURED;
174 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
179 if (dbus_message_iter_get_arg_type(iter) != type)
182 dbus_message_iter_get_basic(iter, data);
184 if (!dbus_message_iter_next(iter) != !next)
190 static void warn_wall(enum action action) {
191 static const char *table[_ACTION_MAX] = {
192 [ACTION_HALT] = "The system is going down for system halt NOW!",
193 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
194 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
195 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
196 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
205 if (!(p = strv_join(arg_wall, " "))) {
206 log_error("Failed to join strings.");
222 utmp_wall(table[action]);
227 const char *description;
228 const char *load_state;
229 const char *active_state;
230 const char *sub_state;
231 const char *following;
232 const char *unit_path;
234 const char *job_type;
235 const char *job_path;
238 static int compare_unit_info(const void *a, const void *b) {
240 const struct unit_info *u = a, *v = b;
242 d1 = strrchr(u->id, '.');
243 d2 = strrchr(v->id, '.');
248 if ((r = strcasecmp(d1, d2)) != 0)
252 return strcasecmp(u->id, v->id);
255 static bool output_show_job(const struct unit_info *u) {
258 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
259 streq(dot+1, arg_type))) &&
260 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0);
263 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
264 unsigned active_len, sub_len, job_len;
265 const struct unit_info *u;
267 active_len = sizeof("ACTIVE")-1;
268 sub_len = sizeof("SUB")-1;
269 job_len = sizeof("JOB")-1;
271 for (u = unit_infos; u < unit_infos + c; u++) {
272 if (!output_show_job(u))
275 active_len = MAX(active_len, strlen(u->active_state));
276 sub_len = MAX(sub_len, strlen(u->sub_state));
278 job_len = MAX(job_len, strlen(u->job_type));
282 printf("%-25s %-6s %-*s %-*s %-*s", "UNIT", "LOAD",
283 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
284 if (columns() >= 80+12 || arg_full)
285 printf(" %s\n", "DESCRIPTION");
290 for (u = unit_infos; u < unit_infos + c; u++) {
293 const char *on_loaded, *off_loaded;
294 const char *on_active, *off_active;
296 if (!output_show_job(u))
299 if (!streq(u->load_state, "loaded")) {
300 on_loaded = ansi_highlight(true);
301 off_loaded = ansi_highlight(false);
303 on_loaded = off_loaded = "";
305 if (streq(u->active_state, "failed")) {
306 on_active = ansi_highlight(true);
307 off_active = ansi_highlight(false);
309 on_active = off_active = "";
311 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
313 printf("%-25s %s%-6s%s %s%-*s %-*s%s%n",
315 on_loaded, u->load_state, off_loaded,
316 on_active, active_len, u->active_state,
317 sub_len, u->sub_state, off_active,
322 a -= strlen(on_loaded) + strlen(off_loaded);
323 a -= strlen(on_active) + strlen(off_active);
326 printf(" %-*s", job_len, u->job_type);
330 if (a + b + 1 < columns()) {
332 printf(" %-*s", job_len, "");
335 printf(" %s", u->description);
337 printf(" %.*s", columns() - a - b - 1, u->description);
344 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
345 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
346 "SUB = The low-level unit activation state, values depend on unit type.\n"
347 "JOB = Pending job for the unit.\n");
350 printf("\n%u units listed.\n", c);
352 printf("\n%u units listed. Pass --all to see inactive units, too.\n", c);
356 static int list_units(DBusConnection *bus, char **args, unsigned n) {
357 DBusMessage *m = NULL, *reply = NULL;
360 DBusMessageIter iter, sub, sub2;
361 unsigned c = 0, n_units = 0;
362 struct unit_info *unit_infos = NULL;
364 dbus_error_init(&error);
368 if (!(m = dbus_message_new_method_call(
369 "org.freedesktop.systemd1",
370 "/org/freedesktop/systemd1",
371 "org.freedesktop.systemd1.Manager",
373 log_error("Could not allocate message.");
377 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
378 log_error("Failed to issue method call: %s", bus_error_message(&error));
383 if (!dbus_message_iter_init(reply, &iter) ||
384 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
385 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
386 log_error("Failed to parse reply.");
391 dbus_message_iter_recurse(&iter, &sub);
393 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
396 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
397 log_error("Failed to parse reply.");
405 n_units = MAX(2*c, 16);
406 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
409 log_error("Failed to allocate unit array.");
419 dbus_message_iter_recurse(&sub, &sub2);
421 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
422 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
423 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
424 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
425 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
426 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
427 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
428 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
429 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
430 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
431 log_error("Failed to parse reply.");
436 dbus_message_iter_next(&sub);
440 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
441 output_units_list(unit_infos, c);
447 dbus_message_unref(m);
450 dbus_message_unref(reply);
454 dbus_error_free(&error);
459 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
460 static const char * const colors[] = {
461 "Requires", "[color=\"black\"]",
462 "RequiresOverridable", "[color=\"black\"]",
463 "Requisite", "[color=\"darkblue\"]",
464 "RequisiteOverridable", "[color=\"darkblue\"]",
465 "Wants", "[color=\"darkgrey\"]",
466 "Conflicts", "[color=\"red\"]",
467 "ConflictedBy", "[color=\"red\"]",
468 "After", "[color=\"green\"]"
471 const char *c = NULL;
478 for (i = 0; i < ELEMENTSOF(colors); i += 2)
479 if (streq(colors[i], prop)) {
487 if (arg_dot != DOT_ALL)
488 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
491 switch (dbus_message_iter_get_arg_type(iter)) {
493 case DBUS_TYPE_ARRAY:
495 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
498 dbus_message_iter_recurse(iter, &sub);
500 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
503 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
504 dbus_message_iter_get_basic(&sub, &s);
505 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
507 dbus_message_iter_next(&sub);
517 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
518 DBusMessage *m = NULL, *reply = NULL;
519 const char *interface = "org.freedesktop.systemd1.Unit";
522 DBusMessageIter iter, sub, sub2, sub3;
527 dbus_error_init(&error);
529 if (!(m = dbus_message_new_method_call(
530 "org.freedesktop.systemd1",
532 "org.freedesktop.DBus.Properties",
534 log_error("Could not allocate message.");
539 if (!dbus_message_append_args(m,
540 DBUS_TYPE_STRING, &interface,
541 DBUS_TYPE_INVALID)) {
542 log_error("Could not append arguments to message.");
547 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
548 log_error("Failed to issue method call: %s", bus_error_message(&error));
553 if (!dbus_message_iter_init(reply, &iter) ||
554 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
555 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
556 log_error("Failed to parse reply.");
561 dbus_message_iter_recurse(&iter, &sub);
563 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
566 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
567 log_error("Failed to parse reply.");
572 dbus_message_iter_recurse(&sub, &sub2);
574 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
575 log_error("Failed to parse reply.");
580 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
581 log_error("Failed to parse reply.");
586 dbus_message_iter_recurse(&sub2, &sub3);
588 if (dot_one_property(name, prop, &sub3)) {
589 log_error("Failed to parse reply.");
594 dbus_message_iter_next(&sub);
601 dbus_message_unref(m);
604 dbus_message_unref(reply);
606 dbus_error_free(&error);
611 static int dot(DBusConnection *bus, char **args, unsigned n) {
612 DBusMessage *m = NULL, *reply = NULL;
615 DBusMessageIter iter, sub, sub2;
617 dbus_error_init(&error);
621 if (!(m = dbus_message_new_method_call(
622 "org.freedesktop.systemd1",
623 "/org/freedesktop/systemd1",
624 "org.freedesktop.systemd1.Manager",
626 log_error("Could not allocate message.");
630 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
631 log_error("Failed to issue method call: %s", bus_error_message(&error));
636 if (!dbus_message_iter_init(reply, &iter) ||
637 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
638 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
639 log_error("Failed to parse reply.");
644 printf("digraph systemd {\n");
646 dbus_message_iter_recurse(&iter, &sub);
647 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
648 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
650 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
651 log_error("Failed to parse reply.");
656 dbus_message_iter_recurse(&sub, &sub2);
658 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
659 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
660 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
661 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
662 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
663 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
664 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
665 log_error("Failed to parse reply.");
670 if ((r = dot_one(bus, id, unit_path)) < 0)
673 /* printf("\t\"%s\";\n", id); */
674 dbus_message_iter_next(&sub);
679 log_info(" Color legend: black = Requires\n"
680 " dark blue = Requisite\n"
681 " dark grey = Wants\n"
685 if (isatty(fileno(stdout)))
686 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
687 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
693 dbus_message_unref(m);
696 dbus_message_unref(reply);
698 dbus_error_free(&error);
703 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
704 DBusMessage *m = NULL, *reply = NULL;
707 DBusMessageIter iter, sub, sub2;
710 dbus_error_init(&error);
714 if (!(m = dbus_message_new_method_call(
715 "org.freedesktop.systemd1",
716 "/org/freedesktop/systemd1",
717 "org.freedesktop.systemd1.Manager",
719 log_error("Could not allocate message.");
723 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
724 log_error("Failed to issue method call: %s", bus_error_message(&error));
729 if (!dbus_message_iter_init(reply, &iter) ||
730 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
731 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
732 log_error("Failed to parse reply.");
737 dbus_message_iter_recurse(&iter, &sub);
739 if (isatty(STDOUT_FILENO))
740 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
742 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
743 const char *name, *type, *state, *job_path, *unit_path;
747 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
748 log_error("Failed to parse reply.");
753 dbus_message_iter_recurse(&sub, &sub2);
755 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
756 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
757 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
758 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
759 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
760 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
761 log_error("Failed to parse reply.");
766 e = arg_full ? NULL : ellipsize(name, 25, 33);
767 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
772 dbus_message_iter_next(&sub);
775 if (isatty(STDOUT_FILENO))
776 printf("\n%u jobs listed.\n", k);
782 dbus_message_unref(m);
785 dbus_message_unref(reply);
787 dbus_error_free(&error);
792 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
793 DBusMessage *m = NULL, *reply = NULL;
798 dbus_error_init(&error);
803 for (i = 1; i < n; i++) {
805 if (!(m = dbus_message_new_method_call(
806 "org.freedesktop.systemd1",
807 "/org/freedesktop/systemd1",
808 "org.freedesktop.systemd1.Manager",
810 log_error("Could not allocate message.");
815 if (!dbus_message_append_args(m,
816 DBUS_TYPE_STRING, &args[i],
817 DBUS_TYPE_INVALID)) {
818 log_error("Could not append arguments to message.");
823 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
824 log_error("Failed to issue method call: %s", bus_error_message(&error));
829 dbus_message_unref(m);
830 dbus_message_unref(reply);
839 dbus_message_unref(m);
842 dbus_message_unref(reply);
844 dbus_error_free(&error);
849 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
850 DBusMessage *m = NULL, *reply = NULL;
855 dbus_error_init(&error);
861 return daemon_reload(bus, args, n);
863 for (i = 1; i < n; i++) {
867 if (!(m = dbus_message_new_method_call(
868 "org.freedesktop.systemd1",
869 "/org/freedesktop/systemd1",
870 "org.freedesktop.systemd1.Manager",
872 log_error("Could not allocate message.");
877 if ((r = safe_atou(args[i], &id)) < 0) {
878 log_error("Failed to parse job id: %s", strerror(-r));
882 assert_cc(sizeof(uint32_t) == sizeof(id));
883 if (!dbus_message_append_args(m,
884 DBUS_TYPE_UINT32, &id,
885 DBUS_TYPE_INVALID)) {
886 log_error("Could not append arguments to message.");
891 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
892 log_error("Failed to issue method call: %s", bus_error_message(&error));
897 if (!dbus_message_get_args(reply, &error,
898 DBUS_TYPE_OBJECT_PATH, &path,
899 DBUS_TYPE_INVALID)) {
900 log_error("Failed to parse reply: %s", bus_error_message(&error));
905 dbus_message_unref(m);
906 if (!(m = dbus_message_new_method_call(
907 "org.freedesktop.systemd1",
909 "org.freedesktop.systemd1.Job",
911 log_error("Could not allocate message.");
916 dbus_message_unref(reply);
917 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
918 log_error("Failed to issue method call: %s", bus_error_message(&error));
923 dbus_message_unref(m);
924 dbus_message_unref(reply);
932 dbus_message_unref(m);
935 dbus_message_unref(reply);
937 dbus_error_free(&error);
942 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
943 DBusMessage *m = NULL, *reply = NULL;
944 dbus_bool_t b = FALSE;
945 DBusMessageIter iter, sub;
947 *interface = "org.freedesktop.systemd1.Unit",
948 *property = "NeedDaemonReload",
951 /* We ignore all errors here, since this is used to show a warning only */
953 if (!(m = dbus_message_new_method_call(
954 "org.freedesktop.systemd1",
955 "/org/freedesktop/systemd1",
956 "org.freedesktop.systemd1.Manager",
960 if (!dbus_message_append_args(m,
961 DBUS_TYPE_STRING, &unit,
965 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
968 if (!dbus_message_get_args(reply, NULL,
969 DBUS_TYPE_OBJECT_PATH, &path,
973 dbus_message_unref(m);
974 if (!(m = dbus_message_new_method_call(
975 "org.freedesktop.systemd1",
977 "org.freedesktop.DBus.Properties",
981 if (!dbus_message_append_args(m,
982 DBUS_TYPE_STRING, &interface,
983 DBUS_TYPE_STRING, &property,
984 DBUS_TYPE_INVALID)) {
988 dbus_message_unref(reply);
989 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
992 if (!dbus_message_iter_init(reply, &iter) ||
993 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
996 dbus_message_iter_recurse(&iter, &sub);
998 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1001 dbus_message_iter_get_basic(&sub, &b);
1005 dbus_message_unref(m);
1008 dbus_message_unref(reply);
1013 typedef struct WaitData {
1018 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1026 dbus_error_init(&error);
1028 log_debug("Got D-Bus request: %s.%s() on %s",
1029 dbus_message_get_interface(message),
1030 dbus_message_get_member(message),
1031 dbus_message_get_path(message));
1033 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1034 log_error("Warning! D-Bus connection terminated.");
1035 dbus_connection_close(connection);
1037 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1040 dbus_bool_t success = true;
1042 if (!dbus_message_get_args(message, &error,
1043 DBUS_TYPE_UINT32, &id,
1044 DBUS_TYPE_OBJECT_PATH, &path,
1045 DBUS_TYPE_BOOLEAN, &success,
1047 log_error("Failed to parse message: %s", bus_error_message(&error));
1051 if ((p = set_remove(d->set, (char*) path)))
1059 dbus_error_free(&error);
1060 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1063 static int enable_wait_for_jobs(DBusConnection *bus) {
1071 dbus_error_init(&error);
1072 dbus_bus_add_match(bus,
1074 "sender='org.freedesktop.systemd1',"
1075 "interface='org.freedesktop.systemd1.Manager',"
1076 "member='JobRemoved',"
1077 "path='/org/freedesktop/systemd1'",
1080 if (dbus_error_is_set(&error)) {
1081 log_error("Failed to add match: %s", bus_error_message(&error));
1082 dbus_error_free(&error);
1086 /* This is slightly dirty, since we don't undo the match registrations. */
1090 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1101 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1102 log_error("Failed to add filter.");
1107 while (!set_isempty(s) &&
1108 dbus_connection_read_write_dispatch(bus, -1))
1111 if (!arg_quiet && d.failed)
1112 log_error("Job failed, see system logs for details.");
1114 r = d.failed ? -EIO : 0;
1117 /* This is slightly dirty, since we don't undo the filter registration. */
1122 static int start_unit_one(
1123 DBusConnection *bus,
1130 DBusMessage *m = NULL, *reply = NULL;
1139 assert(arg_no_block || s);
1141 if (!(m = dbus_message_new_method_call(
1142 "org.freedesktop.systemd1",
1143 "/org/freedesktop/systemd1",
1144 "org.freedesktop.systemd1.Manager",
1146 log_error("Could not allocate message.");
1151 if (!dbus_message_append_args(m,
1152 DBUS_TYPE_STRING, &name,
1153 DBUS_TYPE_STRING, &mode,
1154 DBUS_TYPE_INVALID)) {
1155 log_error("Could not append arguments to message.");
1160 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1162 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1163 /* There's always a fallback possible for
1164 * legacy actions. */
1169 log_error("Failed to issue method call: %s", bus_error_message(error));
1174 if (!dbus_message_get_args(reply, error,
1175 DBUS_TYPE_OBJECT_PATH, &path,
1176 DBUS_TYPE_INVALID)) {
1177 log_error("Failed to parse reply: %s", bus_error_message(error));
1182 if (need_daemon_reload(bus, name))
1183 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1184 arg_session ? "--session" : "--system");
1186 if (!arg_no_block) {
1189 if (!(p = strdup(path))) {
1190 log_error("Failed to duplicate path.");
1195 if ((r = set_put(s, p)) < 0) {
1197 log_error("Failed to add path to set.");
1206 dbus_message_unref(m);
1209 dbus_message_unref(reply);
1214 static enum action verb_to_action(const char *verb) {
1215 if (streq(verb, "halt"))
1217 else if (streq(verb, "poweroff"))
1218 return ACTION_POWEROFF;
1219 else if (streq(verb, "reboot"))
1220 return ACTION_REBOOT;
1221 else if (streq(verb, "rescue"))
1222 return ACTION_RESCUE;
1223 else if (streq(verb, "emergency"))
1224 return ACTION_EMERGENCY;
1225 else if (streq(verb, "default"))
1226 return ACTION_DEFAULT;
1228 return ACTION_INVALID;
1231 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1233 static const char * const table[_ACTION_MAX] = {
1234 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1235 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1236 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1237 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1238 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1239 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1240 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1241 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1242 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1243 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET
1248 const char *method, *mode, *one_name;
1252 dbus_error_init(&error);
1256 if (arg_action == ACTION_SYSTEMCTL) {
1258 streq(args[0], "stop") ? "StopUnit" :
1259 streq(args[0], "reload") ? "ReloadUnit" :
1260 streq(args[0], "restart") ? "RestartUnit" :
1261 streq(args[0], "try-restart") ||
1262 streq(args[0], "condrestart") ? "TryRestartUnit" :
1263 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1264 streq(args[0], "reload-or-try-restart") ||
1265 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1269 (streq(args[0], "isolate") ||
1270 streq(args[0], "rescue") ||
1271 streq(args[0], "emergency")) ? "isolate" :
1275 one_name = table[verb_to_action(args[0])];
1278 assert(arg_action < ELEMENTSOF(table));
1279 assert(table[arg_action]);
1281 method = "StartUnit";
1283 mode = (arg_action == ACTION_EMERGENCY ||
1284 arg_action == ACTION_RESCUE ||
1285 arg_action == ACTION_RUNLEVEL2 ||
1286 arg_action == ACTION_RUNLEVEL3 ||
1287 arg_action == ACTION_RUNLEVEL4 ||
1288 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1290 one_name = table[arg_action];
1293 if (!arg_no_block) {
1294 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1295 log_error("Could not watch jobs: %s", strerror(-ret));
1299 if (!(s = set_new(string_hash_func, string_compare_func))) {
1300 log_error("Failed to allocate set.");
1307 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1310 for (i = 1; i < n; i++)
1311 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1312 ret = translate_bus_error_to_exit_status(r, &error);
1313 dbus_error_free(&error);
1318 if ((r = wait_for_jobs(bus, s)) < 0) {
1327 dbus_error_free(&error);
1332 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1338 r = start_unit(bus, args, n);
1341 warn_wall(verb_to_action(args[0]));
1346 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1347 DBusMessage *m = NULL, *reply = NULL;
1349 *interface = "org.freedesktop.systemd1.Unit",
1350 *property = "ActiveState";
1351 int r = 3; /* According to LSB: "program is not running" */
1358 dbus_error_init(&error);
1360 for (i = 1; i < n; i++) {
1361 const char *path = NULL;
1363 DBusMessageIter iter, sub;
1365 if (!(m = dbus_message_new_method_call(
1366 "org.freedesktop.systemd1",
1367 "/org/freedesktop/systemd1",
1368 "org.freedesktop.systemd1.Manager",
1370 log_error("Could not allocate message.");
1375 if (!dbus_message_append_args(m,
1376 DBUS_TYPE_STRING, &args[i],
1377 DBUS_TYPE_INVALID)) {
1378 log_error("Could not append arguments to message.");
1383 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1385 /* Hmm, cannot figure out anything about this unit... */
1389 dbus_error_free(&error);
1393 if (!dbus_message_get_args(reply, &error,
1394 DBUS_TYPE_OBJECT_PATH, &path,
1395 DBUS_TYPE_INVALID)) {
1396 log_error("Failed to parse reply: %s", bus_error_message(&error));
1401 dbus_message_unref(m);
1402 if (!(m = dbus_message_new_method_call(
1403 "org.freedesktop.systemd1",
1405 "org.freedesktop.DBus.Properties",
1407 log_error("Could not allocate message.");
1412 if (!dbus_message_append_args(m,
1413 DBUS_TYPE_STRING, &interface,
1414 DBUS_TYPE_STRING, &property,
1415 DBUS_TYPE_INVALID)) {
1416 log_error("Could not append arguments to message.");
1421 dbus_message_unref(reply);
1422 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1423 log_error("Failed to issue method call: %s", bus_error_message(&error));
1428 if (!dbus_message_iter_init(reply, &iter) ||
1429 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1430 log_error("Failed to parse reply.");
1435 dbus_message_iter_recurse(&iter, &sub);
1437 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1438 log_error("Failed to parse reply.");
1443 dbus_message_iter_get_basic(&sub, &state);
1448 if (streq(state, "active") || streq(state, "reloading"))
1451 dbus_message_unref(m);
1452 dbus_message_unref(reply);
1458 dbus_message_unref(m);
1461 dbus_message_unref(reply);
1463 dbus_error_free(&error);
1468 typedef struct ExecStatusInfo {
1474 usec_t start_timestamp;
1475 usec_t exit_timestamp;
1480 LIST_FIELDS(struct ExecStatusInfo, exec);
1483 static void exec_status_info_free(ExecStatusInfo *i) {
1491 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1492 uint64_t start_timestamp, exit_timestamp;
1493 DBusMessageIter sub2, sub3;
1497 int32_t code, status;
1503 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1506 dbus_message_iter_recurse(sub, &sub2);
1508 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1511 if (!(i->path = strdup(path)))
1514 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1515 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1519 dbus_message_iter_recurse(&sub2, &sub3);
1520 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1521 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1522 dbus_message_iter_next(&sub3);
1527 if (!(i->argv = new0(char*, n+1)))
1531 dbus_message_iter_recurse(&sub2, &sub3);
1532 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1535 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1536 dbus_message_iter_get_basic(&sub3, &s);
1537 dbus_message_iter_next(&sub3);
1539 if (!(i->argv[n++] = strdup(s)))
1543 if (!dbus_message_iter_next(&sub2) ||
1544 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1545 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1546 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1547 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1548 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1549 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1553 i->start_timestamp = (usec_t) start_timestamp;
1554 i->exit_timestamp = (usec_t) exit_timestamp;
1555 i->pid = (pid_t) pid;
1562 typedef struct UnitStatusInfo {
1564 const char *load_state;
1565 const char *active_state;
1566 const char *sub_state;
1568 const char *description;
1571 const char *default_control_group;
1573 usec_t inactive_exit_timestamp;
1574 usec_t active_enter_timestamp;
1575 usec_t active_exit_timestamp;
1576 usec_t inactive_enter_timestamp;
1578 bool need_daemon_reload;
1583 const char *status_text;
1585 #ifdef HAVE_SYSV_COMPAT
1589 usec_t start_timestamp;
1590 usec_t exit_timestamp;
1592 int exit_code, exit_status;
1595 unsigned n_accepted;
1596 unsigned n_connections;
1600 const char *sysfs_path;
1602 /* Mount, Automount */
1608 LIST_HEAD(ExecStatusInfo, exec);
1611 static void print_status_info(UnitStatusInfo *i) {
1613 const char *on, *off, *ss;
1615 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1616 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1620 /* This shows pretty information about a unit. See
1621 * print_property() for a low-level property printer */
1623 printf("%s", strna(i->id));
1625 if (i->description && !streq_ptr(i->id, i->description))
1626 printf(" - %s", i->description);
1630 if (streq_ptr(i->load_state, "failed")) {
1631 on = ansi_highlight(true);
1632 off = ansi_highlight(false);
1637 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1639 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1641 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1643 if (streq_ptr(i->active_state, "failed")) {
1644 on = ansi_highlight(true);
1645 off = ansi_highlight(false);
1646 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1647 on = ansi_highlight_green(true);
1648 off = ansi_highlight_green(false);
1653 printf("\t Active: %s%s (%s)%s",
1655 strna(i->active_state),
1659 printf("\t Active: %s%s%s",
1661 strna(i->active_state),
1664 timestamp = (streq_ptr(i->active_state, "active") ||
1665 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1666 (streq_ptr(i->active_state, "inactive") ||
1667 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1668 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1669 i->active_exit_timestamp;
1671 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1672 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1675 printf(" since [%s; %s]\n", s2, s1);
1677 printf(" since [%s]\n", s2);
1682 printf("\t Device: %s\n", i->sysfs_path);
1684 printf("\t Where: %s\n", i->where);
1686 printf("\t What: %s\n", i->what);
1689 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1691 LIST_FOREACH(exec, p, i->exec) {
1694 /* Only show exited processes here */
1698 t = strv_join(p->argv, " ");
1699 printf("\t Process: %u (%s, code=%s, ", p->pid, strna(t), sigchld_code_to_string(p->code));
1702 if (p->code == CLD_EXITED) {
1705 printf("status=%i", p->status);
1707 #ifdef HAVE_SYSV_COMPAT
1708 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1710 if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1715 printf("signal=%s", signal_to_string(p->status));
1718 if (i->main_pid == p->pid &&
1719 i->start_timestamp == p->start_timestamp &&
1720 i->exit_timestamp == p->start_timestamp)
1721 /* Let's not show this twice */
1724 if (p->pid == i->control_pid)
1728 if (i->main_pid > 0 || i->control_pid > 0) {
1731 if (i->main_pid > 0) {
1732 printf("Main PID: %u", (unsigned) i->main_pid);
1736 get_process_name(i->main_pid, &t);
1741 } else if (i->exit_code > 0) {
1742 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1744 if (i->exit_code == CLD_EXITED) {
1747 printf("status=%i", i->exit_status);
1749 #ifdef HAVE_SYSV_COMPAT
1750 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1752 if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
1757 printf("signal=%s", signal_to_string(i->exit_status));
1762 if (i->main_pid > 0 && i->control_pid > 0)
1765 if (i->control_pid > 0) {
1768 printf(" Control: %u", (unsigned) i->control_pid);
1770 get_process_name(i->control_pid, &t);
1781 printf("\t Status: \"%s\"\n", i->status_text);
1783 if (i->default_control_group) {
1786 printf("\t CGroup: %s\n", i->default_control_group);
1788 if ((c = columns()) > 18)
1793 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
1796 if (i->need_daemon_reload)
1797 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1798 ansi_highlight(true),
1799 ansi_highlight(false),
1800 arg_session ? "--session" : "--system");
1803 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1805 switch (dbus_message_iter_get_arg_type(iter)) {
1807 case DBUS_TYPE_STRING: {
1810 dbus_message_iter_get_basic(iter, &s);
1813 if (streq(name, "Id"))
1815 else if (streq(name, "LoadState"))
1817 else if (streq(name, "ActiveState"))
1818 i->active_state = s;
1819 else if (streq(name, "SubState"))
1821 else if (streq(name, "Description"))
1823 else if (streq(name, "FragmentPath"))
1825 #ifdef HAVE_SYSV_COMPAT
1826 else if (streq(name, "SysVPath")) {
1831 else if (streq(name, "DefaultControlGroup"))
1832 i->default_control_group = s;
1833 else if (streq(name, "StatusText"))
1835 else if (streq(name, "SysFSPath"))
1837 else if (streq(name, "Where"))
1839 else if (streq(name, "What"))
1846 case DBUS_TYPE_BOOLEAN: {
1849 dbus_message_iter_get_basic(iter, &b);
1851 if (streq(name, "Accept"))
1853 else if (streq(name, "NeedDaemonReload"))
1854 i->need_daemon_reload = b;
1859 case DBUS_TYPE_UINT32: {
1862 dbus_message_iter_get_basic(iter, &u);
1864 if (streq(name, "MainPID")) {
1866 i->main_pid = (pid_t) u;
1869 } else if (streq(name, "ControlPID"))
1870 i->control_pid = (pid_t) u;
1871 else if (streq(name, "ExecMainPID")) {
1873 i->main_pid = (pid_t) u;
1874 } else if (streq(name, "NAccepted"))
1876 else if (streq(name, "NConnections"))
1877 i->n_connections = u;
1882 case DBUS_TYPE_INT32: {
1885 dbus_message_iter_get_basic(iter, &j);
1887 if (streq(name, "ExecMainCode"))
1888 i->exit_code = (int) j;
1889 else if (streq(name, "ExecMainStatus"))
1890 i->exit_status = (int) j;
1895 case DBUS_TYPE_UINT64: {
1898 dbus_message_iter_get_basic(iter, &u);
1900 if (streq(name, "ExecMainStartTimestamp"))
1901 i->start_timestamp = (usec_t) u;
1902 else if (streq(name, "ExecMainExitTimestamp"))
1903 i->exit_timestamp = (usec_t) u;
1904 else if (streq(name, "ActiveEnterTimestamp"))
1905 i->active_enter_timestamp = (usec_t) u;
1906 else if (streq(name, "InactiveEnterTimestamp"))
1907 i->inactive_enter_timestamp = (usec_t) u;
1908 else if (streq(name, "InactiveExitTimestamp"))
1909 i->inactive_exit_timestamp = (usec_t) u;
1910 else if (streq(name, "ActiveExitTimestamp"))
1911 i->active_exit_timestamp = (usec_t) u;
1916 case DBUS_TYPE_ARRAY: {
1918 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
1919 startswith(name, "Exec")) {
1920 DBusMessageIter sub;
1922 dbus_message_iter_recurse(iter, &sub);
1923 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1924 ExecStatusInfo *info;
1927 if (!(info = new0(ExecStatusInfo, 1)))
1930 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
1935 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
1937 dbus_message_iter_next(&sub);
1948 static int print_property(const char *name, DBusMessageIter *iter) {
1952 /* This is a low-level property printer, see
1953 * print_status_info() for the nicer output */
1955 if (arg_property && !strv_find(arg_property, name))
1958 switch (dbus_message_iter_get_arg_type(iter)) {
1960 case DBUS_TYPE_STRING: {
1962 dbus_message_iter_get_basic(iter, &s);
1964 if (arg_all || s[0])
1965 printf("%s=%s\n", name, s);
1970 case DBUS_TYPE_BOOLEAN: {
1972 dbus_message_iter_get_basic(iter, &b);
1973 printf("%s=%s\n", name, yes_no(b));
1978 case DBUS_TYPE_UINT64: {
1980 dbus_message_iter_get_basic(iter, &u);
1982 /* Yes, heuristics! But we can change this check
1983 * should it turn out to not be sufficient */
1985 if (strstr(name, "Timestamp")) {
1986 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
1988 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
1989 printf("%s=%s\n", name, strempty(t));
1990 } else if (strstr(name, "USec")) {
1991 char timespan[FORMAT_TIMESPAN_MAX];
1993 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
1995 printf("%s=%llu\n", name, (unsigned long long) u);
2000 case DBUS_TYPE_UINT32: {
2002 dbus_message_iter_get_basic(iter, &u);
2004 if (strstr(name, "UMask") || strstr(name, "Mode"))
2005 printf("%s=%04o\n", name, u);
2007 printf("%s=%u\n", name, (unsigned) u);
2012 case DBUS_TYPE_INT32: {
2014 dbus_message_iter_get_basic(iter, &i);
2016 printf("%s=%i\n", name, (int) i);
2020 case DBUS_TYPE_DOUBLE: {
2022 dbus_message_iter_get_basic(iter, &d);
2024 printf("%s=%g\n", name, d);
2028 case DBUS_TYPE_STRUCT: {
2029 DBusMessageIter sub;
2030 dbus_message_iter_recurse(iter, &sub);
2032 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2035 dbus_message_iter_get_basic(&sub, &u);
2038 printf("%s=%u\n", name, (unsigned) u);
2040 printf("%s=\n", name);
2043 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2046 dbus_message_iter_get_basic(&sub, &s);
2048 if (arg_all || s[0])
2049 printf("%s=%s\n", name, s);
2057 case DBUS_TYPE_ARRAY:
2059 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2060 DBusMessageIter sub;
2063 dbus_message_iter_recurse(iter, &sub);
2065 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2066 printf("%s=", name);
2068 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2071 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2072 dbus_message_iter_get_basic(&sub, &s);
2073 printf("%s%s", space ? " " : "", s);
2076 dbus_message_iter_next(&sub);
2084 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2085 DBusMessageIter sub;
2087 dbus_message_iter_recurse(iter, &sub);
2089 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2090 printf("%s=", name);
2092 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2095 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2096 dbus_message_iter_get_basic(&sub, &u);
2099 dbus_message_iter_next(&sub);
2107 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2108 DBusMessageIter sub, sub2;
2110 dbus_message_iter_recurse(iter, &sub);
2111 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2112 const char *type, *path;
2114 dbus_message_iter_recurse(&sub, &sub2);
2116 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2117 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2118 printf("%s=%s\n", type, path);
2120 dbus_message_iter_next(&sub);
2125 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2126 DBusMessageIter sub, sub2;
2128 dbus_message_iter_recurse(iter, &sub);
2129 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2131 uint64_t value, next_elapse;
2133 dbus_message_iter_recurse(&sub, &sub2);
2135 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2136 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2137 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2138 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2140 printf("%s={ value=%s ; next_elapse=%s }\n",
2142 format_timespan(timespan1, sizeof(timespan1), value),
2143 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2146 dbus_message_iter_next(&sub);
2151 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2152 DBusMessageIter sub;
2154 dbus_message_iter_recurse(iter, &sub);
2155 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2156 ExecStatusInfo info;
2159 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2160 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2163 t = strv_join(info.argv, " ");
2165 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2169 yes_no(info.ignore),
2170 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2171 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2172 (unsigned) info. pid,
2173 sigchld_code_to_string(info.code),
2175 info.code == CLD_EXITED ? "" : "/",
2176 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2182 strv_free(info.argv);
2184 dbus_message_iter_next(&sub);
2194 printf("%s=[unprintable]\n", name);
2199 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2200 DBusMessage *m = NULL, *reply = NULL;
2201 const char *interface = "";
2204 DBusMessageIter iter, sub, sub2, sub3;
2205 UnitStatusInfo info;
2213 dbus_error_init(&error);
2215 if (!(m = dbus_message_new_method_call(
2216 "org.freedesktop.systemd1",
2218 "org.freedesktop.DBus.Properties",
2220 log_error("Could not allocate message.");
2225 if (!dbus_message_append_args(m,
2226 DBUS_TYPE_STRING, &interface,
2227 DBUS_TYPE_INVALID)) {
2228 log_error("Could not append arguments to message.");
2233 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2234 log_error("Failed to issue method call: %s", bus_error_message(&error));
2239 if (!dbus_message_iter_init(reply, &iter) ||
2240 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2241 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2242 log_error("Failed to parse reply.");
2247 dbus_message_iter_recurse(&iter, &sub);
2254 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2257 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2258 log_error("Failed to parse reply.");
2263 dbus_message_iter_recurse(&sub, &sub2);
2265 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2266 log_error("Failed to parse reply.");
2271 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2272 log_error("Failed to parse reply.");
2277 dbus_message_iter_recurse(&sub2, &sub3);
2279 if (show_properties)
2280 r = print_property(name, &sub3);
2282 r = status_property(name, &sub3, &info);
2285 log_error("Failed to parse reply.");
2290 dbus_message_iter_next(&sub);
2295 if (!show_properties)
2296 print_status_info(&info);
2298 if (!streq_ptr(info.active_state, "active") &&
2299 !streq_ptr(info.active_state, "reloading"))
2300 /* According to LSB: "program not running" */
2303 while ((p = info.exec)) {
2304 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2305 exec_status_info_free(p);
2310 dbus_message_unref(m);
2313 dbus_message_unref(reply);
2315 dbus_error_free(&error);
2320 static int show(DBusConnection *bus, char **args, unsigned n) {
2321 DBusMessage *m = NULL, *reply = NULL;
2325 bool show_properties, new_line = false;
2330 dbus_error_init(&error);
2332 show_properties = !streq(args[0], "status");
2334 if (show_properties && n <= 1) {
2335 /* If not argument is specified inspect the manager
2338 ret = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2342 for (i = 1; i < n; i++) {
2343 const char *path = NULL;
2346 if (safe_atou32(args[i], &id) < 0) {
2348 /* Interpret as unit name */
2350 if (!(m = dbus_message_new_method_call(
2351 "org.freedesktop.systemd1",
2352 "/org/freedesktop/systemd1",
2353 "org.freedesktop.systemd1.Manager",
2355 log_error("Could not allocate message.");
2360 if (!dbus_message_append_args(m,
2361 DBUS_TYPE_STRING, &args[i],
2362 DBUS_TYPE_INVALID)) {
2363 log_error("Could not append arguments to message.");
2368 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2370 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2371 log_error("Failed to issue method call: %s", bus_error_message(&error));
2376 dbus_error_free(&error);
2378 dbus_message_unref(m);
2379 if (!(m = dbus_message_new_method_call(
2380 "org.freedesktop.systemd1",
2381 "/org/freedesktop/systemd1",
2382 "org.freedesktop.systemd1.Manager",
2384 log_error("Could not allocate message.");
2389 if (!dbus_message_append_args(m,
2390 DBUS_TYPE_STRING, &args[i],
2391 DBUS_TYPE_INVALID)) {
2392 log_error("Could not append arguments to message.");
2397 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2398 log_error("Failed to issue method call: %s", bus_error_message(&error));
2400 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2401 ret = 4; /* According to LSB: "program or service status is unknown" */
2408 } else if (show_properties) {
2410 /* Interpret as job id */
2412 if (!(m = dbus_message_new_method_call(
2413 "org.freedesktop.systemd1",
2414 "/org/freedesktop/systemd1",
2415 "org.freedesktop.systemd1.Manager",
2417 log_error("Could not allocate message.");
2422 if (!dbus_message_append_args(m,
2423 DBUS_TYPE_UINT32, &id,
2424 DBUS_TYPE_INVALID)) {
2425 log_error("Could not append arguments to message.");
2430 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2431 log_error("Failed to issue method call: %s", bus_error_message(&error));
2437 /* Interpret as PID */
2439 if (!(m = dbus_message_new_method_call(
2440 "org.freedesktop.systemd1",
2441 "/org/freedesktop/systemd1",
2442 "org.freedesktop.systemd1.Manager",
2444 log_error("Could not allocate message.");
2449 if (!dbus_message_append_args(m,
2450 DBUS_TYPE_UINT32, &id,
2451 DBUS_TYPE_INVALID)) {
2452 log_error("Could not append arguments to message.");
2457 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2458 log_error("Failed to issue method call: %s", bus_error_message(&error));
2464 if (!dbus_message_get_args(reply, &error,
2465 DBUS_TYPE_OBJECT_PATH, &path,
2466 DBUS_TYPE_INVALID)) {
2467 log_error("Failed to parse reply: %s", bus_error_message(&error));
2472 if ((r = show_one(bus, path, show_properties, &new_line)) != 0)
2475 dbus_message_unref(m);
2476 dbus_message_unref(reply);
2482 dbus_message_unref(m);
2485 dbus_message_unref(reply);
2487 dbus_error_free(&error);
2492 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2494 DBusMessage *m = NULL, *reply = NULL;
2499 dbus_error_init(&error);
2501 log_debug("Got D-Bus request: %s.%s() on %s",
2502 dbus_message_get_interface(message),
2503 dbus_message_get_member(message),
2504 dbus_message_get_path(message));
2506 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2507 log_error("Warning! D-Bus connection terminated.");
2508 dbus_connection_close(connection);
2510 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2511 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2512 const char *id, *path;
2514 if (!dbus_message_get_args(message, &error,
2515 DBUS_TYPE_STRING, &id,
2516 DBUS_TYPE_OBJECT_PATH, &path,
2518 log_error("Failed to parse message: %s", bus_error_message(&error));
2519 else if (streq(dbus_message_get_member(message), "UnitNew"))
2520 printf("Unit %s added.\n", id);
2522 printf("Unit %s removed.\n", id);
2524 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2525 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2529 if (!dbus_message_get_args(message, &error,
2530 DBUS_TYPE_UINT32, &id,
2531 DBUS_TYPE_OBJECT_PATH, &path,
2533 log_error("Failed to parse message: %s", bus_error_message(&error));
2534 else if (streq(dbus_message_get_member(message), "JobNew"))
2535 printf("Job %u added.\n", id);
2537 printf("Job %u removed.\n", id);
2540 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2542 const char *path, *interface, *property = "Id";
2543 DBusMessageIter iter, sub;
2545 path = dbus_message_get_path(message);
2547 if (!dbus_message_get_args(message, &error,
2548 DBUS_TYPE_STRING, &interface,
2549 DBUS_TYPE_INVALID)) {
2550 log_error("Failed to parse message: %s", bus_error_message(&error));
2554 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2555 !streq(interface, "org.freedesktop.systemd1.Unit"))
2558 if (!(m = dbus_message_new_method_call(
2559 "org.freedesktop.systemd1",
2561 "org.freedesktop.DBus.Properties",
2563 log_error("Could not allocate message.");
2567 if (!dbus_message_append_args(m,
2568 DBUS_TYPE_STRING, &interface,
2569 DBUS_TYPE_STRING, &property,
2570 DBUS_TYPE_INVALID)) {
2571 log_error("Could not append arguments to message.");
2575 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2576 log_error("Failed to issue method call: %s", bus_error_message(&error));
2580 if (!dbus_message_iter_init(reply, &iter) ||
2581 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2582 log_error("Failed to parse reply.");
2586 dbus_message_iter_recurse(&iter, &sub);
2588 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2591 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2592 log_error("Failed to parse reply.");
2596 dbus_message_iter_get_basic(&sub, &id);
2597 printf("Unit %s changed.\n", id);
2601 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2602 log_error("Failed to parse reply.");
2606 dbus_message_iter_get_basic(&sub, &id);
2607 printf("Job %u changed.\n", id);
2613 dbus_message_unref(m);
2616 dbus_message_unref(reply);
2618 dbus_error_free(&error);
2619 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2623 dbus_message_unref(m);
2626 dbus_message_unref(reply);
2628 dbus_error_free(&error);
2629 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2632 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2633 DBusMessage *m = NULL, *reply = NULL;
2637 dbus_error_init(&error);
2640 dbus_bus_add_match(bus,
2642 "sender='org.freedesktop.systemd1',"
2643 "interface='org.freedesktop.systemd1.Manager',"
2644 "path='/org/freedesktop/systemd1'",
2647 if (dbus_error_is_set(&error)) {
2648 log_error("Failed to add match: %s", bus_error_message(&error));
2653 dbus_bus_add_match(bus,
2655 "sender='org.freedesktop.systemd1',"
2656 "interface='org.freedesktop.DBus.Properties',"
2657 "member='PropertiesChanged'",
2660 if (dbus_error_is_set(&error)) {
2661 log_error("Failed to add match: %s", bus_error_message(&error));
2667 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2668 log_error("Failed to add filter.");
2673 if (!(m = dbus_message_new_method_call(
2674 "org.freedesktop.systemd1",
2675 "/org/freedesktop/systemd1",
2676 "org.freedesktop.systemd1.Manager",
2678 log_error("Could not allocate message.");
2683 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2684 log_error("Failed to issue method call: %s", bus_error_message(&error));
2689 while (dbus_connection_read_write_dispatch(bus, -1))
2696 /* This is slightly dirty, since we don't undo the filter or the matches. */
2699 dbus_message_unref(m);
2702 dbus_message_unref(reply);
2704 dbus_error_free(&error);
2709 static int dump(DBusConnection *bus, char **args, unsigned n) {
2710 DBusMessage *m = NULL, *reply = NULL;
2715 dbus_error_init(&error);
2717 if (!(m = dbus_message_new_method_call(
2718 "org.freedesktop.systemd1",
2719 "/org/freedesktop/systemd1",
2720 "org.freedesktop.systemd1.Manager",
2722 log_error("Could not allocate message.");
2726 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2727 log_error("Failed to issue method call: %s", bus_error_message(&error));
2732 if (!dbus_message_get_args(reply, &error,
2733 DBUS_TYPE_STRING, &text,
2734 DBUS_TYPE_INVALID)) {
2735 log_error("Failed to parse reply: %s", bus_error_message(&error));
2740 fputs(text, stdout);
2746 dbus_message_unref(m);
2749 dbus_message_unref(reply);
2751 dbus_error_free(&error);
2756 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2757 DBusMessage *m = NULL, *reply = NULL;
2760 const char *name = "", *path, *id;
2761 dbus_bool_t cleanup = FALSE;
2762 DBusMessageIter iter, sub;
2764 *interface = "org.freedesktop.systemd1.Unit",
2767 dbus_error_init(&error);
2769 if (!(m = dbus_message_new_method_call(
2770 "org.freedesktop.systemd1",
2771 "/org/freedesktop/systemd1",
2772 "org.freedesktop.systemd1.Manager",
2773 "CreateSnapshot"))) {
2774 log_error("Could not allocate message.");
2781 if (!dbus_message_append_args(m,
2782 DBUS_TYPE_STRING, &name,
2783 DBUS_TYPE_BOOLEAN, &cleanup,
2784 DBUS_TYPE_INVALID)) {
2785 log_error("Could not append arguments to message.");
2790 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2791 log_error("Failed to issue method call: %s", bus_error_message(&error));
2796 if (!dbus_message_get_args(reply, &error,
2797 DBUS_TYPE_OBJECT_PATH, &path,
2798 DBUS_TYPE_INVALID)) {
2799 log_error("Failed to parse reply: %s", bus_error_message(&error));
2804 dbus_message_unref(m);
2805 if (!(m = dbus_message_new_method_call(
2806 "org.freedesktop.systemd1",
2808 "org.freedesktop.DBus.Properties",
2810 log_error("Could not allocate message.");
2814 if (!dbus_message_append_args(m,
2815 DBUS_TYPE_STRING, &interface,
2816 DBUS_TYPE_STRING, &property,
2817 DBUS_TYPE_INVALID)) {
2818 log_error("Could not append arguments to message.");
2823 dbus_message_unref(reply);
2824 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2825 log_error("Failed to issue method call: %s", bus_error_message(&error));
2830 if (!dbus_message_iter_init(reply, &iter) ||
2831 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2832 log_error("Failed to parse reply.");
2837 dbus_message_iter_recurse(&iter, &sub);
2839 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2840 log_error("Failed to parse reply.");
2845 dbus_message_iter_get_basic(&sub, &id);
2853 dbus_message_unref(m);
2856 dbus_message_unref(reply);
2858 dbus_error_free(&error);
2863 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2864 DBusMessage *m = NULL, *reply = NULL;
2872 dbus_error_init(&error);
2874 for (i = 1; i < n; i++) {
2875 const char *path = NULL;
2877 if (!(m = dbus_message_new_method_call(
2878 "org.freedesktop.systemd1",
2879 "/org/freedesktop/systemd1",
2880 "org.freedesktop.systemd1.Manager",
2882 log_error("Could not allocate message.");
2887 if (!dbus_message_append_args(m,
2888 DBUS_TYPE_STRING, &args[i],
2889 DBUS_TYPE_INVALID)) {
2890 log_error("Could not append arguments to message.");
2895 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2896 log_error("Failed to issue method call: %s", bus_error_message(&error));
2901 if (!dbus_message_get_args(reply, &error,
2902 DBUS_TYPE_OBJECT_PATH, &path,
2903 DBUS_TYPE_INVALID)) {
2904 log_error("Failed to parse reply: %s", bus_error_message(&error));
2909 dbus_message_unref(m);
2910 if (!(m = dbus_message_new_method_call(
2911 "org.freedesktop.systemd1",
2913 "org.freedesktop.systemd1.Snapshot",
2915 log_error("Could not allocate message.");
2920 dbus_message_unref(reply);
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 dbus_message_unref(m);
2928 dbus_message_unref(reply);
2936 dbus_message_unref(m);
2939 dbus_message_unref(reply);
2941 dbus_error_free(&error);
2946 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2947 DBusMessage *m = NULL, *reply = NULL;
2952 dbus_error_init(&error);
2954 if (arg_action == ACTION_RELOAD)
2956 else if (arg_action == ACTION_REEXEC)
2957 method = "Reexecute";
2959 assert(arg_action == ACTION_SYSTEMCTL);
2962 streq(args[0], "clear-jobs") ||
2963 streq(args[0], "cancel") ? "ClearJobs" :
2964 streq(args[0], "daemon-reexec") ? "Reexecute" :
2965 streq(args[0], "reset-failed") ? "ResetFailed" :
2966 streq(args[0], "daemon-exit") ? "Exit" :
2970 if (!(m = dbus_message_new_method_call(
2971 "org.freedesktop.systemd1",
2972 "/org/freedesktop/systemd1",
2973 "org.freedesktop.systemd1.Manager",
2975 log_error("Could not allocate message.");
2979 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2981 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
2982 /* There's always a fallback possible for
2983 * legacy actions. */
2988 log_error("Failed to issue method call: %s", bus_error_message(&error));
2997 dbus_message_unref(m);
3000 dbus_message_unref(reply);
3002 dbus_error_free(&error);
3007 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3008 DBusMessage *m = NULL, *reply = NULL;
3014 dbus_error_init(&error);
3017 return daemon_reload(bus, args, n);
3019 for (i = 1; i < n; i++) {
3021 if (!(m = dbus_message_new_method_call(
3022 "org.freedesktop.systemd1",
3023 "/org/freedesktop/systemd1",
3024 "org.freedesktop.systemd1.Manager",
3025 "ResetFailedUnit"))) {
3026 log_error("Could not allocate message.");
3031 if (!dbus_message_append_args(m,
3032 DBUS_TYPE_STRING, args + i,
3033 DBUS_TYPE_INVALID)) {
3034 log_error("Could not append arguments to message.");
3039 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3040 log_error("Failed to issue method call: %s", bus_error_message(&error));
3045 dbus_message_unref(m);
3046 dbus_message_unref(reply);
3054 dbus_message_unref(m);
3057 dbus_message_unref(reply);
3059 dbus_error_free(&error);
3064 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3065 DBusMessage *m = NULL, *reply = NULL;
3067 DBusMessageIter iter, sub, sub2;
3070 *interface = "org.freedesktop.systemd1.Manager",
3071 *property = "Environment";
3073 dbus_error_init(&error);
3075 if (!(m = dbus_message_new_method_call(
3076 "org.freedesktop.systemd1",
3077 "/org/freedesktop/systemd1",
3078 "org.freedesktop.DBus.Properties",
3080 log_error("Could not allocate message.");
3084 if (!dbus_message_append_args(m,
3085 DBUS_TYPE_STRING, &interface,
3086 DBUS_TYPE_STRING, &property,
3087 DBUS_TYPE_INVALID)) {
3088 log_error("Could not append arguments to message.");
3093 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3094 log_error("Failed to issue method call: %s", bus_error_message(&error));
3099 if (!dbus_message_iter_init(reply, &iter) ||
3100 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3101 log_error("Failed to parse reply.");
3106 dbus_message_iter_recurse(&iter, &sub);
3108 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3109 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3110 log_error("Failed to parse reply.");
3115 dbus_message_iter_recurse(&sub, &sub2);
3117 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3120 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3121 log_error("Failed to parse reply.");
3126 dbus_message_iter_get_basic(&sub2, &text);
3127 printf("%s\n", text);
3129 dbus_message_iter_next(&sub2);
3136 dbus_message_unref(m);
3139 dbus_message_unref(reply);
3141 dbus_error_free(&error);
3146 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3147 DBusMessage *m = NULL, *reply = NULL;
3151 DBusMessageIter iter, sub;
3154 dbus_error_init(&error);
3156 method = streq(args[0], "set-environment")
3158 : "UnsetEnvironment";
3160 if (!(m = dbus_message_new_method_call(
3161 "org.freedesktop.systemd1",
3162 "/org/freedesktop/systemd1",
3163 "org.freedesktop.systemd1.Manager",
3166 log_error("Could not allocate message.");
3170 dbus_message_iter_init_append(m, &iter);
3172 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3173 log_error("Could not append arguments to message.");
3178 for (i = 1; i < n; i++)
3179 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3180 log_error("Could not append arguments to message.");
3185 if (!dbus_message_iter_close_container(&iter, &sub)) {
3186 log_error("Could not append arguments to message.");
3191 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3192 log_error("Failed to issue method call: %s", bus_error_message(&error));
3201 dbus_message_unref(m);
3204 dbus_message_unref(reply);
3206 dbus_error_free(&error);
3219 static Hashmap *will_install = NULL, *have_installed = NULL;
3220 static Set *remove_symlinks_to = NULL;
3222 static void install_info_free(InstallInfo *i) {
3227 strv_free(i->aliases);
3228 strv_free(i->wanted_by);
3232 static void install_info_hashmap_free(Hashmap *m) {
3235 while ((i = hashmap_steal_first(m)))
3236 install_info_free(i);
3241 static int install_info_add(const char *name) {
3245 assert(will_install);
3247 if (!unit_name_is_valid_no_type(name)) {
3248 log_warning("Unit name %s is not a valid unit name.", name);
3252 if (hashmap_get(have_installed, name) ||
3253 hashmap_get(will_install, name))
3256 if (!(i = new0(InstallInfo, 1))) {
3261 if (!(i->name = strdup(name))) {
3266 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3273 install_info_free(i);
3278 static int config_parse_also(
3279 const char *filename,
3281 const char *section,
3295 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3299 if (!(n = strndup(w, l)))
3302 if ((r = install_info_add(n)) < 0) {
3303 log_warning("Cannot install unit %s: %s", n, strerror(-r));
3314 static int mark_symlink_for_removal(const char *p) {
3319 assert(path_is_absolute(p));
3321 if (!remove_symlinks_to)
3324 if (!(n = strdup(p)))
3327 path_kill_slashes(n);
3329 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3331 return r == -EEXIST ? 0 : r;
3337 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3346 if (!(d = fdopendir(fd))) {
3347 close_nointr_nofail(fd);
3353 while ((de = readdir(d))) {
3354 bool is_dir = false, is_link = false;
3356 if (ignore_file(de->d_name))
3359 if (de->d_type == DT_LNK)
3361 else if (de->d_type == DT_DIR)
3363 else if (de->d_type == DT_UNKNOWN) {
3366 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3367 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3374 is_link = S_ISLNK(st.st_mode);
3375 is_dir = S_ISDIR(st.st_mode);
3383 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3384 log_error("Failed to open %s/%s: %m", root, de->d_name);
3391 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3392 log_error("Failed to allocate directory string.");
3393 close_nointr_nofail(nfd);
3398 /* This will close nfd, regardless whether it succeeds or not */
3399 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3405 } else if (is_link) {
3409 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3410 log_error("Failed to allocate symlink string.");
3415 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3416 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3424 if ((c = canonicalize_file_name(dest))) {
3425 /* This might fail if the destination
3426 * is already removed */
3432 path_kill_slashes(dest);
3433 if (set_get(remove_symlinks_to, dest)) {
3436 log_info("rm '%s'", p);
3438 if (unlink(p) < 0) {
3439 log_error("Cannot unlink symlink %s: %m", p);
3444 rmdir_parents(p, config_path);
3445 path_kill_slashes(p);
3447 if (!set_get(remove_symlinks_to, p)) {
3449 if ((r = mark_symlink_for_removal(p)) < 0) {
3468 static int remove_marked_symlinks(const char *config_path) {
3472 assert(config_path);
3474 if (set_size(remove_symlinks_to) <= 0)
3477 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3484 if ((cfd = dup(fd)) < 0) {
3489 /* This takes possession of cfd and closes it */
3490 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3496 close_nointr_nofail(fd);
3501 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3508 if (streq(verb, "enable")) {
3511 mkdir_parents(new_path, 0755);
3513 if (symlink(old_path, new_path) >= 0) {
3516 log_info("ln -s '%s' '%s'", old_path, new_path);
3521 if (errno != EEXIST) {
3522 log_error("Cannot link %s to %s: %m", old_path, new_path);
3526 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3528 if (errno == EINVAL) {
3529 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3533 log_error("readlink() failed: %s", strerror(-r));
3537 if (streq(dest, old_path)) {
3543 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3552 log_info("ln -s '%s' '%s'", old_path, new_path);
3554 if (symlink(old_path, new_path) >= 0)
3557 log_error("Cannot link %s to %s: %m", old_path, new_path);
3560 } else if (streq(verb, "disable")) {
3563 if ((r = mark_symlink_for_removal(old_path)) < 0)
3566 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3567 if (errno == ENOENT)
3570 if (errno == EINVAL) {
3571 log_warning("File %s not a symlink, ignoring.", old_path);
3575 log_error("readlink() failed: %s", strerror(-r));
3579 if (!streq(dest, old_path)) {
3580 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3587 if ((r = mark_symlink_for_removal(new_path)) < 0)
3591 log_info("rm '%s'", new_path);
3593 if (unlink(new_path) >= 0)
3596 log_error("Cannot unlink %s: %m", new_path);
3599 } else if (streq(verb, "is-enabled")) {
3602 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3604 if (errno == ENOENT || errno == EINVAL)
3607 log_error("readlink() failed: %s", strerror(-r));
3611 if (streq(dest, old_path)) {
3619 assert_not_reached("Unknown action.");
3622 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3624 char *alias_path = NULL;
3629 assert(config_path);
3631 STRV_FOREACH(s, i->aliases) {
3633 if (!unit_name_is_valid_no_type(*s)) {
3634 log_error("Invalid name %s.", *s);
3640 if (!(alias_path = path_make_absolute(*s, config_path))) {
3641 log_error("Out of memory");
3646 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3649 if (streq(verb, "disable"))
3650 rmdir_parents(alias_path, config_path);
3660 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3662 char *alias_path = NULL;
3667 assert(config_path);
3669 STRV_FOREACH(s, i->wanted_by) {
3670 if (!unit_name_is_valid_no_type(*s)) {
3671 log_error("Invalid name %s.", *s);
3679 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3680 log_error("Out of memory");
3685 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3688 if (streq(verb, "disable"))
3689 rmdir_parents(alias_path, config_path);
3700 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3702 const ConfigItem items[] = {
3703 { "Alias", config_parse_strv, &i->aliases, "Install" },
3704 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3705 { "Also", config_parse_also, NULL, "Install" },
3707 { NULL, NULL, NULL, NULL }
3711 char *filename = NULL;
3718 STRV_FOREACH(p, paths->unit_path) {
3721 if (!(filename = path_make_absolute(i->name, *p))) {
3722 log_error("Out of memory");
3726 /* Ensure that we don't follow symlinks */
3727 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3728 if ((f = fdopen(fd, "re")))
3731 if (errno == ELOOP) {
3732 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3737 if (errno != ENOENT) {
3738 log_error("Failed to open %s: %m", filename);
3748 log_error("Couldn't find %s.", i->name);
3754 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3761 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3764 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3767 if ((r = mark_symlink_for_removal(filename)) < 0)
3770 if ((r = remove_marked_symlinks(config_path)) < 0)
3776 static char *get_config_path(void) {
3778 if (arg_session && arg_global)
3779 return strdup(SESSION_CONFIG_UNIT_PATH);
3784 if (session_config_home(&p) < 0)
3790 return strdup(SYSTEM_CONFIG_UNIT_PATH);
3793 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3797 char *config_path = NULL;
3800 const char *verb = args[0];
3802 dbus_error_init(&error);
3805 if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3806 log_error("Failed to determine lookup paths: %s", strerror(-r));
3810 if (!(config_path = get_config_path())) {
3811 log_error("Failed to determine config path");
3816 will_install = hashmap_new(string_hash_func, string_compare_func);
3817 have_installed = hashmap_new(string_hash_func, string_compare_func);
3819 if (!will_install || !have_installed) {
3820 log_error("Failed to allocate unit sets.");
3825 if (!arg_defaults && streq(verb, "disable"))
3826 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3827 log_error("Failed to allocate symlink sets.");
3832 for (j = 1; j < n; j++)
3833 if ((r = install_info_add(args[j])) < 0) {
3834 log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
3838 while ((i = hashmap_first(will_install))) {
3841 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3843 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3851 /* In test mode and found something */
3857 if (streq(verb, "is-enabled"))
3858 r = r > 0 ? 0 : -ENOENT;
3860 /* Don't try to reload anything if the user asked us to not do this */
3862 /* Don't try to reload anything when updating a unit globally */
3864 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3865 (arg_session || sd_booted() > 0) &&
3866 /* Don't try to reload anything if we are running in a chroot environment */
3867 (arg_session || running_in_chroot() <= 0) ) {
3870 if ((q = daemon_reload(bus, args, n)) < 0)
3875 install_info_hashmap_free(will_install);
3876 install_info_hashmap_free(have_installed);
3878 set_free_free(remove_symlinks_to);
3880 lookup_paths_free(&paths);
3887 static int systemctl_help(void) {
3889 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3890 "Send control commands to or query the systemd manager.\n\n"
3891 " -h --help Show this help\n"
3892 " --version Show package version\n"
3893 " -t --type=TYPE List only units of a particular type\n"
3894 " -p --property=NAME Show only properties by this name\n"
3895 " -a --all Show all units/properties, including dead/empty ones\n"
3896 " --full Don't ellipsize unit names on output\n"
3897 " --fail When queueing a new job, fail if conflicting jobs are\n"
3899 " -q --quiet Suppress output\n"
3900 " --no-block Do not wait until operation finished\n"
3901 " --system Connect to system bus\n"
3902 " --session Connect to session bus\n"
3903 " --order When generating graph for dot, show only order\n"
3904 " --require When generating graph for dot, show only requirement\n"
3905 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3906 " --global Enable/disable unit files globally\n"
3907 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3909 " --force When enabling unit files, override existing symlinks\n"
3910 " --defaults When disabling unit files, remove default symlinks only\n\n"
3912 " list-units List units\n"
3913 " start [NAME...] Start (activate) one or more units\n"
3914 " stop [NAME...] Stop (deactivate) one or more units\n"
3915 " reload [NAME...] Reload one or more units\n"
3916 " restart [NAME...] Start or restart one or more units\n"
3917 " try-restart [NAME...] Restart one or more units if active\n"
3918 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3919 " otherwise start or restart\n"
3920 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3921 " otherwise restart if active\n"
3922 " isolate [NAME] Start one unit and stop all others\n"
3923 " is-active [NAME...] Check whether units are active\n"
3924 " status [NAME...|PID...] Show runtime status of one or more units\n"
3925 " show [NAME...|JOB...] Show properties of one or more\n"
3926 " units/jobs or the manager\n"
3927 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
3929 " enable [NAME...] Enable one or more unit files\n"
3930 " disable [NAME...] Disable one or more unit files\n"
3931 " is-enabled [NAME...] Check whether unit files are enabled\n"
3932 " load [NAME...] Load one or more units\n"
3933 " list-jobs List jobs\n"
3934 " cancel [JOB...] Cancel all, one, or more jobs\n"
3935 " monitor Monitor unit/job changes\n"
3936 " dump Dump server status\n"
3937 " dot Dump dependency graph for dot(1)\n"
3938 " snapshot [NAME] Create a snapshot\n"
3939 " delete [NAME...] Remove one or more snapshots\n"
3940 " daemon-reload Reload systemd manager configuration\n"
3941 " daemon-reexec Reexecute systemd manager\n"
3942 " daemon-exit Ask the systemd manager to quit\n"
3943 " show-environment Dump environment\n"
3944 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3945 " unset-environment [NAME...] Unset one or more environment variables\n"
3946 " halt Shut down and halt the system\n"
3947 " poweroff Shut down and power-off the system\n"
3948 " reboot Shut down and reboot the system\n"
3949 " rescue Enter system rescue mode\n"
3950 " emergency Enter system emergency mode\n"
3951 " default Enter system default mode\n",
3952 program_invocation_short_name);
3957 static int halt_help(void) {
3959 printf("%s [OPTIONS...]\n\n"
3960 "%s the system.\n\n"
3961 " --help Show this help\n"
3962 " --halt Halt the machine\n"
3963 " -p --poweroff Switch off the machine\n"
3964 " --reboot Reboot the machine\n"
3965 " -f --force Force immediate halt/power-off/reboot\n"
3966 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3967 " -d --no-wtmp Don't write wtmp record\n"
3968 " -n --no-sync Don't sync before halt/power-off/reboot\n"
3969 " --no-wall Don't send wall message before halt/power-off/reboot\n",
3970 program_invocation_short_name,
3971 arg_action == ACTION_REBOOT ? "Reboot" :
3972 arg_action == ACTION_POWEROFF ? "Power off" :
3978 static int shutdown_help(void) {
3980 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3981 "Shut down the system.\n\n"
3982 " --help Show this help\n"
3983 " -H --halt Halt the machine\n"
3984 " -P --poweroff Power-off the machine\n"
3985 " -r --reboot Reboot the machine\n"
3986 " -h Equivalent to --poweroff, overriden by --halt\n"
3987 " -k Don't halt/power-off/reboot, just send warnings\n"
3988 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3989 " -c Cancel a pending shutdown\n",
3990 program_invocation_short_name);
3995 static int telinit_help(void) {
3997 printf("%s [OPTIONS...] {COMMAND}\n\n"
3998 "Send control commands to the init daemon.\n\n"
3999 " --help Show this help\n"
4000 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4002 " 0 Power-off the machine\n"
4003 " 6 Reboot the machine\n"
4004 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4005 " 1, s, S Enter rescue mode\n"
4006 " q, Q Reload init daemon configuration\n"
4007 " u, U Reexecute init daemon\n",
4008 program_invocation_short_name);
4013 static int runlevel_help(void) {
4015 printf("%s [OPTIONS...]\n\n"
4016 "Prints the previous and current runlevel of the init system.\n\n"
4017 " --help Show this help\n",
4018 program_invocation_short_name);
4023 static int systemctl_parse_argv(int argc, char *argv[]) {
4041 static const struct option options[] = {
4042 { "help", no_argument, NULL, 'h' },
4043 { "version", no_argument, NULL, ARG_VERSION },
4044 { "type", required_argument, NULL, 't' },
4045 { "property", required_argument, NULL, 'p' },
4046 { "all", no_argument, NULL, 'a' },
4047 { "full", no_argument, NULL, ARG_FULL },
4048 { "fail", no_argument, NULL, ARG_FAIL },
4049 { "session", no_argument, NULL, ARG_SESSION },
4050 { "system", no_argument, NULL, ARG_SYSTEM },
4051 { "global", no_argument, NULL, ARG_GLOBAL },
4052 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4053 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4054 { "quiet", no_argument, NULL, 'q' },
4055 { "order", no_argument, NULL, ARG_ORDER },
4056 { "require", no_argument, NULL, ARG_REQUIRE },
4057 { "force", no_argument, NULL, ARG_FORCE },
4058 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4059 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4060 { NULL, 0, NULL, 0 }
4068 while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
4077 puts(PACKAGE_STRING);
4079 puts(SYSTEMD_FEATURES);
4089 if (!(l = strv_append(arg_property, optarg)))
4092 strv_free(arg_property);
4095 /* If the user asked for a particular
4096 * property, show it to him, even if it is
4115 arg_session = false;
4119 arg_no_block = true;
4127 arg_dot = DOT_ORDER;
4131 arg_dot = DOT_REQUIRE;
4147 arg_no_reload = true;
4156 arg_defaults = true;
4163 log_error("Unknown option code %c", c);
4171 static int halt_parse_argv(int argc, char *argv[]) {
4180 static const struct option options[] = {
4181 { "help", no_argument, NULL, ARG_HELP },
4182 { "halt", no_argument, NULL, ARG_HALT },
4183 { "poweroff", no_argument, NULL, 'p' },
4184 { "reboot", no_argument, NULL, ARG_REBOOT },
4185 { "force", no_argument, NULL, 'f' },
4186 { "wtmp-only", no_argument, NULL, 'w' },
4187 { "no-wtmp", no_argument, NULL, 'd' },
4188 { "no-sync", no_argument, NULL, 'n' },
4189 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4190 { NULL, 0, NULL, 0 }
4198 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4199 if (runlevel == '0' || runlevel == '6')
4200 arg_immediate = true;
4202 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4210 arg_action = ACTION_HALT;
4214 if (arg_action != ACTION_REBOOT)
4215 arg_action = ACTION_POWEROFF;
4219 arg_action = ACTION_REBOOT;
4223 arg_immediate = true;
4244 /* Compatibility nops */
4251 log_error("Unknown option code %c", c);
4256 if (optind < argc) {
4257 log_error("Too many arguments.");
4264 static int parse_time_spec(const char *t, usec_t *_u) {
4268 if (streq(t, "now"))
4270 else if (t[0] == '+') {
4273 if (safe_atou64(t + 1, &u) < 0)
4276 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4285 hour = strtol(t, &e, 10);
4286 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4289 minute = strtol(e+1, &e, 10);
4290 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4293 n = now(CLOCK_REALTIME);
4294 s = (time_t) (n / USEC_PER_SEC);
4297 assert_se(localtime_r(&s, &tm));
4299 tm.tm_hour = (int) hour;
4300 tm.tm_min = (int) minute;
4303 assert_se(s = mktime(&tm));
4305 *_u = (usec_t) s * USEC_PER_SEC;
4308 *_u += USEC_PER_DAY;
4314 static int shutdown_parse_argv(int argc, char *argv[]) {
4321 static const struct option options[] = {
4322 { "help", no_argument, NULL, ARG_HELP },
4323 { "halt", no_argument, NULL, 'H' },
4324 { "poweroff", no_argument, NULL, 'P' },
4325 { "reboot", no_argument, NULL, 'r' },
4326 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4327 { NULL, 0, NULL, 0 }
4335 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4343 arg_action = ACTION_HALT;
4347 arg_action = ACTION_POWEROFF;
4351 arg_action = ACTION_REBOOT;
4355 if (arg_action != ACTION_HALT)
4356 arg_action = ACTION_POWEROFF;
4369 /* Compatibility nops */
4373 arg_action = ACTION_CANCEL_SHUTDOWN;
4380 log_error("Unknown option code %c", c);
4385 if (argc > optind) {
4386 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4387 log_error("Failed to parse time specification: %s", argv[optind]);
4391 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4393 /* We skip the time argument */
4394 if (argc > optind + 1)
4395 arg_wall = argv + optind + 1;
4402 static int telinit_parse_argv(int argc, char *argv[]) {
4409 static const struct option options[] = {
4410 { "help", no_argument, NULL, ARG_HELP },
4411 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4412 { NULL, 0, NULL, 0 }
4415 static const struct {
4419 { '0', ACTION_POWEROFF },
4420 { '6', ACTION_REBOOT },
4421 { '1', ACTION_RESCUE },
4422 { '2', ACTION_RUNLEVEL2 },
4423 { '3', ACTION_RUNLEVEL3 },
4424 { '4', ACTION_RUNLEVEL4 },
4425 { '5', ACTION_RUNLEVEL5 },
4426 { 's', ACTION_RESCUE },
4427 { 'S', ACTION_RESCUE },
4428 { 'q', ACTION_RELOAD },
4429 { 'Q', ACTION_RELOAD },
4430 { 'u', ACTION_REEXEC },
4431 { 'U', ACTION_REEXEC }
4440 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4455 log_error("Unknown option code %c", c);
4460 if (optind >= argc) {
4465 if (optind + 1 < argc) {
4466 log_error("Too many arguments.");
4470 if (strlen(argv[optind]) != 1) {
4471 log_error("Expected single character argument.");
4475 for (i = 0; i < ELEMENTSOF(table); i++)
4476 if (table[i].from == argv[optind][0])
4479 if (i >= ELEMENTSOF(table)) {
4480 log_error("Unknown command %s.", argv[optind]);
4484 arg_action = table[i].to;
4491 static int runlevel_parse_argv(int argc, char *argv[]) {
4497 static const struct option options[] = {
4498 { "help", no_argument, NULL, ARG_HELP },
4499 { NULL, 0, NULL, 0 }
4507 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4518 log_error("Unknown option code %c", c);
4523 if (optind < argc) {
4524 log_error("Too many arguments.");
4531 static int parse_argv(int argc, char *argv[]) {
4535 if (program_invocation_short_name) {
4537 if (strstr(program_invocation_short_name, "halt")) {
4538 arg_action = ACTION_HALT;
4539 return halt_parse_argv(argc, argv);
4540 } else if (strstr(program_invocation_short_name, "poweroff")) {
4541 arg_action = ACTION_POWEROFF;
4542 return halt_parse_argv(argc, argv);
4543 } else if (strstr(program_invocation_short_name, "reboot")) {
4544 arg_action = ACTION_REBOOT;
4545 return halt_parse_argv(argc, argv);
4546 } else if (strstr(program_invocation_short_name, "shutdown")) {
4547 arg_action = ACTION_POWEROFF;
4548 return shutdown_parse_argv(argc, argv);
4549 } else if (strstr(program_invocation_short_name, "init")) {
4551 if (sd_booted() > 0) {
4552 arg_action = ACTION_INVALID;
4553 return telinit_parse_argv(argc, argv);
4555 /* Hmm, so some other init system is
4556 * running, we need to forward this
4557 * request to it. For now we simply
4558 * guess that it is Upstart. */
4560 execv("/lib/upstart/telinit", argv);
4562 log_error("Couldn't find an alternative telinit implementation to spawn.");
4566 } else if (strstr(program_invocation_short_name, "runlevel")) {
4567 arg_action = ACTION_RUNLEVEL;
4568 return runlevel_parse_argv(argc, argv);
4572 arg_action = ACTION_SYSTEMCTL;
4573 return systemctl_parse_argv(argc, argv);
4576 static int action_to_runlevel(void) {
4578 static const char table[_ACTION_MAX] = {
4579 [ACTION_HALT] = '0',
4580 [ACTION_POWEROFF] = '0',
4581 [ACTION_REBOOT] = '6',
4582 [ACTION_RUNLEVEL2] = '2',
4583 [ACTION_RUNLEVEL3] = '3',
4584 [ACTION_RUNLEVEL4] = '4',
4585 [ACTION_RUNLEVEL5] = '5',
4586 [ACTION_RESCUE] = '1'
4589 assert(arg_action < _ACTION_MAX);
4591 return table[arg_action];
4594 static int talk_upstart(void) {
4595 DBusMessage *m = NULL, *reply = NULL;
4597 int previous, rl, r;
4599 env1_buf[] = "RUNLEVEL=X",
4600 env2_buf[] = "PREVLEVEL=X";
4601 char *env1 = env1_buf, *env2 = env2_buf;
4602 const char *emit = "runlevel";
4603 dbus_bool_t b_false = FALSE;
4604 DBusMessageIter iter, sub;
4605 DBusConnection *bus;
4607 dbus_error_init(&error);
4609 if (!(rl = action_to_runlevel()))
4612 if (utmp_get_runlevel(&previous, NULL) < 0)
4615 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4616 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4621 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4626 if ((r = bus_check_peercred(bus)) < 0) {
4627 log_error("Failed to verify owner of bus.");
4631 if (!(m = dbus_message_new_method_call(
4632 "com.ubuntu.Upstart",
4633 "/com/ubuntu/Upstart",
4634 "com.ubuntu.Upstart0_6",
4637 log_error("Could not allocate message.");
4642 dbus_message_iter_init_append(m, &iter);
4644 env1_buf[sizeof(env1_buf)-2] = rl;
4645 env2_buf[sizeof(env2_buf)-2] = previous;
4647 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4648 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4649 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4650 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4651 !dbus_message_iter_close_container(&iter, &sub) ||
4652 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4653 log_error("Could not append arguments to message.");
4658 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4660 if (error_is_no_service(&error)) {
4665 log_error("Failed to issue method call: %s", bus_error_message(&error));
4674 dbus_message_unref(m);
4677 dbus_message_unref(reply);
4680 dbus_connection_flush(bus);
4681 dbus_connection_close(bus);
4682 dbus_connection_unref(bus);
4685 dbus_error_free(&error);
4690 static int talk_initctl(void) {
4691 struct init_request request;
4695 if (!(rl = action_to_runlevel()))
4699 request.magic = INIT_MAGIC;
4700 request.sleeptime = 0;
4701 request.cmd = INIT_CMD_RUNLVL;
4702 request.runlevel = rl;
4704 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4706 if (errno == ENOENT)
4709 log_error("Failed to open "INIT_FIFO": %m");
4714 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4715 close_nointr_nofail(fd);
4718 log_error("Failed to write to "INIT_FIFO": %m");
4719 return errno ? -errno : -EIO;
4725 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4727 static const struct {
4735 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4737 { "list-units", LESS, 1, list_units },
4738 { "list-jobs", EQUAL, 1, list_jobs },
4739 { "clear-jobs", EQUAL, 1, daemon_reload },
4740 { "load", MORE, 2, load_unit },
4741 { "cancel", MORE, 2, cancel_job },
4742 { "start", MORE, 2, start_unit },
4743 { "stop", MORE, 2, start_unit },
4744 { "reload", MORE, 2, start_unit },
4745 { "restart", MORE, 2, start_unit },
4746 { "try-restart", MORE, 2, start_unit },
4747 { "reload-or-restart", MORE, 2, start_unit },
4748 { "reload-or-try-restart", MORE, 2, start_unit },
4749 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4750 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4751 { "isolate", EQUAL, 2, start_unit },
4752 { "is-active", MORE, 2, check_unit },
4753 { "check", MORE, 2, check_unit },
4754 { "show", MORE, 1, show },
4755 { "status", MORE, 2, show },
4756 { "monitor", EQUAL, 1, monitor },
4757 { "dump", EQUAL, 1, dump },
4758 { "dot", EQUAL, 1, dot },
4759 { "snapshot", LESS, 2, snapshot },
4760 { "delete", MORE, 2, delete_snapshot },
4761 { "daemon-reload", EQUAL, 1, daemon_reload },
4762 { "daemon-reexec", EQUAL, 1, daemon_reload },
4763 { "daemon-exit", EQUAL, 1, daemon_reload },
4764 { "show-environment", EQUAL, 1, show_enviroment },
4765 { "set-environment", MORE, 2, set_environment },
4766 { "unset-environment", MORE, 2, set_environment },
4767 { "halt", EQUAL, 1, start_special },
4768 { "poweroff", EQUAL, 1, start_special },
4769 { "reboot", EQUAL, 1, start_special },
4770 { "default", EQUAL, 1, start_special },
4771 { "rescue", EQUAL, 1, start_special },
4772 { "emergency", EQUAL, 1, start_special },
4773 { "reset-failed", MORE, 1, reset_failed },
4774 { "enable", MORE, 2, enable_unit },
4775 { "disable", MORE, 2, enable_unit },
4776 { "is-enabled", MORE, 2, enable_unit }
4786 left = argc - optind;
4789 /* Special rule: no arguments means "list-units" */
4792 if (streq(argv[optind], "help")) {
4797 for (i = 0; i < ELEMENTSOF(verbs); i++)
4798 if (streq(argv[optind], verbs[i].verb))
4801 if (i >= ELEMENTSOF(verbs)) {
4802 log_error("Unknown operation %s", argv[optind]);
4807 switch (verbs[i].argc_cmp) {
4810 if (left != verbs[i].argc) {
4811 log_error("Invalid number of arguments.");
4818 if (left < verbs[i].argc) {
4819 log_error("Too few arguments.");
4826 if (left > verbs[i].argc) {
4827 log_error("Too many arguments.");
4834 assert_not_reached("Unknown comparison operator.");
4837 /* Require a bus connection for all operations but
4839 if (!streq(verbs[i].verb, "enable") &&
4840 !streq(verbs[i].verb, "disable") &&
4842 log_error("Failed to get D-Bus connection: %s", error->message);
4846 return verbs[i].dispatch(bus, argv + optind, left);
4849 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
4851 struct msghdr msghdr;
4853 union sockaddr_union sockaddr;
4854 struct shutdownd_command c;
4862 strncpy(c.wall_message, message, sizeof(c.wall_message));
4864 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4868 sockaddr.sa.sa_family = AF_UNIX;
4869 sockaddr.un.sun_path[0] = 0;
4870 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
4873 iovec.iov_base = (char*) &c;
4874 iovec.iov_len = sizeof(c);
4877 msghdr.msg_name = &sockaddr;
4878 msghdr.msg_namelen = sizeof(sa_family_t) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
4880 msghdr.msg_iov = &iovec;
4881 msghdr.msg_iovlen = 1;
4883 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
4884 close_nointr_nofail(fd);
4888 close_nointr_nofail(fd);
4892 static int reload_with_fallback(DBusConnection *bus) {
4895 /* First, try systemd via D-Bus. */
4896 if (daemon_reload(bus, NULL, 0) > 0)
4900 /* Nothing else worked, so let's try signals */
4901 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
4903 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
4904 log_error("kill() failed: %m");
4911 static int start_with_fallback(DBusConnection *bus) {
4914 /* First, try systemd via D-Bus. */
4915 if (start_unit(bus, NULL, 0) >= 0)
4919 /* Hmm, talking to systemd via D-Bus didn't work. Then
4920 * let's try to talk to Upstart via D-Bus. */
4921 if (talk_upstart() > 0)
4924 /* Nothing else worked, so let's try
4926 if (talk_initctl() > 0)
4929 log_error("Failed to talk to init daemon.");
4933 warn_wall(arg_action);
4937 static int halt_main(DBusConnection *bus) {
4940 if (geteuid() != 0) {
4941 log_error("Must be root.");
4947 char date[FORMAT_TIMESTAMP_MAX];
4949 m = strv_join(arg_wall, " ");
4950 r = send_shutdownd(arg_when,
4951 arg_action == ACTION_HALT ? 'H' :
4952 arg_action == ACTION_POWEROFF ? 'P' :
4959 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
4961 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
4962 format_timestamp(date, sizeof(date), arg_when));
4967 if (!arg_dry && !arg_immediate)
4968 return start_with_fallback(bus);
4971 if (sd_booted() > 0)
4972 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
4973 else if ((r = utmp_put_shutdown(0)) < 0)
4974 log_warning("Failed to write utmp record: %s", strerror(-r));
4983 /* Make sure C-A-D is handled by the kernel from this
4985 reboot(RB_ENABLE_CAD);
4987 switch (arg_action) {
4990 log_info("Halting.");
4991 reboot(RB_HALT_SYSTEM);
4994 case ACTION_POWEROFF:
4995 log_info("Powering off.");
4996 reboot(RB_POWER_OFF);
5000 log_info("Rebooting.");
5001 reboot(RB_AUTOBOOT);
5005 assert_not_reached("Unknown halt action.");
5008 /* We should never reach this. */
5012 static int runlevel_main(void) {
5013 int r, runlevel, previous;
5015 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5016 printf("unknown\n");
5021 previous <= 0 ? 'N' : previous,
5022 runlevel <= 0 ? 'N' : runlevel);
5027 int main(int argc, char*argv[]) {
5028 int r, retval = EXIT_FAILURE;
5029 DBusConnection *bus = NULL;
5032 dbus_error_init(&error);
5034 log_parse_environment();
5037 if ((r = parse_argv(argc, argv)) < 0)
5040 retval = EXIT_SUCCESS;
5044 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5045 * let's shortcut this */
5046 if (arg_action == ACTION_RUNLEVEL) {
5047 r = runlevel_main();
5048 retval = r < 0 ? EXIT_FAILURE : r;
5052 bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5054 switch (arg_action) {
5056 case ACTION_SYSTEMCTL:
5057 r = systemctl_main(bus, argc, argv, &error);
5061 case ACTION_POWEROFF:
5066 case ACTION_RUNLEVEL2:
5067 case ACTION_RUNLEVEL3:
5068 case ACTION_RUNLEVEL4:
5069 case ACTION_RUNLEVEL5:
5071 case ACTION_EMERGENCY:
5072 case ACTION_DEFAULT:
5073 r = start_with_fallback(bus);
5078 r = reload_with_fallback(bus);
5081 case ACTION_CANCEL_SHUTDOWN:
5082 r = send_shutdownd(0, 0, false, NULL);
5085 case ACTION_INVALID:
5086 case ACTION_RUNLEVEL:
5088 assert_not_reached("Unknown action");
5091 retval = r < 0 ? EXIT_FAILURE : r;
5096 dbus_connection_flush(bus);
5097 dbus_connection_close(bus);
5098 dbus_connection_unref(bus);
5101 dbus_error_free(&error);
5105 strv_free(arg_property);