1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <sys/reboot.h>
28 #include <sys/ioctl.h>
32 #include <sys/socket.h>
35 #include <dbus/dbus.h>
41 #include "utmp-wtmp.h"
45 #include "dbus-common.h"
46 #include "cgroup-show.h"
47 #include "cgroup-util.h"
49 #include "path-lookup.h"
50 #include "conf-parser.h"
51 #include "sd-daemon.h"
52 #include "shutdownd.h"
53 #include "exit-status.h"
54 #include "bus-errors.h"
57 static const char *arg_type = NULL;
58 static char **arg_property = NULL;
59 static bool arg_all = false;
60 static bool arg_fail = false;
61 static bool arg_session = false;
62 static bool arg_global = false;
63 static bool arg_immediate = false;
64 static bool arg_no_block = false;
65 static bool arg_no_wtmp = false;
66 static bool arg_no_sync = false;
67 static bool arg_no_wall = false;
68 static bool arg_no_reload = false;
69 static bool arg_dry = false;
70 static bool arg_quiet = false;
71 static bool arg_full = false;
72 static bool arg_force = false;
73 static bool arg_defaults = false;
74 static char **arg_wall = NULL;
75 static usec_t arg_when = 0;
92 ACTION_CANCEL_SHUTDOWN,
94 } arg_action = ACTION_SYSTEMCTL;
101 static bool private_bus = false;
103 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
105 static bool on_tty(void) {
108 if (_unlikely_(t < 0))
109 t = isatty(STDOUT_FILENO) > 0;
114 static const char *ansi_highlight(bool b) {
119 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
122 static const char *ansi_highlight_green(bool b) {
127 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
130 static bool error_is_no_service(const DBusError *error) {
133 if (!dbus_error_is_set(error))
136 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
139 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
142 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
145 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
148 if (!dbus_error_is_set(error))
151 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
152 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
153 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
154 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
155 return EXIT_NOPERMISSION;
157 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
158 return EXIT_NOTINSTALLED;
160 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
161 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
162 return EXIT_NOTIMPLEMENTED;
164 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
165 return EXIT_NOTCONFIGURED;
173 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
178 if (dbus_message_iter_get_arg_type(iter) != type)
181 dbus_message_iter_get_basic(iter, data);
183 if (!dbus_message_iter_next(iter) != !next)
189 static void warn_wall(enum action action) {
190 static const char *table[_ACTION_MAX] = {
191 [ACTION_HALT] = "The system is going down for system halt NOW!",
192 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
193 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
194 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
195 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
204 if (!(p = strv_join(arg_wall, " "))) {
205 log_error("Failed to join strings.");
221 utmp_wall(table[action]);
226 const char *description;
227 const char *load_state;
228 const char *active_state;
229 const char *sub_state;
230 const char *following;
231 const char *unit_path;
233 const char *job_type;
234 const char *job_path;
237 static int compare_unit_info(const void *a, const void *b) {
239 const struct unit_info *u = a, *v = b;
241 d1 = strrchr(u->id, '.');
242 d2 = strrchr(v->id, '.');
247 if ((r = strcasecmp(d1, d2)) != 0)
251 return strcasecmp(u->id, v->id);
254 static bool output_show_job(const struct unit_info *u) {
256 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
257 streq(dot+1, arg_type))) &&
258 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0);
261 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
262 unsigned active_len, sub_len, job_len;
264 active_len = strlen("ACTIVE");
265 sub_len = strlen("SUB");
266 job_len = strlen("JOB");
267 for (const struct unit_info *u = unit_infos; u < unit_infos + c; u++) {
268 if (output_show_job(u)) {
269 active_len = MAX(active_len, strlen(u->active_state));
270 sub_len = MAX(sub_len, strlen(u->sub_state));
272 job_len = MAX(job_len, strlen(u->job_type));
277 printf("%-25s %-6s %-*s %-*s %-*s", "UNIT", "LOAD",
278 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
279 if (columns() >= 80+12 || arg_full)
280 printf(" %s\n", "DESCRIPTION");
285 for (const struct unit_info *u = unit_infos; u < unit_infos + c; u++) {
286 if (output_show_job(u)) {
289 const char *on_loaded, *off_loaded;
290 const char *on_active, *off_active;
292 if (!streq(u->load_state, "loaded")) {
293 on_loaded = ansi_highlight(true);
294 off_loaded = ansi_highlight(false);
296 on_loaded = off_loaded = "";
298 if (streq(u->active_state, "failed")) {
299 on_active = ansi_highlight(true);
300 off_active = ansi_highlight(false);
302 on_active = off_active = "";
304 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
306 printf("%-25s %s%-6s%s %s%-*s %-*s%s%n",
308 on_loaded, u->load_state, off_loaded,
309 on_active, active_len, u->active_state,
310 sub_len, u->sub_state, off_active,
315 a -= strlen(on_loaded) + strlen(off_loaded);
316 a -= strlen(on_active) + strlen(off_active);
319 printf(" %-*s", job_len, u->job_type);
323 if (a + b + 1 < columns()) {
325 printf(" %-*s", job_len, "");
328 printf(" %s", u->description);
330 printf(" %.*s", columns() - a - b - 1, u->description);
338 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
339 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
340 "SUB = The low-level unit activation state, values depend on unit type.\n"
341 "JOB = Pending job for the unit.\n");
344 printf("\n%u units listed.\n", c);
346 printf("\n%u units listed. Pass --all to see inactive units, too.\n", c);
350 static int list_units(DBusConnection *bus, char **args, unsigned n) {
351 DBusMessage *m = NULL, *reply = NULL;
354 DBusMessageIter iter, sub, sub2;
355 unsigned c = 0, n_units = 0;
356 struct unit_info *unit_infos = NULL;
358 dbus_error_init(&error);
362 if (!(m = dbus_message_new_method_call(
363 "org.freedesktop.systemd1",
364 "/org/freedesktop/systemd1",
365 "org.freedesktop.systemd1.Manager",
367 log_error("Could not allocate message.");
371 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
372 log_error("Failed to issue method call: %s", bus_error_message(&error));
377 if (!dbus_message_iter_init(reply, &iter) ||
378 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
379 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
380 log_error("Failed to parse reply.");
385 dbus_message_iter_recurse(&iter, &sub);
387 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
390 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
391 log_error("Failed to parse reply.");
399 n_units = MAX(2*c, 16);
400 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
403 log_error("Failed to allocate unit array.");
413 dbus_message_iter_recurse(&sub, &sub2);
415 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
416 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
417 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
418 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
419 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
420 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
421 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
422 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
423 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
424 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
425 log_error("Failed to parse reply.");
430 dbus_message_iter_next(&sub);
434 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
435 output_units_list(unit_infos, c);
441 dbus_message_unref(m);
444 dbus_message_unref(reply);
448 dbus_error_free(&error);
453 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
454 static const char * const colors[] = {
455 "Requires", "[color=\"black\"]",
456 "RequiresOverridable", "[color=\"black\"]",
457 "Requisite", "[color=\"darkblue\"]",
458 "RequisiteOverridable", "[color=\"darkblue\"]",
459 "Wants", "[color=\"darkgrey\"]",
460 "Conflicts", "[color=\"red\"]",
461 "ConflictedBy", "[color=\"red\"]",
462 "After", "[color=\"green\"]"
465 const char *c = NULL;
472 for (i = 0; i < ELEMENTSOF(colors); i += 2)
473 if (streq(colors[i], prop)) {
481 if (arg_dot != DOT_ALL)
482 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
485 switch (dbus_message_iter_get_arg_type(iter)) {
487 case DBUS_TYPE_ARRAY:
489 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
492 dbus_message_iter_recurse(iter, &sub);
494 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
497 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
498 dbus_message_iter_get_basic(&sub, &s);
499 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
501 dbus_message_iter_next(&sub);
511 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
512 DBusMessage *m = NULL, *reply = NULL;
513 const char *interface = "org.freedesktop.systemd1.Unit";
516 DBusMessageIter iter, sub, sub2, sub3;
521 dbus_error_init(&error);
523 if (!(m = dbus_message_new_method_call(
524 "org.freedesktop.systemd1",
526 "org.freedesktop.DBus.Properties",
528 log_error("Could not allocate message.");
533 if (!dbus_message_append_args(m,
534 DBUS_TYPE_STRING, &interface,
535 DBUS_TYPE_INVALID)) {
536 log_error("Could not append arguments to message.");
541 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
542 log_error("Failed to issue method call: %s", bus_error_message(&error));
547 if (!dbus_message_iter_init(reply, &iter) ||
548 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
549 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
550 log_error("Failed to parse reply.");
555 dbus_message_iter_recurse(&iter, &sub);
557 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
560 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
561 log_error("Failed to parse reply.");
566 dbus_message_iter_recurse(&sub, &sub2);
568 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
569 log_error("Failed to parse reply.");
574 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
575 log_error("Failed to parse reply.");
580 dbus_message_iter_recurse(&sub2, &sub3);
582 if (dot_one_property(name, prop, &sub3)) {
583 log_error("Failed to parse reply.");
588 dbus_message_iter_next(&sub);
595 dbus_message_unref(m);
598 dbus_message_unref(reply);
600 dbus_error_free(&error);
605 static int dot(DBusConnection *bus, char **args, unsigned n) {
606 DBusMessage *m = NULL, *reply = NULL;
609 DBusMessageIter iter, sub, sub2;
611 dbus_error_init(&error);
615 if (!(m = dbus_message_new_method_call(
616 "org.freedesktop.systemd1",
617 "/org/freedesktop/systemd1",
618 "org.freedesktop.systemd1.Manager",
620 log_error("Could not allocate message.");
624 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
625 log_error("Failed to issue method call: %s", bus_error_message(&error));
630 if (!dbus_message_iter_init(reply, &iter) ||
631 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
632 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
633 log_error("Failed to parse reply.");
638 printf("digraph systemd {\n");
640 dbus_message_iter_recurse(&iter, &sub);
641 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
642 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
644 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
645 log_error("Failed to parse reply.");
650 dbus_message_iter_recurse(&sub, &sub2);
652 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
653 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
654 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
655 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
656 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
657 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
658 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
659 log_error("Failed to parse reply.");
664 if ((r = dot_one(bus, id, unit_path)) < 0)
667 /* printf("\t\"%s\";\n", id); */
668 dbus_message_iter_next(&sub);
673 log_info(" Color legend: black = Requires\n"
674 " dark blue = Requisite\n"
675 " dark grey = Wants\n"
679 if (isatty(fileno(stdout)))
680 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
681 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
687 dbus_message_unref(m);
690 dbus_message_unref(reply);
692 dbus_error_free(&error);
697 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
698 DBusMessage *m = NULL, *reply = NULL;
701 DBusMessageIter iter, sub, sub2;
704 dbus_error_init(&error);
708 if (!(m = dbus_message_new_method_call(
709 "org.freedesktop.systemd1",
710 "/org/freedesktop/systemd1",
711 "org.freedesktop.systemd1.Manager",
713 log_error("Could not allocate message.");
717 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
718 log_error("Failed to issue method call: %s", bus_error_message(&error));
723 if (!dbus_message_iter_init(reply, &iter) ||
724 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
725 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
726 log_error("Failed to parse reply.");
731 dbus_message_iter_recurse(&iter, &sub);
733 if (isatty(STDOUT_FILENO))
734 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
736 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
737 const char *name, *type, *state, *job_path, *unit_path;
741 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
742 log_error("Failed to parse reply.");
747 dbus_message_iter_recurse(&sub, &sub2);
749 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
750 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
751 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
752 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
753 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
754 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
755 log_error("Failed to parse reply.");
760 e = arg_full ? NULL : ellipsize(name, 25, 33);
761 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
766 dbus_message_iter_next(&sub);
769 if (isatty(STDOUT_FILENO))
770 printf("\n%u jobs listed.\n", k);
776 dbus_message_unref(m);
779 dbus_message_unref(reply);
781 dbus_error_free(&error);
786 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
787 DBusMessage *m = NULL, *reply = NULL;
792 dbus_error_init(&error);
797 for (i = 1; i < n; i++) {
799 if (!(m = dbus_message_new_method_call(
800 "org.freedesktop.systemd1",
801 "/org/freedesktop/systemd1",
802 "org.freedesktop.systemd1.Manager",
804 log_error("Could not allocate message.");
809 if (!dbus_message_append_args(m,
810 DBUS_TYPE_STRING, &args[i],
811 DBUS_TYPE_INVALID)) {
812 log_error("Could not append arguments to message.");
817 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
818 log_error("Failed to issue method call: %s", bus_error_message(&error));
823 dbus_message_unref(m);
824 dbus_message_unref(reply);
833 dbus_message_unref(m);
836 dbus_message_unref(reply);
838 dbus_error_free(&error);
843 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
844 DBusMessage *m = NULL, *reply = NULL;
849 dbus_error_init(&error);
855 return daemon_reload(bus, args, n);
857 for (i = 1; i < n; i++) {
861 if (!(m = dbus_message_new_method_call(
862 "org.freedesktop.systemd1",
863 "/org/freedesktop/systemd1",
864 "org.freedesktop.systemd1.Manager",
866 log_error("Could not allocate message.");
871 if ((r = safe_atou(args[i], &id)) < 0) {
872 log_error("Failed to parse job id: %s", strerror(-r));
876 assert_cc(sizeof(uint32_t) == sizeof(id));
877 if (!dbus_message_append_args(m,
878 DBUS_TYPE_UINT32, &id,
879 DBUS_TYPE_INVALID)) {
880 log_error("Could not append arguments to message.");
885 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
886 log_error("Failed to issue method call: %s", bus_error_message(&error));
891 if (!dbus_message_get_args(reply, &error,
892 DBUS_TYPE_OBJECT_PATH, &path,
893 DBUS_TYPE_INVALID)) {
894 log_error("Failed to parse reply: %s", bus_error_message(&error));
899 dbus_message_unref(m);
900 if (!(m = dbus_message_new_method_call(
901 "org.freedesktop.systemd1",
903 "org.freedesktop.systemd1.Job",
905 log_error("Could not allocate message.");
910 dbus_message_unref(reply);
911 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
912 log_error("Failed to issue method call: %s", bus_error_message(&error));
917 dbus_message_unref(m);
918 dbus_message_unref(reply);
926 dbus_message_unref(m);
929 dbus_message_unref(reply);
931 dbus_error_free(&error);
936 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
937 DBusMessage *m = NULL, *reply = NULL;
938 dbus_bool_t b = FALSE;
939 DBusMessageIter iter, sub;
941 *interface = "org.freedesktop.systemd1.Unit",
942 *property = "NeedDaemonReload",
945 /* We ignore all errors here, since this is used to show a warning only */
947 if (!(m = dbus_message_new_method_call(
948 "org.freedesktop.systemd1",
949 "/org/freedesktop/systemd1",
950 "org.freedesktop.systemd1.Manager",
954 if (!dbus_message_append_args(m,
955 DBUS_TYPE_STRING, &unit,
959 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
962 if (!dbus_message_get_args(reply, NULL,
963 DBUS_TYPE_OBJECT_PATH, &path,
967 dbus_message_unref(m);
968 if (!(m = dbus_message_new_method_call(
969 "org.freedesktop.systemd1",
971 "org.freedesktop.DBus.Properties",
975 if (!dbus_message_append_args(m,
976 DBUS_TYPE_STRING, &interface,
977 DBUS_TYPE_STRING, &property,
978 DBUS_TYPE_INVALID)) {
982 dbus_message_unref(reply);
983 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
986 if (!dbus_message_iter_init(reply, &iter) ||
987 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
990 dbus_message_iter_recurse(&iter, &sub);
992 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
995 dbus_message_iter_get_basic(&sub, &b);
999 dbus_message_unref(m);
1002 dbus_message_unref(reply);
1007 typedef struct WaitData {
1012 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1020 dbus_error_init(&error);
1022 log_debug("Got D-Bus request: %s.%s() on %s",
1023 dbus_message_get_interface(message),
1024 dbus_message_get_member(message),
1025 dbus_message_get_path(message));
1027 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1028 log_error("Warning! D-Bus connection terminated.");
1029 dbus_connection_close(connection);
1031 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1034 dbus_bool_t success = true;
1036 if (!dbus_message_get_args(message, &error,
1037 DBUS_TYPE_UINT32, &id,
1038 DBUS_TYPE_OBJECT_PATH, &path,
1039 DBUS_TYPE_BOOLEAN, &success,
1041 log_error("Failed to parse message: %s", bus_error_message(&error));
1045 if ((p = set_remove(d->set, (char*) path)))
1053 dbus_error_free(&error);
1054 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1057 static int enable_wait_for_jobs(DBusConnection *bus) {
1065 dbus_error_init(&error);
1066 dbus_bus_add_match(bus,
1068 "sender='org.freedesktop.systemd1',"
1069 "interface='org.freedesktop.systemd1.Manager',"
1070 "member='JobRemoved',"
1071 "path='/org/freedesktop/systemd1'",
1074 if (dbus_error_is_set(&error)) {
1075 log_error("Failed to add match: %s", bus_error_message(&error));
1076 dbus_error_free(&error);
1080 /* This is slightly dirty, since we don't undo the match registrations. */
1084 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1095 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1096 log_error("Failed to add filter.");
1101 while (!set_isempty(s) &&
1102 dbus_connection_read_write_dispatch(bus, -1))
1105 if (!arg_quiet && d.failed)
1106 log_error("Job failed, see system logs for details.");
1108 r = d.failed ? -EIO : 0;
1111 /* This is slightly dirty, since we don't undo the filter registration. */
1116 static int start_unit_one(
1117 DBusConnection *bus,
1124 DBusMessage *m = NULL, *reply = NULL;
1133 assert(arg_no_block || s);
1135 if (!(m = dbus_message_new_method_call(
1136 "org.freedesktop.systemd1",
1137 "/org/freedesktop/systemd1",
1138 "org.freedesktop.systemd1.Manager",
1140 log_error("Could not allocate message.");
1145 if (!dbus_message_append_args(m,
1146 DBUS_TYPE_STRING, &name,
1147 DBUS_TYPE_STRING, &mode,
1148 DBUS_TYPE_INVALID)) {
1149 log_error("Could not append arguments to message.");
1154 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1156 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1157 /* There's always a fallback possible for
1158 * legacy actions. */
1163 log_error("Failed to issue method call: %s", bus_error_message(error));
1168 if (!dbus_message_get_args(reply, error,
1169 DBUS_TYPE_OBJECT_PATH, &path,
1170 DBUS_TYPE_INVALID)) {
1171 log_error("Failed to parse reply: %s", bus_error_message(error));
1176 if (need_daemon_reload(bus, name))
1177 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1178 arg_session ? "--session" : "--system");
1180 if (!arg_no_block) {
1183 if (!(p = strdup(path))) {
1184 log_error("Failed to duplicate path.");
1189 if ((r = set_put(s, p)) < 0) {
1191 log_error("Failed to add path to set.");
1200 dbus_message_unref(m);
1203 dbus_message_unref(reply);
1208 static enum action verb_to_action(const char *verb) {
1209 if (streq(verb, "halt"))
1211 else if (streq(verb, "poweroff"))
1212 return ACTION_POWEROFF;
1213 else if (streq(verb, "reboot"))
1214 return ACTION_REBOOT;
1215 else if (streq(verb, "rescue"))
1216 return ACTION_RESCUE;
1217 else if (streq(verb, "emergency"))
1218 return ACTION_EMERGENCY;
1219 else if (streq(verb, "default"))
1220 return ACTION_DEFAULT;
1222 return ACTION_INVALID;
1225 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1227 static const char * const table[_ACTION_MAX] = {
1228 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1229 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1230 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1231 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1232 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1233 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1234 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1235 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1236 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1237 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET
1242 const char *method, *mode, *one_name;
1246 dbus_error_init(&error);
1250 if (arg_action == ACTION_SYSTEMCTL) {
1252 streq(args[0], "stop") ? "StopUnit" :
1253 streq(args[0], "reload") ? "ReloadUnit" :
1254 streq(args[0], "restart") ? "RestartUnit" :
1255 streq(args[0], "try-restart") ? "TryRestartUnit" :
1256 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1257 streq(args[0], "reload-or-try-restart") ||
1258 streq(args[0], "force-reload") ||
1259 streq(args[0], "condrestart") ? "ReloadOrTryRestartUnit" :
1263 (streq(args[0], "isolate") ||
1264 streq(args[0], "rescue") ||
1265 streq(args[0], "emergency")) ? "isolate" :
1269 one_name = table[verb_to_action(args[0])];
1272 assert(arg_action < ELEMENTSOF(table));
1273 assert(table[arg_action]);
1275 method = "StartUnit";
1277 mode = (arg_action == ACTION_EMERGENCY ||
1278 arg_action == ACTION_RESCUE ||
1279 arg_action == ACTION_RUNLEVEL2 ||
1280 arg_action == ACTION_RUNLEVEL3 ||
1281 arg_action == ACTION_RUNLEVEL4 ||
1282 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1284 one_name = table[arg_action];
1287 if (!arg_no_block) {
1288 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1289 log_error("Could not watch jobs: %s", strerror(-ret));
1293 if (!(s = set_new(string_hash_func, string_compare_func))) {
1294 log_error("Failed to allocate set.");
1301 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1304 for (i = 1; i < n; i++)
1305 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1306 ret = translate_bus_error_to_exit_status(r, &error);
1307 dbus_error_free(&error);
1312 if ((r = wait_for_jobs(bus, s)) < 0) {
1321 dbus_error_free(&error);
1326 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1332 r = start_unit(bus, args, n);
1335 warn_wall(verb_to_action(args[0]));
1340 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1341 DBusMessage *m = NULL, *reply = NULL;
1343 *interface = "org.freedesktop.systemd1.Unit",
1344 *property = "ActiveState";
1345 int r = 3; /* According to LSB: "program is not running" */
1352 dbus_error_init(&error);
1354 for (i = 1; i < n; i++) {
1355 const char *path = NULL;
1357 DBusMessageIter iter, sub;
1359 if (!(m = dbus_message_new_method_call(
1360 "org.freedesktop.systemd1",
1361 "/org/freedesktop/systemd1",
1362 "org.freedesktop.systemd1.Manager",
1364 log_error("Could not allocate message.");
1369 if (!dbus_message_append_args(m,
1370 DBUS_TYPE_STRING, &args[i],
1371 DBUS_TYPE_INVALID)) {
1372 log_error("Could not append arguments to message.");
1377 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1379 /* Hmm, cannot figure out anything about this unit... */
1383 dbus_error_free(&error);
1387 if (!dbus_message_get_args(reply, &error,
1388 DBUS_TYPE_OBJECT_PATH, &path,
1389 DBUS_TYPE_INVALID)) {
1390 log_error("Failed to parse reply: %s", bus_error_message(&error));
1395 dbus_message_unref(m);
1396 if (!(m = dbus_message_new_method_call(
1397 "org.freedesktop.systemd1",
1399 "org.freedesktop.DBus.Properties",
1401 log_error("Could not allocate message.");
1406 if (!dbus_message_append_args(m,
1407 DBUS_TYPE_STRING, &interface,
1408 DBUS_TYPE_STRING, &property,
1409 DBUS_TYPE_INVALID)) {
1410 log_error("Could not append arguments to message.");
1415 dbus_message_unref(reply);
1416 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1417 log_error("Failed to issue method call: %s", bus_error_message(&error));
1422 if (!dbus_message_iter_init(reply, &iter) ||
1423 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1424 log_error("Failed to parse reply.");
1429 dbus_message_iter_recurse(&iter, &sub);
1431 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1432 log_error("Failed to parse reply.");
1437 dbus_message_iter_get_basic(&sub, &state);
1442 if (streq(state, "active") || streq(state, "reloading"))
1445 dbus_message_unref(m);
1446 dbus_message_unref(reply);
1452 dbus_message_unref(m);
1455 dbus_message_unref(reply);
1457 dbus_error_free(&error);
1462 typedef struct ExecStatusInfo {
1468 usec_t start_timestamp;
1469 usec_t exit_timestamp;
1474 LIST_FIELDS(struct ExecStatusInfo, exec);
1477 static void exec_status_info_free(ExecStatusInfo *i) {
1485 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1486 uint64_t start_timestamp, exit_timestamp;
1487 DBusMessageIter sub2, sub3;
1491 int32_t code, status;
1497 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1500 dbus_message_iter_recurse(sub, &sub2);
1502 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1505 if (!(i->path = strdup(path)))
1508 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1509 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1513 dbus_message_iter_recurse(&sub2, &sub3);
1514 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1515 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1516 dbus_message_iter_next(&sub3);
1521 if (!(i->argv = new0(char*, n+1)))
1525 dbus_message_iter_recurse(&sub2, &sub3);
1526 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1529 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1530 dbus_message_iter_get_basic(&sub3, &s);
1531 dbus_message_iter_next(&sub3);
1533 if (!(i->argv[n++] = strdup(s)))
1537 if (!dbus_message_iter_next(&sub2) ||
1538 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1539 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1540 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1541 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1542 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1543 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1547 i->start_timestamp = (usec_t) start_timestamp;
1548 i->exit_timestamp = (usec_t) exit_timestamp;
1549 i->pid = (pid_t) pid;
1556 typedef struct UnitStatusInfo {
1558 const char *load_state;
1559 const char *active_state;
1560 const char *sub_state;
1562 const char *description;
1565 const char *default_control_group;
1567 usec_t inactive_exit_timestamp;
1568 usec_t active_enter_timestamp;
1569 usec_t active_exit_timestamp;
1570 usec_t inactive_enter_timestamp;
1572 bool need_daemon_reload;
1577 const char *status_text;
1581 usec_t start_timestamp;
1582 usec_t exit_timestamp;
1584 int exit_code, exit_status;
1587 unsigned n_accepted;
1588 unsigned n_connections;
1592 const char *sysfs_path;
1594 /* Mount, Automount */
1600 LIST_HEAD(ExecStatusInfo, exec);
1603 static void print_status_info(UnitStatusInfo *i) {
1605 const char *on, *off, *ss;
1607 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1608 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1612 /* This shows pretty information about a unit. See
1613 * print_property() for a low-level property printer */
1615 printf("%s", strna(i->id));
1617 if (i->description && !streq_ptr(i->id, i->description))
1618 printf(" - %s", i->description);
1622 if (streq_ptr(i->load_state, "failed")) {
1623 on = ansi_highlight(true);
1624 off = ansi_highlight(false);
1629 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1631 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1633 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1635 if (streq_ptr(i->active_state, "failed")) {
1636 on = ansi_highlight(true);
1637 off = ansi_highlight(false);
1638 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1639 on = ansi_highlight_green(true);
1640 off = ansi_highlight_green(false);
1645 printf("\t Active: %s%s (%s)%s",
1647 strna(i->active_state),
1651 printf("\t Active: %s%s%s",
1653 strna(i->active_state),
1656 timestamp = (streq_ptr(i->active_state, "active") ||
1657 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1658 (streq_ptr(i->active_state, "inactive") ||
1659 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1660 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1661 i->active_exit_timestamp;
1663 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1664 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1667 printf(" since [%s; %s]\n", s2, s1);
1669 printf(" since [%s]\n", s2);
1674 printf("\t Device: %s\n", i->sysfs_path);
1676 printf("\t Where: %s\n", i->where);
1678 printf("\t What: %s\n", i->what);
1681 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1683 LIST_FOREACH(exec, p, i->exec) {
1686 /* Only show exited processes here */
1690 t = strv_join(p->argv, " ");
1691 printf("\t Process: %u (%s, code=%s, ", p->pid, strna(t), sigchld_code_to_string(p->code));
1694 if (p->code == CLD_EXITED) {
1697 printf("status=%i", p->status);
1699 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1703 printf("signal=%s", signal_to_string(p->status));
1706 if (i->main_pid == p->pid &&
1707 i->start_timestamp == p->start_timestamp &&
1708 i->exit_timestamp == p->start_timestamp)
1709 /* Let's not show this twice */
1712 if (p->pid == i->control_pid)
1716 if (i->main_pid > 0 || i->control_pid > 0) {
1719 if (i->main_pid > 0) {
1720 printf("Main PID: %u", (unsigned) i->main_pid);
1724 get_process_name(i->main_pid, &t);
1729 } else if (i->exit_code > 0) {
1730 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1732 if (i->exit_code == CLD_EXITED) {
1735 printf("status=%i", i->exit_status);
1737 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1741 printf("signal=%s", signal_to_string(i->exit_status));
1746 if (i->main_pid > 0 && i->control_pid > 0)
1749 if (i->control_pid > 0) {
1752 printf(" Control: %u", (unsigned) i->control_pid);
1754 get_process_name(i->control_pid, &t);
1765 printf("\t Status: \"%s\"\n", i->status_text);
1767 if (i->default_control_group) {
1770 printf("\t CGroup: %s\n", i->default_control_group);
1772 if ((c = columns()) > 18)
1777 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
1780 if (i->need_daemon_reload)
1781 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1782 ansi_highlight(true),
1783 ansi_highlight(false),
1784 arg_session ? "--session" : "--system");
1787 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1789 switch (dbus_message_iter_get_arg_type(iter)) {
1791 case DBUS_TYPE_STRING: {
1794 dbus_message_iter_get_basic(iter, &s);
1797 if (streq(name, "Id"))
1799 else if (streq(name, "LoadState"))
1801 else if (streq(name, "ActiveState"))
1802 i->active_state = s;
1803 else if (streq(name, "SubState"))
1805 else if (streq(name, "Description"))
1807 else if (streq(name, "FragmentPath"))
1809 else if (streq(name, "SysVPath")) {
1812 } else if (streq(name, "DefaultControlGroup"))
1813 i->default_control_group = s;
1814 else if (streq(name, "StatusText"))
1816 else if (streq(name, "SysFSPath"))
1818 else if (streq(name, "Where"))
1820 else if (streq(name, "What"))
1827 case DBUS_TYPE_BOOLEAN: {
1830 dbus_message_iter_get_basic(iter, &b);
1832 if (streq(name, "Accept"))
1834 else if (streq(name, "NeedDaemonReload"))
1835 i->need_daemon_reload = b;
1840 case DBUS_TYPE_UINT32: {
1843 dbus_message_iter_get_basic(iter, &u);
1845 if (streq(name, "MainPID")) {
1847 i->main_pid = (pid_t) u;
1850 } else if (streq(name, "ControlPID"))
1851 i->control_pid = (pid_t) u;
1852 else if (streq(name, "ExecMainPID")) {
1854 i->main_pid = (pid_t) u;
1855 } else if (streq(name, "NAccepted"))
1857 else if (streq(name, "NConnections"))
1858 i->n_connections = u;
1863 case DBUS_TYPE_INT32: {
1866 dbus_message_iter_get_basic(iter, &j);
1868 if (streq(name, "ExecMainCode"))
1869 i->exit_code = (int) j;
1870 else if (streq(name, "ExecMainStatus"))
1871 i->exit_status = (int) j;
1876 case DBUS_TYPE_UINT64: {
1879 dbus_message_iter_get_basic(iter, &u);
1881 if (streq(name, "ExecMainStartTimestamp"))
1882 i->start_timestamp = (usec_t) u;
1883 else if (streq(name, "ExecMainExitTimestamp"))
1884 i->exit_timestamp = (usec_t) u;
1885 else if (streq(name, "ActiveEnterTimestamp"))
1886 i->active_enter_timestamp = (usec_t) u;
1887 else if (streq(name, "InactiveEnterTimestamp"))
1888 i->inactive_enter_timestamp = (usec_t) u;
1889 else if (streq(name, "InactiveExitTimestamp"))
1890 i->inactive_exit_timestamp = (usec_t) u;
1891 else if (streq(name, "ActiveExitTimestamp"))
1892 i->active_exit_timestamp = (usec_t) u;
1897 case DBUS_TYPE_ARRAY: {
1899 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
1900 startswith(name, "Exec")) {
1901 DBusMessageIter sub;
1903 dbus_message_iter_recurse(iter, &sub);
1904 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1905 ExecStatusInfo *info;
1908 if (!(info = new0(ExecStatusInfo, 1)))
1911 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
1916 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
1918 dbus_message_iter_next(&sub);
1929 static int print_property(const char *name, DBusMessageIter *iter) {
1933 /* This is a low-level property printer, see
1934 * print_status_info() for the nicer output */
1936 if (arg_property && !strv_find(arg_property, name))
1939 switch (dbus_message_iter_get_arg_type(iter)) {
1941 case DBUS_TYPE_STRING: {
1943 dbus_message_iter_get_basic(iter, &s);
1945 if (arg_all || s[0])
1946 printf("%s=%s\n", name, s);
1951 case DBUS_TYPE_BOOLEAN: {
1953 dbus_message_iter_get_basic(iter, &b);
1954 printf("%s=%s\n", name, yes_no(b));
1959 case DBUS_TYPE_UINT64: {
1961 dbus_message_iter_get_basic(iter, &u);
1963 /* Yes, heuristics! But we can change this check
1964 * should it turn out to not be sufficient */
1966 if (strstr(name, "Timestamp")) {
1967 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
1969 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
1970 printf("%s=%s\n", name, strempty(t));
1971 } else if (strstr(name, "USec")) {
1972 char timespan[FORMAT_TIMESPAN_MAX];
1974 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
1976 printf("%s=%llu\n", name, (unsigned long long) u);
1981 case DBUS_TYPE_UINT32: {
1983 dbus_message_iter_get_basic(iter, &u);
1985 if (strstr(name, "UMask") || strstr(name, "Mode"))
1986 printf("%s=%04o\n", name, u);
1988 printf("%s=%u\n", name, (unsigned) u);
1993 case DBUS_TYPE_INT32: {
1995 dbus_message_iter_get_basic(iter, &i);
1997 printf("%s=%i\n", name, (int) i);
2001 case DBUS_TYPE_STRUCT: {
2002 DBusMessageIter sub;
2003 dbus_message_iter_recurse(iter, &sub);
2005 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2008 dbus_message_iter_get_basic(&sub, &u);
2011 printf("%s=%u\n", name, (unsigned) u);
2013 printf("%s=\n", name);
2016 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2019 dbus_message_iter_get_basic(&sub, &s);
2021 if (arg_all || s[0])
2022 printf("%s=%s\n", name, s);
2030 case DBUS_TYPE_ARRAY:
2032 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2033 DBusMessageIter sub;
2036 dbus_message_iter_recurse(iter, &sub);
2038 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2039 printf("%s=", name);
2041 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2044 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2045 dbus_message_iter_get_basic(&sub, &s);
2046 printf("%s%s", space ? " " : "", s);
2049 dbus_message_iter_next(&sub);
2057 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2058 DBusMessageIter sub;
2060 dbus_message_iter_recurse(iter, &sub);
2062 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2063 printf("%s=", name);
2065 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2068 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2069 dbus_message_iter_get_basic(&sub, &u);
2072 dbus_message_iter_next(&sub);
2080 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2081 DBusMessageIter sub, sub2;
2083 dbus_message_iter_recurse(iter, &sub);
2084 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2085 const char *type, *path;
2087 dbus_message_iter_recurse(&sub, &sub2);
2089 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2090 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2091 printf("%s=%s\n", type, path);
2093 dbus_message_iter_next(&sub);
2098 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2099 DBusMessageIter sub, sub2;
2101 dbus_message_iter_recurse(iter, &sub);
2102 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2104 uint64_t value, next_elapse;
2106 dbus_message_iter_recurse(&sub, &sub2);
2108 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2109 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2110 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2111 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2113 printf("%s={ value=%s ; next_elapse=%s }\n",
2115 format_timespan(timespan1, sizeof(timespan1), value),
2116 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2119 dbus_message_iter_next(&sub);
2124 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2125 DBusMessageIter sub;
2127 dbus_message_iter_recurse(iter, &sub);
2128 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2129 ExecStatusInfo info;
2132 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2133 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2136 t = strv_join(info.argv, " ");
2138 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2142 yes_no(info.ignore),
2143 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2144 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2145 (unsigned) info. pid,
2146 sigchld_code_to_string(info.code),
2148 info.code == CLD_EXITED ? "" : "/",
2149 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2155 strv_free(info.argv);
2157 dbus_message_iter_next(&sub);
2167 printf("%s=[unprintable]\n", name);
2172 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2173 DBusMessage *m = NULL, *reply = NULL;
2174 const char *interface = "";
2177 DBusMessageIter iter, sub, sub2, sub3;
2178 UnitStatusInfo info;
2186 dbus_error_init(&error);
2188 if (!(m = dbus_message_new_method_call(
2189 "org.freedesktop.systemd1",
2191 "org.freedesktop.DBus.Properties",
2193 log_error("Could not allocate message.");
2198 if (!dbus_message_append_args(m,
2199 DBUS_TYPE_STRING, &interface,
2200 DBUS_TYPE_INVALID)) {
2201 log_error("Could not append arguments to message.");
2206 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2207 log_error("Failed to issue method call: %s", bus_error_message(&error));
2212 if (!dbus_message_iter_init(reply, &iter) ||
2213 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2214 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2215 log_error("Failed to parse reply.");
2220 dbus_message_iter_recurse(&iter, &sub);
2227 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2230 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2231 log_error("Failed to parse reply.");
2236 dbus_message_iter_recurse(&sub, &sub2);
2238 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2239 log_error("Failed to parse reply.");
2244 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2245 log_error("Failed to parse reply.");
2250 dbus_message_iter_recurse(&sub2, &sub3);
2252 if (show_properties)
2253 r = print_property(name, &sub3);
2255 r = status_property(name, &sub3, &info);
2258 log_error("Failed to parse reply.");
2263 dbus_message_iter_next(&sub);
2268 if (!show_properties)
2269 print_status_info(&info);
2271 if (!streq_ptr(info.active_state, "active") &&
2272 !streq_ptr(info.active_state, "reloading"))
2273 /* According to LSB: "program not running" */
2276 while ((p = info.exec)) {
2277 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2278 exec_status_info_free(p);
2283 dbus_message_unref(m);
2286 dbus_message_unref(reply);
2288 dbus_error_free(&error);
2293 static int show(DBusConnection *bus, char **args, unsigned n) {
2294 DBusMessage *m = NULL, *reply = NULL;
2298 bool show_properties, new_line = false;
2303 dbus_error_init(&error);
2305 show_properties = !streq(args[0], "status");
2307 if (show_properties && n <= 1) {
2308 /* If not argument is specified inspect the manager
2311 ret = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2315 for (i = 1; i < n; i++) {
2316 const char *path = NULL;
2319 if (safe_atou32(args[i], &id) < 0) {
2321 /* Interpret as unit name */
2323 if (!(m = dbus_message_new_method_call(
2324 "org.freedesktop.systemd1",
2325 "/org/freedesktop/systemd1",
2326 "org.freedesktop.systemd1.Manager",
2328 log_error("Could not allocate message.");
2333 if (!dbus_message_append_args(m,
2334 DBUS_TYPE_STRING, &args[i],
2335 DBUS_TYPE_INVALID)) {
2336 log_error("Could not append arguments to message.");
2341 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2343 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2344 log_error("Failed to issue method call: %s", bus_error_message(&error));
2349 dbus_error_free(&error);
2351 dbus_message_unref(m);
2352 if (!(m = dbus_message_new_method_call(
2353 "org.freedesktop.systemd1",
2354 "/org/freedesktop/systemd1",
2355 "org.freedesktop.systemd1.Manager",
2357 log_error("Could not allocate message.");
2362 if (!dbus_message_append_args(m,
2363 DBUS_TYPE_STRING, &args[i],
2364 DBUS_TYPE_INVALID)) {
2365 log_error("Could not append arguments to message.");
2370 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2371 log_error("Failed to issue method call: %s", bus_error_message(&error));
2373 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2374 ret = 4; /* According to LSB: "program or service status is unknown" */
2381 } else if (show_properties) {
2383 /* Interpret as job id */
2385 if (!(m = dbus_message_new_method_call(
2386 "org.freedesktop.systemd1",
2387 "/org/freedesktop/systemd1",
2388 "org.freedesktop.systemd1.Manager",
2390 log_error("Could not allocate message.");
2395 if (!dbus_message_append_args(m,
2396 DBUS_TYPE_UINT32, &id,
2397 DBUS_TYPE_INVALID)) {
2398 log_error("Could not append arguments to message.");
2403 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2404 log_error("Failed to issue method call: %s", bus_error_message(&error));
2410 /* Interpret as PID */
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 if (!dbus_message_get_args(reply, &error,
2438 DBUS_TYPE_OBJECT_PATH, &path,
2439 DBUS_TYPE_INVALID)) {
2440 log_error("Failed to parse reply: %s", bus_error_message(&error));
2445 if ((r = show_one(bus, path, show_properties, &new_line)) != 0)
2448 dbus_message_unref(m);
2449 dbus_message_unref(reply);
2455 dbus_message_unref(m);
2458 dbus_message_unref(reply);
2460 dbus_error_free(&error);
2465 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2467 DBusMessage *m = NULL, *reply = NULL;
2472 dbus_error_init(&error);
2474 log_debug("Got D-Bus request: %s.%s() on %s",
2475 dbus_message_get_interface(message),
2476 dbus_message_get_member(message),
2477 dbus_message_get_path(message));
2479 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2480 log_error("Warning! D-Bus connection terminated.");
2481 dbus_connection_close(connection);
2483 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2484 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2485 const char *id, *path;
2487 if (!dbus_message_get_args(message, &error,
2488 DBUS_TYPE_STRING, &id,
2489 DBUS_TYPE_OBJECT_PATH, &path,
2491 log_error("Failed to parse message: %s", bus_error_message(&error));
2492 else if (streq(dbus_message_get_member(message), "UnitNew"))
2493 printf("Unit %s added.\n", id);
2495 printf("Unit %s removed.\n", id);
2497 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2498 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2502 if (!dbus_message_get_args(message, &error,
2503 DBUS_TYPE_UINT32, &id,
2504 DBUS_TYPE_OBJECT_PATH, &path,
2506 log_error("Failed to parse message: %s", bus_error_message(&error));
2507 else if (streq(dbus_message_get_member(message), "JobNew"))
2508 printf("Job %u added.\n", id);
2510 printf("Job %u removed.\n", id);
2513 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2515 const char *path, *interface, *property = "Id";
2516 DBusMessageIter iter, sub;
2518 path = dbus_message_get_path(message);
2520 if (!dbus_message_get_args(message, &error,
2521 DBUS_TYPE_STRING, &interface,
2522 DBUS_TYPE_INVALID)) {
2523 log_error("Failed to parse message: %s", bus_error_message(&error));
2527 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2528 !streq(interface, "org.freedesktop.systemd1.Unit"))
2531 if (!(m = dbus_message_new_method_call(
2532 "org.freedesktop.systemd1",
2534 "org.freedesktop.DBus.Properties",
2536 log_error("Could not allocate message.");
2540 if (!dbus_message_append_args(m,
2541 DBUS_TYPE_STRING, &interface,
2542 DBUS_TYPE_STRING, &property,
2543 DBUS_TYPE_INVALID)) {
2544 log_error("Could not append arguments to message.");
2548 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2549 log_error("Failed to issue method call: %s", bus_error_message(&error));
2553 if (!dbus_message_iter_init(reply, &iter) ||
2554 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2555 log_error("Failed to parse reply.");
2559 dbus_message_iter_recurse(&iter, &sub);
2561 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2564 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2565 log_error("Failed to parse reply.");
2569 dbus_message_iter_get_basic(&sub, &id);
2570 printf("Unit %s changed.\n", id);
2574 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2575 log_error("Failed to parse reply.");
2579 dbus_message_iter_get_basic(&sub, &id);
2580 printf("Job %u changed.\n", id);
2586 dbus_message_unref(m);
2589 dbus_message_unref(reply);
2591 dbus_error_free(&error);
2592 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2596 dbus_message_unref(m);
2599 dbus_message_unref(reply);
2601 dbus_error_free(&error);
2602 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2605 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2606 DBusMessage *m = NULL, *reply = NULL;
2610 dbus_error_init(&error);
2613 dbus_bus_add_match(bus,
2615 "sender='org.freedesktop.systemd1',"
2616 "interface='org.freedesktop.systemd1.Manager',"
2617 "path='/org/freedesktop/systemd1'",
2620 if (dbus_error_is_set(&error)) {
2621 log_error("Failed to add match: %s", bus_error_message(&error));
2626 dbus_bus_add_match(bus,
2628 "sender='org.freedesktop.systemd1',"
2629 "interface='org.freedesktop.DBus.Properties',"
2630 "member='PropertiesChanged'",
2633 if (dbus_error_is_set(&error)) {
2634 log_error("Failed to add match: %s", bus_error_message(&error));
2640 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2641 log_error("Failed to add filter.");
2646 if (!(m = dbus_message_new_method_call(
2647 "org.freedesktop.systemd1",
2648 "/org/freedesktop/systemd1",
2649 "org.freedesktop.systemd1.Manager",
2651 log_error("Could not allocate message.");
2656 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2657 log_error("Failed to issue method call: %s", bus_error_message(&error));
2662 while (dbus_connection_read_write_dispatch(bus, -1))
2669 /* This is slightly dirty, since we don't undo the filter or the matches. */
2672 dbus_message_unref(m);
2675 dbus_message_unref(reply);
2677 dbus_error_free(&error);
2682 static int dump(DBusConnection *bus, char **args, unsigned n) {
2683 DBusMessage *m = NULL, *reply = NULL;
2688 dbus_error_init(&error);
2690 if (!(m = dbus_message_new_method_call(
2691 "org.freedesktop.systemd1",
2692 "/org/freedesktop/systemd1",
2693 "org.freedesktop.systemd1.Manager",
2695 log_error("Could not allocate message.");
2699 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2700 log_error("Failed to issue method call: %s", bus_error_message(&error));
2705 if (!dbus_message_get_args(reply, &error,
2706 DBUS_TYPE_STRING, &text,
2707 DBUS_TYPE_INVALID)) {
2708 log_error("Failed to parse reply: %s", bus_error_message(&error));
2713 fputs(text, stdout);
2719 dbus_message_unref(m);
2722 dbus_message_unref(reply);
2724 dbus_error_free(&error);
2729 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2730 DBusMessage *m = NULL, *reply = NULL;
2733 const char *name = "", *path, *id;
2734 dbus_bool_t cleanup = FALSE;
2735 DBusMessageIter iter, sub;
2737 *interface = "org.freedesktop.systemd1.Unit",
2740 dbus_error_init(&error);
2742 if (!(m = dbus_message_new_method_call(
2743 "org.freedesktop.systemd1",
2744 "/org/freedesktop/systemd1",
2745 "org.freedesktop.systemd1.Manager",
2746 "CreateSnapshot"))) {
2747 log_error("Could not allocate message.");
2754 if (!dbus_message_append_args(m,
2755 DBUS_TYPE_STRING, &name,
2756 DBUS_TYPE_BOOLEAN, &cleanup,
2757 DBUS_TYPE_INVALID)) {
2758 log_error("Could not append arguments to message.");
2763 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2764 log_error("Failed to issue method call: %s", bus_error_message(&error));
2769 if (!dbus_message_get_args(reply, &error,
2770 DBUS_TYPE_OBJECT_PATH, &path,
2771 DBUS_TYPE_INVALID)) {
2772 log_error("Failed to parse reply: %s", bus_error_message(&error));
2777 dbus_message_unref(m);
2778 if (!(m = dbus_message_new_method_call(
2779 "org.freedesktop.systemd1",
2781 "org.freedesktop.DBus.Properties",
2783 log_error("Could not allocate message.");
2787 if (!dbus_message_append_args(m,
2788 DBUS_TYPE_STRING, &interface,
2789 DBUS_TYPE_STRING, &property,
2790 DBUS_TYPE_INVALID)) {
2791 log_error("Could not append arguments to message.");
2796 dbus_message_unref(reply);
2797 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2798 log_error("Failed to issue method call: %s", bus_error_message(&error));
2803 if (!dbus_message_iter_init(reply, &iter) ||
2804 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2805 log_error("Failed to parse reply.");
2810 dbus_message_iter_recurse(&iter, &sub);
2812 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2813 log_error("Failed to parse reply.");
2818 dbus_message_iter_get_basic(&sub, &id);
2826 dbus_message_unref(m);
2829 dbus_message_unref(reply);
2831 dbus_error_free(&error);
2836 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2837 DBusMessage *m = NULL, *reply = NULL;
2845 dbus_error_init(&error);
2847 for (i = 1; i < n; i++) {
2848 const char *path = NULL;
2850 if (!(m = dbus_message_new_method_call(
2851 "org.freedesktop.systemd1",
2852 "/org/freedesktop/systemd1",
2853 "org.freedesktop.systemd1.Manager",
2855 log_error("Could not allocate message.");
2860 if (!dbus_message_append_args(m,
2861 DBUS_TYPE_STRING, &args[i],
2862 DBUS_TYPE_INVALID)) {
2863 log_error("Could not append arguments to message.");
2868 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2869 log_error("Failed to issue method call: %s", bus_error_message(&error));
2874 if (!dbus_message_get_args(reply, &error,
2875 DBUS_TYPE_OBJECT_PATH, &path,
2876 DBUS_TYPE_INVALID)) {
2877 log_error("Failed to parse reply: %s", bus_error_message(&error));
2882 dbus_message_unref(m);
2883 if (!(m = dbus_message_new_method_call(
2884 "org.freedesktop.systemd1",
2886 "org.freedesktop.systemd1.Snapshot",
2888 log_error("Could not allocate message.");
2893 dbus_message_unref(reply);
2894 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2895 log_error("Failed to issue method call: %s", bus_error_message(&error));
2900 dbus_message_unref(m);
2901 dbus_message_unref(reply);
2909 dbus_message_unref(m);
2912 dbus_message_unref(reply);
2914 dbus_error_free(&error);
2919 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2920 DBusMessage *m = NULL, *reply = NULL;
2925 dbus_error_init(&error);
2927 if (arg_action == ACTION_RELOAD)
2929 else if (arg_action == ACTION_REEXEC)
2930 method = "Reexecute";
2932 assert(arg_action == ACTION_SYSTEMCTL);
2935 streq(args[0], "clear-jobs") ||
2936 streq(args[0], "cancel") ? "ClearJobs" :
2937 streq(args[0], "daemon-reexec") ? "Reexecute" :
2938 streq(args[0], "reset-failed") ? "ResetFailed" :
2939 streq(args[0], "daemon-exit") ? "Exit" :
2943 if (!(m = dbus_message_new_method_call(
2944 "org.freedesktop.systemd1",
2945 "/org/freedesktop/systemd1",
2946 "org.freedesktop.systemd1.Manager",
2948 log_error("Could not allocate message.");
2952 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2954 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
2955 /* There's always a fallback possible for
2956 * legacy actions. */
2961 log_error("Failed to issue method call: %s", bus_error_message(&error));
2970 dbus_message_unref(m);
2973 dbus_message_unref(reply);
2975 dbus_error_free(&error);
2980 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
2981 DBusMessage *m = NULL, *reply = NULL;
2987 dbus_error_init(&error);
2990 return daemon_reload(bus, args, n);
2992 for (i = 1; i < n; i++) {
2994 if (!(m = dbus_message_new_method_call(
2995 "org.freedesktop.systemd1",
2996 "/org/freedesktop/systemd1",
2997 "org.freedesktop.systemd1.Manager",
2998 "ResetFailedUnit"))) {
2999 log_error("Could not allocate message.");
3004 if (!dbus_message_append_args(m,
3005 DBUS_TYPE_STRING, args + i,
3006 DBUS_TYPE_INVALID)) {
3007 log_error("Could not append arguments to message.");
3012 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3013 log_error("Failed to issue method call: %s", bus_error_message(&error));
3018 dbus_message_unref(m);
3019 dbus_message_unref(reply);
3027 dbus_message_unref(m);
3030 dbus_message_unref(reply);
3032 dbus_error_free(&error);
3037 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3038 DBusMessage *m = NULL, *reply = NULL;
3040 DBusMessageIter iter, sub, sub2;
3043 *interface = "org.freedesktop.systemd1.Manager",
3044 *property = "Environment";
3046 dbus_error_init(&error);
3048 if (!(m = dbus_message_new_method_call(
3049 "org.freedesktop.systemd1",
3050 "/org/freedesktop/systemd1",
3051 "org.freedesktop.DBus.Properties",
3053 log_error("Could not allocate message.");
3057 if (!dbus_message_append_args(m,
3058 DBUS_TYPE_STRING, &interface,
3059 DBUS_TYPE_STRING, &property,
3060 DBUS_TYPE_INVALID)) {
3061 log_error("Could not append arguments to message.");
3066 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3067 log_error("Failed to issue method call: %s", bus_error_message(&error));
3072 if (!dbus_message_iter_init(reply, &iter) ||
3073 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3074 log_error("Failed to parse reply.");
3079 dbus_message_iter_recurse(&iter, &sub);
3081 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3082 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3083 log_error("Failed to parse reply.");
3088 dbus_message_iter_recurse(&sub, &sub2);
3090 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3093 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3094 log_error("Failed to parse reply.");
3099 dbus_message_iter_get_basic(&sub2, &text);
3100 printf("%s\n", text);
3102 dbus_message_iter_next(&sub2);
3109 dbus_message_unref(m);
3112 dbus_message_unref(reply);
3114 dbus_error_free(&error);
3119 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3120 DBusMessage *m = NULL, *reply = NULL;
3124 DBusMessageIter iter, sub;
3127 dbus_error_init(&error);
3129 method = streq(args[0], "set-environment")
3131 : "UnsetEnvironment";
3133 if (!(m = dbus_message_new_method_call(
3134 "org.freedesktop.systemd1",
3135 "/org/freedesktop/systemd1",
3136 "org.freedesktop.systemd1.Manager",
3139 log_error("Could not allocate message.");
3143 dbus_message_iter_init_append(m, &iter);
3145 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3146 log_error("Could not append arguments to message.");
3151 for (i = 1; i < n; i++)
3152 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3153 log_error("Could not append arguments to message.");
3158 if (!dbus_message_iter_close_container(&iter, &sub)) {
3159 log_error("Could not append arguments to message.");
3164 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3165 log_error("Failed to issue method call: %s", bus_error_message(&error));
3174 dbus_message_unref(m);
3177 dbus_message_unref(reply);
3179 dbus_error_free(&error);
3192 static Hashmap *will_install = NULL, *have_installed = NULL;
3193 static Set *remove_symlinks_to = NULL;
3195 static void install_info_free(InstallInfo *i) {
3200 strv_free(i->aliases);
3201 strv_free(i->wanted_by);
3205 static void install_info_hashmap_free(Hashmap *m) {
3208 while ((i = hashmap_steal_first(m)))
3209 install_info_free(i);
3214 static bool unit_name_valid(const char *name) {
3216 /* This is a minimal version of unit_name_valid() from
3222 if (ignore_file(name))
3228 static int install_info_add(const char *name) {
3232 assert(will_install);
3234 if (!unit_name_valid(name))
3237 if (hashmap_get(have_installed, name) ||
3238 hashmap_get(will_install, name))
3241 if (!(i = new0(InstallInfo, 1))) {
3246 if (!(i->name = strdup(name))) {
3251 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3258 install_info_free(i);
3263 static int config_parse_also(
3264 const char *filename,
3266 const char *section,
3280 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3284 if (!(n = strndup(w, l)))
3287 r = install_info_add(n);
3297 static int mark_symlink_for_removal(const char *p) {
3302 assert(path_is_absolute(p));
3304 if (!remove_symlinks_to)
3307 if (!(n = strdup(p)))
3310 path_kill_slashes(n);
3312 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3314 return r == -EEXIST ? 0 : r;
3320 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3329 if (!(d = fdopendir(fd))) {
3330 close_nointr_nofail(fd);
3336 while ((de = readdir(d))) {
3337 bool is_dir = false, is_link = false;
3339 if (ignore_file(de->d_name))
3342 if (de->d_type == DT_LNK)
3344 else if (de->d_type == DT_DIR)
3346 else if (de->d_type == DT_UNKNOWN) {
3349 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3350 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3357 is_link = S_ISLNK(st.st_mode);
3358 is_dir = S_ISDIR(st.st_mode);
3366 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3367 log_error("Failed to open %s/%s: %m", root, de->d_name);
3374 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3375 log_error("Failed to allocate directory string.");
3376 close_nointr_nofail(nfd);
3381 /* This will close nfd, regardless whether it succeeds or not */
3382 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3388 } else if (is_link) {
3392 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3393 log_error("Failed to allocate symlink string.");
3398 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3399 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3407 if ((c = canonicalize_file_name(dest))) {
3408 /* This might fail if the destination
3409 * is already removed */
3415 path_kill_slashes(dest);
3416 if (set_get(remove_symlinks_to, dest)) {
3419 log_info("rm '%s'", p);
3421 if (unlink(p) < 0) {
3422 log_error("Cannot unlink symlink %s: %m", p);
3427 rmdir_parents(p, config_path);
3428 path_kill_slashes(p);
3430 if (!set_get(remove_symlinks_to, p)) {
3432 if ((r = mark_symlink_for_removal(p)) < 0) {
3451 static int remove_marked_symlinks(const char *config_path) {
3455 assert(config_path);
3457 if (set_size(remove_symlinks_to) <= 0)
3460 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3467 if ((cfd = dup(fd)) < 0) {
3472 /* This takes possession of cfd and closes it */
3473 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3479 close_nointr_nofail(fd);
3484 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3491 if (streq(verb, "enable")) {
3494 mkdir_parents(new_path, 0755);
3496 if (symlink(old_path, new_path) >= 0) {
3499 log_info("ln -s '%s' '%s'", old_path, new_path);
3504 if (errno != EEXIST) {
3505 log_error("Cannot link %s to %s: %m", old_path, new_path);
3509 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3511 if (errno == EINVAL) {
3512 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3516 log_error("readlink() failed: %s", strerror(-r));
3520 if (streq(dest, old_path)) {
3526 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3535 log_info("ln -s '%s' '%s'", old_path, new_path);
3537 if (symlink(old_path, new_path) >= 0)
3540 log_error("Cannot link %s to %s: %m", old_path, new_path);
3543 } else if (streq(verb, "disable")) {
3546 if ((r = mark_symlink_for_removal(old_path)) < 0)
3549 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3550 if (errno == ENOENT)
3553 if (errno == EINVAL) {
3554 log_warning("File %s not a symlink, ignoring.", old_path);
3558 log_error("readlink() failed: %s", strerror(-r));
3562 if (!streq(dest, old_path)) {
3563 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3570 if ((r = mark_symlink_for_removal(new_path)) < 0)
3574 log_info("rm '%s'", new_path);
3576 if (unlink(new_path) >= 0)
3579 log_error("Cannot unlink %s: %m", new_path);
3582 } else if (streq(verb, "is-enabled")) {
3585 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3587 if (errno == ENOENT || errno == EINVAL)
3590 log_error("readlink() failed: %s", strerror(-r));
3594 if (streq(dest, old_path)) {
3602 assert_not_reached("Unknown action.");
3605 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3607 char *alias_path = NULL;
3612 assert(config_path);
3614 STRV_FOREACH(s, i->aliases) {
3616 if (!unit_name_valid(*s)) {
3617 log_error("Invalid name %s.", *s);
3623 if (!(alias_path = path_make_absolute(*s, config_path))) {
3624 log_error("Out of memory");
3629 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3632 if (streq(verb, "disable"))
3633 rmdir_parents(alias_path, config_path);
3644 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3646 char *alias_path = NULL;
3651 assert(config_path);
3653 STRV_FOREACH(s, i->wanted_by) {
3654 if (!unit_name_valid(*s)) {
3655 log_error("Invalid name %s.", *s);
3663 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3664 log_error("Out of memory");
3669 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3672 if (streq(verb, "disable"))
3673 rmdir_parents(alias_path, config_path);
3684 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3686 const ConfigItem items[] = {
3687 { "Alias", config_parse_strv, &i->aliases, "Install" },
3688 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3689 { "Also", config_parse_also, NULL, "Install" },
3691 { NULL, NULL, NULL, NULL }
3695 char *filename = NULL;
3702 STRV_FOREACH(p, paths->unit_path) {
3705 if (!(filename = path_make_absolute(i->name, *p))) {
3706 log_error("Out of memory");
3710 /* Ensure that we don't follow symlinks */
3711 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3712 if ((f = fdopen(fd, "re")))
3715 if (errno == ELOOP) {
3716 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3721 if (errno != ENOENT) {
3722 log_error("Failed to open %s: %m", filename);
3732 log_error("Couldn't find %s.", i->name);
3738 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3745 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3748 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3751 if ((r = mark_symlink_for_removal(filename)) < 0)
3754 if ((r = remove_marked_symlinks(config_path)) < 0)
3760 static char *get_config_path(void) {
3762 if (arg_session && arg_global)
3763 return strdup(SESSION_CONFIG_UNIT_PATH);
3768 if (session_config_home(&p) < 0)
3774 return strdup(SYSTEM_CONFIG_UNIT_PATH);
3777 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3781 char *config_path = NULL;
3784 const char *verb = args[0];
3786 dbus_error_init(&error);
3789 if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3790 log_error("Failed to determine lookup paths: %s", strerror(-r));
3794 if (!(config_path = get_config_path())) {
3795 log_error("Failed to determine config path");
3800 will_install = hashmap_new(string_hash_func, string_compare_func);
3801 have_installed = hashmap_new(string_hash_func, string_compare_func);
3803 if (!will_install || !have_installed) {
3804 log_error("Failed to allocate unit sets.");
3809 if (!arg_defaults && streq(verb, "disable"))
3810 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3811 log_error("Failed to allocate symlink sets.");
3816 for (j = 1; j < n; j++)
3817 if ((r = install_info_add(args[j])) < 0)
3820 while ((i = hashmap_first(will_install))) {
3823 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3825 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3833 /* In test mode and found something */
3839 if (streq(verb, "is-enabled"))
3840 r = r > 0 ? 0 : -ENOENT;
3842 /* Don't try to reload anything if the user asked us to not do this */
3844 /* Don't try to reload anything when updating a unit globally */
3846 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3847 (arg_session || sd_booted() > 0) &&
3848 /* Don't try to reload anything if we are running in a chroot environment */
3849 (arg_session || running_in_chroot() <= 0) ) {
3852 if ((q = daemon_reload(bus, args, n)) < 0)
3857 install_info_hashmap_free(will_install);
3858 install_info_hashmap_free(have_installed);
3860 set_free_free(remove_symlinks_to);
3862 lookup_paths_free(&paths);
3869 static int systemctl_help(void) {
3871 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3872 "Send control commands to or query the systemd manager.\n\n"
3873 " -h --help Show this help\n"
3874 " --version Show package version\n"
3875 " -t --type=TYPE List only units of a particular type\n"
3876 " -p --property=NAME Show only properties by this name\n"
3877 " -a --all Show all units/properties, including dead/empty ones\n"
3878 " --full Don't ellipsize unit names on output\n"
3879 " --fail When queueing a new job, fail if conflicting jobs are\n"
3881 " -q --quiet Suppress output\n"
3882 " --no-block Do not wait until operation finished\n"
3883 " --system Connect to system bus\n"
3884 " --session Connect to session bus\n"
3885 " --order When generating graph for dot, show only order\n"
3886 " --require When generating graph for dot, show only requirement\n"
3887 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3888 " --global Enable/disable unit files globally\n"
3889 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3891 " --force When enabling unit files, override existing symlinks\n"
3892 " --defaults When disabling unit files, remove default symlinks only\n\n"
3894 " list-units List units\n"
3895 " start [NAME...] Start (activate) one or more units\n"
3896 " stop [NAME...] Stop (deactivate) one or more units\n"
3897 " reload [NAME...] Reload one or more units\n"
3898 " restart [NAME...] Start or restart one or more units\n"
3899 " try-restart [NAME...] Restart one or more units if active\n"
3900 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3901 " otherwise start or restart\n"
3902 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3903 " otherwise restart if active\n"
3904 " isolate [NAME] Start one unit and stop all others\n"
3905 " is-active [NAME...] Check whether units are active\n"
3906 " status [NAME...|PID...] Show runtime status of one or more units\n"
3907 " show [NAME...|JOB...] Show properties of one or more\n"
3908 " units/jobs or the manager\n"
3909 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
3911 " enable [NAME...] Enable one or more unit files\n"
3912 " disable [NAME...] Disable one or more unit files\n"
3913 " is-enabled [NAME...] Check whether unit files are enabled\n"
3914 " load [NAME...] Load one or more units\n"
3915 " list-jobs List jobs\n"
3916 " cancel [JOB...] Cancel all, one, or more jobs\n"
3917 " monitor Monitor unit/job changes\n"
3918 " dump Dump server status\n"
3919 " dot Dump dependency graph for dot(1)\n"
3920 " snapshot [NAME] Create a snapshot\n"
3921 " delete [NAME...] Remove one or more snapshots\n"
3922 " daemon-reload Reload systemd manager configuration\n"
3923 " daemon-reexec Reexecute systemd manager\n"
3924 " daemon-exit Ask the systemd manager to quit\n"
3925 " show-environment Dump environment\n"
3926 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3927 " unset-environment [NAME...] Unset one or more environment variables\n"
3928 " halt Shut down and halt the system\n"
3929 " poweroff Shut down and power-off the system\n"
3930 " reboot Shut down and reboot the system\n"
3931 " rescue Enter system rescue mode\n"
3932 " emergency Enter system emergency mode\n"
3933 " default Enter system default mode\n",
3934 program_invocation_short_name);
3939 static int halt_help(void) {
3941 printf("%s [OPTIONS...]\n\n"
3942 "%s the system.\n\n"
3943 " --help Show this help\n"
3944 " --halt Halt the machine\n"
3945 " -p --poweroff Switch off the machine\n"
3946 " --reboot Reboot the machine\n"
3947 " -f --force Force immediate halt/power-off/reboot\n"
3948 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3949 " -d --no-wtmp Don't write wtmp record\n"
3950 " -n --no-sync Don't sync before halt/power-off/reboot\n"
3951 " --no-wall Don't send wall message before halt/power-off/reboot\n",
3952 program_invocation_short_name,
3953 arg_action == ACTION_REBOOT ? "Reboot" :
3954 arg_action == ACTION_POWEROFF ? "Power off" :
3960 static int shutdown_help(void) {
3962 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3963 "Shut down the system.\n\n"
3964 " --help Show this help\n"
3965 " -H --halt Halt the machine\n"
3966 " -P --poweroff Power-off the machine\n"
3967 " -r --reboot Reboot the machine\n"
3968 " -h Equivalent to --poweroff, overriden by --halt\n"
3969 " -k Don't halt/power-off/reboot, just send warnings\n"
3970 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3971 " -c Cancel a pending shutdown\n",
3972 program_invocation_short_name);
3977 static int telinit_help(void) {
3979 printf("%s [OPTIONS...] {COMMAND}\n\n"
3980 "Send control commands to the init daemon.\n\n"
3981 " --help Show this help\n"
3982 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
3984 " 0 Power-off the machine\n"
3985 " 6 Reboot the machine\n"
3986 " 2, 3, 4, 5 Start runlevelX.target unit\n"
3987 " 1, s, S Enter rescue mode\n"
3988 " q, Q Reload init daemon configuration\n"
3989 " u, U Reexecute init daemon\n",
3990 program_invocation_short_name);
3995 static int runlevel_help(void) {
3997 printf("%s [OPTIONS...]\n\n"
3998 "Prints the previous and current runlevel of the init system.\n\n"
3999 " --help Show this help\n",
4000 program_invocation_short_name);
4005 static int systemctl_parse_argv(int argc, char *argv[]) {
4023 static const struct option options[] = {
4024 { "help", no_argument, NULL, 'h' },
4025 { "version", no_argument, NULL, ARG_VERSION },
4026 { "type", required_argument, NULL, 't' },
4027 { "property", required_argument, NULL, 'p' },
4028 { "all", no_argument, NULL, 'a' },
4029 { "full", no_argument, NULL, ARG_FULL },
4030 { "fail", no_argument, NULL, ARG_FAIL },
4031 { "session", no_argument, NULL, ARG_SESSION },
4032 { "system", no_argument, NULL, ARG_SYSTEM },
4033 { "global", no_argument, NULL, ARG_GLOBAL },
4034 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4035 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4036 { "quiet", no_argument, NULL, 'q' },
4037 { "order", no_argument, NULL, ARG_ORDER },
4038 { "require", no_argument, NULL, ARG_REQUIRE },
4039 { "force", no_argument, NULL, ARG_FORCE },
4040 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4041 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4042 { NULL, 0, NULL, 0 }
4050 while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
4059 puts(PACKAGE_STRING);
4061 puts(SYSTEMD_FEATURES);
4071 if (!(l = strv_append(arg_property, optarg)))
4074 strv_free(arg_property);
4077 /* If the user asked for a particular
4078 * property, show it to him, even if it is
4097 arg_session = false;
4101 arg_no_block = true;
4109 arg_dot = DOT_ORDER;
4113 arg_dot = DOT_REQUIRE;
4129 arg_no_reload = true;
4138 arg_defaults = true;
4145 log_error("Unknown option code %c", c);
4153 static int halt_parse_argv(int argc, char *argv[]) {
4162 static const struct option options[] = {
4163 { "help", no_argument, NULL, ARG_HELP },
4164 { "halt", no_argument, NULL, ARG_HALT },
4165 { "poweroff", no_argument, NULL, 'p' },
4166 { "reboot", no_argument, NULL, ARG_REBOOT },
4167 { "force", no_argument, NULL, 'f' },
4168 { "wtmp-only", no_argument, NULL, 'w' },
4169 { "no-wtmp", no_argument, NULL, 'd' },
4170 { "no-sync", no_argument, NULL, 'n' },
4171 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4172 { NULL, 0, NULL, 0 }
4180 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4181 if (runlevel == '0' || runlevel == '6')
4182 arg_immediate = true;
4184 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4192 arg_action = ACTION_HALT;
4196 if (arg_action != ACTION_REBOOT)
4197 arg_action = ACTION_POWEROFF;
4201 arg_action = ACTION_REBOOT;
4205 arg_immediate = true;
4226 /* Compatibility nops */
4233 log_error("Unknown option code %c", c);
4238 if (optind < argc) {
4239 log_error("Too many arguments.");
4246 static int parse_time_spec(const char *t, usec_t *_u) {
4250 if (streq(t, "now"))
4252 else if (t[0] == '+') {
4255 if (safe_atou64(t + 1, &u) < 0)
4258 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4267 hour = strtol(t, &e, 10);
4268 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4271 minute = strtol(e+1, &e, 10);
4272 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4275 n = now(CLOCK_REALTIME);
4276 s = (time_t) (n / USEC_PER_SEC);
4279 assert_se(localtime_r(&s, &tm));
4281 tm.tm_hour = (int) hour;
4282 tm.tm_min = (int) minute;
4285 assert_se(s = mktime(&tm));
4287 *_u = (usec_t) s * USEC_PER_SEC;
4290 *_u += USEC_PER_DAY;
4296 static int shutdown_parse_argv(int argc, char *argv[]) {
4303 static const struct option options[] = {
4304 { "help", no_argument, NULL, ARG_HELP },
4305 { "halt", no_argument, NULL, 'H' },
4306 { "poweroff", no_argument, NULL, 'P' },
4307 { "reboot", no_argument, NULL, 'r' },
4308 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4309 { NULL, 0, NULL, 0 }
4317 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4325 arg_action = ACTION_HALT;
4329 arg_action = ACTION_POWEROFF;
4333 arg_action = ACTION_REBOOT;
4337 if (arg_action != ACTION_HALT)
4338 arg_action = ACTION_POWEROFF;
4351 /* Compatibility nops */
4355 arg_action = ACTION_CANCEL_SHUTDOWN;
4362 log_error("Unknown option code %c", c);
4367 if (argc > optind) {
4368 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4369 log_error("Failed to parse time specification: %s", argv[optind]);
4373 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4375 /* We skip the time argument */
4376 if (argc > optind + 1)
4377 arg_wall = argv + optind + 1;
4384 static int telinit_parse_argv(int argc, char *argv[]) {
4391 static const struct option options[] = {
4392 { "help", no_argument, NULL, ARG_HELP },
4393 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4394 { NULL, 0, NULL, 0 }
4397 static const struct {
4401 { '0', ACTION_POWEROFF },
4402 { '6', ACTION_REBOOT },
4403 { '1', ACTION_RESCUE },
4404 { '2', ACTION_RUNLEVEL2 },
4405 { '3', ACTION_RUNLEVEL3 },
4406 { '4', ACTION_RUNLEVEL4 },
4407 { '5', ACTION_RUNLEVEL5 },
4408 { 's', ACTION_RESCUE },
4409 { 'S', ACTION_RESCUE },
4410 { 'q', ACTION_RELOAD },
4411 { 'Q', ACTION_RELOAD },
4412 { 'u', ACTION_REEXEC },
4413 { 'U', ACTION_REEXEC }
4422 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4437 log_error("Unknown option code %c", c);
4442 if (optind >= argc) {
4447 if (optind + 1 < argc) {
4448 log_error("Too many arguments.");
4452 if (strlen(argv[optind]) != 1) {
4453 log_error("Expected single character argument.");
4457 for (i = 0; i < ELEMENTSOF(table); i++)
4458 if (table[i].from == argv[optind][0])
4461 if (i >= ELEMENTSOF(table)) {
4462 log_error("Unknown command %s.", argv[optind]);
4466 arg_action = table[i].to;
4473 static int runlevel_parse_argv(int argc, char *argv[]) {
4479 static const struct option options[] = {
4480 { "help", no_argument, NULL, ARG_HELP },
4481 { NULL, 0, NULL, 0 }
4489 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4500 log_error("Unknown option code %c", c);
4505 if (optind < argc) {
4506 log_error("Too many arguments.");
4513 static int parse_argv(int argc, char *argv[]) {
4517 if (program_invocation_short_name) {
4519 if (strstr(program_invocation_short_name, "halt")) {
4520 arg_action = ACTION_HALT;
4521 return halt_parse_argv(argc, argv);
4522 } else if (strstr(program_invocation_short_name, "poweroff")) {
4523 arg_action = ACTION_POWEROFF;
4524 return halt_parse_argv(argc, argv);
4525 } else if (strstr(program_invocation_short_name, "reboot")) {
4526 arg_action = ACTION_REBOOT;
4527 return halt_parse_argv(argc, argv);
4528 } else if (strstr(program_invocation_short_name, "shutdown")) {
4529 arg_action = ACTION_POWEROFF;
4530 return shutdown_parse_argv(argc, argv);
4531 } else if (strstr(program_invocation_short_name, "init")) {
4533 if (sd_booted() > 0) {
4534 arg_action = ACTION_INVALID;
4535 return telinit_parse_argv(argc, argv);
4537 /* Hmm, so some other init system is
4538 * running, we need to forward this
4539 * request to it. For now we simply
4540 * guess that it is Upstart. */
4542 execv("/lib/upstart/telinit", argv);
4544 log_error("Couldn't find an alternative telinit implementation to spawn.");
4548 } else if (strstr(program_invocation_short_name, "runlevel")) {
4549 arg_action = ACTION_RUNLEVEL;
4550 return runlevel_parse_argv(argc, argv);
4554 arg_action = ACTION_SYSTEMCTL;
4555 return systemctl_parse_argv(argc, argv);
4558 static int action_to_runlevel(void) {
4560 static const char table[_ACTION_MAX] = {
4561 [ACTION_HALT] = '0',
4562 [ACTION_POWEROFF] = '0',
4563 [ACTION_REBOOT] = '6',
4564 [ACTION_RUNLEVEL2] = '2',
4565 [ACTION_RUNLEVEL3] = '3',
4566 [ACTION_RUNLEVEL4] = '4',
4567 [ACTION_RUNLEVEL5] = '5',
4568 [ACTION_RESCUE] = '1'
4571 assert(arg_action < _ACTION_MAX);
4573 return table[arg_action];
4576 static int talk_upstart(void) {
4577 DBusMessage *m = NULL, *reply = NULL;
4579 int previous, rl, r;
4581 env1_buf[] = "RUNLEVEL=X",
4582 env2_buf[] = "PREVLEVEL=X";
4583 char *env1 = env1_buf, *env2 = env2_buf;
4584 const char *emit = "runlevel";
4585 dbus_bool_t b_false = FALSE;
4586 DBusMessageIter iter, sub;
4587 DBusConnection *bus;
4589 dbus_error_init(&error);
4591 if (!(rl = action_to_runlevel()))
4594 if (utmp_get_runlevel(&previous, NULL) < 0)
4597 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4598 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4603 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4608 if ((r = bus_check_peercred(bus)) < 0) {
4609 log_error("Failed to verify owner of bus.");
4613 if (!(m = dbus_message_new_method_call(
4614 "com.ubuntu.Upstart",
4615 "/com/ubuntu/Upstart",
4616 "com.ubuntu.Upstart0_6",
4619 log_error("Could not allocate message.");
4624 dbus_message_iter_init_append(m, &iter);
4626 env1_buf[sizeof(env1_buf)-2] = rl;
4627 env2_buf[sizeof(env2_buf)-2] = previous;
4629 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4630 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4631 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4632 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4633 !dbus_message_iter_close_container(&iter, &sub) ||
4634 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4635 log_error("Could not append arguments to message.");
4640 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4642 if (error_is_no_service(&error)) {
4647 log_error("Failed to issue method call: %s", bus_error_message(&error));
4656 dbus_message_unref(m);
4659 dbus_message_unref(reply);
4662 dbus_connection_flush(bus);
4663 dbus_connection_close(bus);
4664 dbus_connection_unref(bus);
4667 dbus_error_free(&error);
4672 static int talk_initctl(void) {
4673 struct init_request request;
4677 if (!(rl = action_to_runlevel()))
4681 request.magic = INIT_MAGIC;
4682 request.sleeptime = 0;
4683 request.cmd = INIT_CMD_RUNLVL;
4684 request.runlevel = rl;
4686 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4688 if (errno == ENOENT)
4691 log_error("Failed to open "INIT_FIFO": %m");
4696 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4697 close_nointr_nofail(fd);
4700 log_error("Failed to write to "INIT_FIFO": %m");
4701 return errno ? -errno : -EIO;
4707 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4709 static const struct {
4717 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4719 { "list-units", LESS, 1, list_units },
4720 { "list-jobs", EQUAL, 1, list_jobs },
4721 { "clear-jobs", EQUAL, 1, daemon_reload },
4722 { "load", MORE, 2, load_unit },
4723 { "cancel", MORE, 2, cancel_job },
4724 { "start", MORE, 2, start_unit },
4725 { "stop", MORE, 2, start_unit },
4726 { "reload", MORE, 2, start_unit },
4727 { "restart", MORE, 2, start_unit },
4728 { "try-restart", MORE, 2, start_unit },
4729 { "reload-or-restart", MORE, 2, start_unit },
4730 { "reload-or-try-restart", MORE, 2, start_unit },
4731 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4732 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4733 { "isolate", EQUAL, 2, start_unit },
4734 { "is-active", MORE, 2, check_unit },
4735 { "check", MORE, 2, check_unit },
4736 { "show", MORE, 1, show },
4737 { "status", MORE, 2, show },
4738 { "monitor", EQUAL, 1, monitor },
4739 { "dump", EQUAL, 1, dump },
4740 { "dot", EQUAL, 1, dot },
4741 { "snapshot", LESS, 2, snapshot },
4742 { "delete", MORE, 2, delete_snapshot },
4743 { "daemon-reload", EQUAL, 1, daemon_reload },
4744 { "daemon-reexec", EQUAL, 1, daemon_reload },
4745 { "daemon-exit", EQUAL, 1, daemon_reload },
4746 { "show-environment", EQUAL, 1, show_enviroment },
4747 { "set-environment", MORE, 2, set_environment },
4748 { "unset-environment", MORE, 2, set_environment },
4749 { "halt", EQUAL, 1, start_special },
4750 { "poweroff", EQUAL, 1, start_special },
4751 { "reboot", EQUAL, 1, start_special },
4752 { "default", EQUAL, 1, start_special },
4753 { "rescue", EQUAL, 1, start_special },
4754 { "emergency", EQUAL, 1, start_special },
4755 { "reset-failed", MORE, 1, reset_failed },
4756 { "enable", MORE, 2, enable_unit },
4757 { "disable", MORE, 2, enable_unit },
4758 { "is-enabled", MORE, 2, enable_unit }
4768 left = argc - optind;
4771 /* Special rule: no arguments means "list-units" */
4774 if (streq(argv[optind], "help")) {
4779 for (i = 0; i < ELEMENTSOF(verbs); i++)
4780 if (streq(argv[optind], verbs[i].verb))
4783 if (i >= ELEMENTSOF(verbs)) {
4784 log_error("Unknown operation %s", argv[optind]);
4789 switch (verbs[i].argc_cmp) {
4792 if (left != verbs[i].argc) {
4793 log_error("Invalid number of arguments.");
4800 if (left < verbs[i].argc) {
4801 log_error("Too few arguments.");
4808 if (left > verbs[i].argc) {
4809 log_error("Too many arguments.");
4816 assert_not_reached("Unknown comparison operator.");
4819 /* Require a bus connection for all operations but
4821 if (!streq(verbs[i].verb, "enable") &&
4822 !streq(verbs[i].verb, "disable") &&
4824 log_error("Failed to get D-Bus connection: %s", error->message);
4828 return verbs[i].dispatch(bus, argv + optind, left);
4831 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
4833 struct msghdr msghdr;
4835 union sockaddr_union sockaddr;
4836 struct shutdownd_command c;
4844 strncpy(c.wall_message, message, sizeof(c.wall_message));
4846 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4850 sockaddr.sa.sa_family = AF_UNIX;
4851 sockaddr.un.sun_path[0] = 0;
4852 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
4855 iovec.iov_base = (char*) &c;
4856 iovec.iov_len = sizeof(c);
4859 msghdr.msg_name = &sockaddr;
4860 msghdr.msg_namelen = sizeof(sa_family_t) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
4862 msghdr.msg_iov = &iovec;
4863 msghdr.msg_iovlen = 1;
4865 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
4866 close_nointr_nofail(fd);
4870 close_nointr_nofail(fd);
4874 static int reload_with_fallback(DBusConnection *bus) {
4877 /* First, try systemd via D-Bus. */
4878 if (daemon_reload(bus, NULL, 0) > 0)
4882 /* Nothing else worked, so let's try signals */
4883 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
4885 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
4886 log_error("kill() failed: %m");
4893 static int start_with_fallback(DBusConnection *bus) {
4896 /* First, try systemd via D-Bus. */
4897 if (start_unit(bus, NULL, 0) >= 0)
4901 /* Hmm, talking to systemd via D-Bus didn't work. Then
4902 * let's try to talk to Upstart via D-Bus. */
4903 if (talk_upstart() > 0)
4906 /* Nothing else worked, so let's try
4908 if (talk_initctl() > 0)
4911 log_error("Failed to talk to init daemon.");
4915 warn_wall(arg_action);
4919 static int halt_main(DBusConnection *bus) {
4922 if (geteuid() != 0) {
4923 log_error("Must be root.");
4929 char date[FORMAT_TIMESTAMP_MAX];
4931 m = strv_join(arg_wall, " ");
4932 r = send_shutdownd(arg_when,
4933 arg_action == ACTION_HALT ? 'H' :
4934 arg_action == ACTION_POWEROFF ? 'P' :
4941 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
4943 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
4944 format_timestamp(date, sizeof(date), arg_when));
4949 if (!arg_dry && !arg_immediate)
4950 return start_with_fallback(bus);
4953 if (sd_booted() > 0)
4954 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
4955 else if ((r = utmp_put_shutdown(0)) < 0)
4956 log_warning("Failed to write utmp record: %s", strerror(-r));
4965 /* Make sure C-A-D is handled by the kernel from this
4967 reboot(RB_ENABLE_CAD);
4969 switch (arg_action) {
4972 log_info("Halting.");
4973 reboot(RB_HALT_SYSTEM);
4976 case ACTION_POWEROFF:
4977 log_info("Powering off.");
4978 reboot(RB_POWER_OFF);
4982 log_info("Rebooting.");
4983 reboot(RB_AUTOBOOT);
4987 assert_not_reached("Unknown halt action.");
4990 /* We should never reach this. */
4994 static int runlevel_main(void) {
4995 int r, runlevel, previous;
4997 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
4998 printf("unknown\n");
5003 previous <= 0 ? 'N' : previous,
5004 runlevel <= 0 ? 'N' : runlevel);
5009 int main(int argc, char*argv[]) {
5010 int r, retval = EXIT_FAILURE;
5011 DBusConnection *bus = NULL;
5014 dbus_error_init(&error);
5016 log_parse_environment();
5019 if ((r = parse_argv(argc, argv)) < 0)
5022 retval = EXIT_SUCCESS;
5026 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5027 * let's shortcut this */
5028 if (arg_action == ACTION_RUNLEVEL) {
5029 r = runlevel_main();
5030 retval = r < 0 ? EXIT_FAILURE : r;
5034 bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5036 switch (arg_action) {
5038 case ACTION_SYSTEMCTL:
5039 r = systemctl_main(bus, argc, argv, &error);
5043 case ACTION_POWEROFF:
5048 case ACTION_RUNLEVEL2:
5049 case ACTION_RUNLEVEL3:
5050 case ACTION_RUNLEVEL4:
5051 case ACTION_RUNLEVEL5:
5053 case ACTION_EMERGENCY:
5054 case ACTION_DEFAULT:
5055 r = start_with_fallback(bus);
5060 r = reload_with_fallback(bus);
5063 case ACTION_CANCEL_SHUTDOWN:
5064 r = send_shutdownd(0, 0, false, NULL);
5067 case ACTION_INVALID:
5068 case ACTION_RUNLEVEL:
5070 assert_not_reached("Unknown action");
5073 retval = r < 0 ? EXIT_FAILURE : r;
5078 dbus_connection_flush(bus);
5079 dbus_connection_close(bus);
5080 dbus_connection_unref(bus);
5083 dbus_error_free(&error);
5087 strv_free(arg_property);