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 void output_units_list(const struct unit_info *unit_infos, unsigned c) {
256 if (columns() >= 80+12 || arg_full)
257 printf("%-25s %-6s %-12s %-18s %-15s %s\n", "UNIT", "LOAD", "ACTIVE", "SUB", "JOB", "DESCRIPTION");
259 printf("%-25s %-6s %-12s %-18s %-15s\n", "UNIT", "LOAD", "ACTIVE", "SUB", "JOB");
262 for (const struct unit_info *u = unit_infos; u < unit_infos + c; u++) {
265 if ((!arg_type || ((dot = strrchr(u->id, '.')) &&
266 streq(dot+1, arg_type))) &&
267 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0)) {
270 const char *on_loaded, *off_loaded;
271 const char *on_active, *off_active;
273 if (!streq(u->load_state, "loaded")) {
274 on_loaded = ansi_highlight(true);
275 off_loaded = ansi_highlight(false);
277 on_loaded = off_loaded = "";
279 if (streq(u->active_state, "failed")) {
280 on_active = ansi_highlight(true);
281 off_active = ansi_highlight(false);
283 on_active = off_active = "";
285 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
287 printf("%-25s %s%-6s%s %s%-12s %-18s%s%n",
289 on_loaded, u->load_state, off_loaded,
290 on_active, u->active_state, u->sub_state, off_active,
295 a -= strlen(on_loaded) + strlen(off_loaded);
296 a -= strlen(on_active) + strlen(off_active);
299 printf(" %-15s%n", u->job_type, &b);
303 if (a + b + 1 < columns()) {
308 printf(" %s", u->description);
310 printf(" %.*s", columns() - a - b - 1, u->description);
318 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
319 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
320 "SUB = The low-level unit activation state, values depend on unit type.\n"
321 "JOB = Pending job for the unit.\n");
324 printf("\n%u units listed.\n", c);
326 printf("\n%u units listed. Pass --all to see inactive units, too.\n", c);
330 static int list_units(DBusConnection *bus, char **args, unsigned n) {
331 DBusMessage *m = NULL, *reply = NULL;
334 DBusMessageIter iter, sub, sub2;
335 unsigned c = 0, n_units = 0;
336 struct unit_info *unit_infos = NULL;
338 dbus_error_init(&error);
342 if (!(m = dbus_message_new_method_call(
343 "org.freedesktop.systemd1",
344 "/org/freedesktop/systemd1",
345 "org.freedesktop.systemd1.Manager",
347 log_error("Could not allocate message.");
351 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
352 log_error("Failed to issue method call: %s", bus_error_message(&error));
357 if (!dbus_message_iter_init(reply, &iter) ||
358 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
359 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
360 log_error("Failed to parse reply.");
365 dbus_message_iter_recurse(&iter, &sub);
367 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
370 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
371 log_error("Failed to parse reply.");
379 n_units = MAX(2*c, 16);
380 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
383 log_error("Failed to allocate unit array.");
393 dbus_message_iter_recurse(&sub, &sub2);
395 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
396 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
397 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
398 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
399 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
400 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
401 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
402 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
403 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
404 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
405 log_error("Failed to parse reply.");
410 dbus_message_iter_next(&sub);
414 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
415 output_units_list(unit_infos, c);
421 dbus_message_unref(m);
424 dbus_message_unref(reply);
428 dbus_error_free(&error);
433 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
434 static const char * const colors[] = {
435 "Requires", "[color=\"black\"]",
436 "RequiresOverridable", "[color=\"black\"]",
437 "Requisite", "[color=\"darkblue\"]",
438 "RequisiteOverridable", "[color=\"darkblue\"]",
439 "Wants", "[color=\"darkgrey\"]",
440 "Conflicts", "[color=\"red\"]",
441 "ConflictedBy", "[color=\"red\"]",
442 "After", "[color=\"green\"]"
445 const char *c = NULL;
452 for (i = 0; i < ELEMENTSOF(colors); i += 2)
453 if (streq(colors[i], prop)) {
461 if (arg_dot != DOT_ALL)
462 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
465 switch (dbus_message_iter_get_arg_type(iter)) {
467 case DBUS_TYPE_ARRAY:
469 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
472 dbus_message_iter_recurse(iter, &sub);
474 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
477 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
478 dbus_message_iter_get_basic(&sub, &s);
479 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
481 dbus_message_iter_next(&sub);
491 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
492 DBusMessage *m = NULL, *reply = NULL;
493 const char *interface = "org.freedesktop.systemd1.Unit";
496 DBusMessageIter iter, sub, sub2, sub3;
501 dbus_error_init(&error);
503 if (!(m = dbus_message_new_method_call(
504 "org.freedesktop.systemd1",
506 "org.freedesktop.DBus.Properties",
508 log_error("Could not allocate message.");
513 if (!dbus_message_append_args(m,
514 DBUS_TYPE_STRING, &interface,
515 DBUS_TYPE_INVALID)) {
516 log_error("Could not append arguments to message.");
521 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
522 log_error("Failed to issue method call: %s", bus_error_message(&error));
527 if (!dbus_message_iter_init(reply, &iter) ||
528 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
529 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
530 log_error("Failed to parse reply.");
535 dbus_message_iter_recurse(&iter, &sub);
537 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
540 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
541 log_error("Failed to parse reply.");
546 dbus_message_iter_recurse(&sub, &sub2);
548 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
549 log_error("Failed to parse reply.");
554 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
555 log_error("Failed to parse reply.");
560 dbus_message_iter_recurse(&sub2, &sub3);
562 if (dot_one_property(name, prop, &sub3)) {
563 log_error("Failed to parse reply.");
568 dbus_message_iter_next(&sub);
575 dbus_message_unref(m);
578 dbus_message_unref(reply);
580 dbus_error_free(&error);
585 static int dot(DBusConnection *bus, char **args, unsigned n) {
586 DBusMessage *m = NULL, *reply = NULL;
589 DBusMessageIter iter, sub, sub2;
591 dbus_error_init(&error);
595 if (!(m = dbus_message_new_method_call(
596 "org.freedesktop.systemd1",
597 "/org/freedesktop/systemd1",
598 "org.freedesktop.systemd1.Manager",
600 log_error("Could not allocate message.");
604 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
605 log_error("Failed to issue method call: %s", bus_error_message(&error));
610 if (!dbus_message_iter_init(reply, &iter) ||
611 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
612 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
613 log_error("Failed to parse reply.");
618 printf("digraph systemd {\n");
620 dbus_message_iter_recurse(&iter, &sub);
621 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
622 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
624 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
625 log_error("Failed to parse reply.");
630 dbus_message_iter_recurse(&sub, &sub2);
632 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
633 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
634 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
635 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
636 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
637 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
638 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
639 log_error("Failed to parse reply.");
644 if ((r = dot_one(bus, id, unit_path)) < 0)
647 /* printf("\t\"%s\";\n", id); */
648 dbus_message_iter_next(&sub);
653 log_info(" Color legend: black = Requires\n"
654 " dark blue = Requisite\n"
655 " dark grey = Wants\n"
659 if (isatty(fileno(stdout)))
660 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
661 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
667 dbus_message_unref(m);
670 dbus_message_unref(reply);
672 dbus_error_free(&error);
677 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
678 DBusMessage *m = NULL, *reply = NULL;
681 DBusMessageIter iter, sub, sub2;
684 dbus_error_init(&error);
688 if (!(m = dbus_message_new_method_call(
689 "org.freedesktop.systemd1",
690 "/org/freedesktop/systemd1",
691 "org.freedesktop.systemd1.Manager",
693 log_error("Could not allocate message.");
697 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
698 log_error("Failed to issue method call: %s", bus_error_message(&error));
703 if (!dbus_message_iter_init(reply, &iter) ||
704 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
705 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
706 log_error("Failed to parse reply.");
711 dbus_message_iter_recurse(&iter, &sub);
713 if (isatty(STDOUT_FILENO))
714 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
716 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
717 const char *name, *type, *state, *job_path, *unit_path;
721 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
722 log_error("Failed to parse reply.");
727 dbus_message_iter_recurse(&sub, &sub2);
729 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
730 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
731 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
732 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
733 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
734 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
735 log_error("Failed to parse reply.");
740 e = arg_full ? NULL : ellipsize(name, 25, 33);
741 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
746 dbus_message_iter_next(&sub);
749 if (isatty(STDOUT_FILENO))
750 printf("\n%u jobs listed.\n", k);
756 dbus_message_unref(m);
759 dbus_message_unref(reply);
761 dbus_error_free(&error);
766 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
767 DBusMessage *m = NULL, *reply = NULL;
772 dbus_error_init(&error);
777 for (i = 1; i < n; i++) {
779 if (!(m = dbus_message_new_method_call(
780 "org.freedesktop.systemd1",
781 "/org/freedesktop/systemd1",
782 "org.freedesktop.systemd1.Manager",
784 log_error("Could not allocate message.");
789 if (!dbus_message_append_args(m,
790 DBUS_TYPE_STRING, &args[i],
791 DBUS_TYPE_INVALID)) {
792 log_error("Could not append arguments to message.");
797 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
798 log_error("Failed to issue method call: %s", bus_error_message(&error));
803 dbus_message_unref(m);
804 dbus_message_unref(reply);
813 dbus_message_unref(m);
816 dbus_message_unref(reply);
818 dbus_error_free(&error);
823 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
824 DBusMessage *m = NULL, *reply = NULL;
829 dbus_error_init(&error);
835 return daemon_reload(bus, args, n);
837 for (i = 1; i < n; i++) {
841 if (!(m = dbus_message_new_method_call(
842 "org.freedesktop.systemd1",
843 "/org/freedesktop/systemd1",
844 "org.freedesktop.systemd1.Manager",
846 log_error("Could not allocate message.");
851 if ((r = safe_atou(args[i], &id)) < 0) {
852 log_error("Failed to parse job id: %s", strerror(-r));
856 assert_cc(sizeof(uint32_t) == sizeof(id));
857 if (!dbus_message_append_args(m,
858 DBUS_TYPE_UINT32, &id,
859 DBUS_TYPE_INVALID)) {
860 log_error("Could not append arguments to message.");
865 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
866 log_error("Failed to issue method call: %s", bus_error_message(&error));
871 if (!dbus_message_get_args(reply, &error,
872 DBUS_TYPE_OBJECT_PATH, &path,
873 DBUS_TYPE_INVALID)) {
874 log_error("Failed to parse reply: %s", bus_error_message(&error));
879 dbus_message_unref(m);
880 if (!(m = dbus_message_new_method_call(
881 "org.freedesktop.systemd1",
883 "org.freedesktop.systemd1.Job",
885 log_error("Could not allocate message.");
890 dbus_message_unref(reply);
891 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
892 log_error("Failed to issue method call: %s", bus_error_message(&error));
897 dbus_message_unref(m);
898 dbus_message_unref(reply);
906 dbus_message_unref(m);
909 dbus_message_unref(reply);
911 dbus_error_free(&error);
916 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
917 DBusMessage *m = NULL, *reply = NULL;
918 dbus_bool_t b = FALSE;
919 DBusMessageIter iter, sub;
921 *interface = "org.freedesktop.systemd1.Unit",
922 *property = "NeedDaemonReload",
925 /* We ignore all errors here, since this is used to show a warning only */
927 if (!(m = dbus_message_new_method_call(
928 "org.freedesktop.systemd1",
929 "/org/freedesktop/systemd1",
930 "org.freedesktop.systemd1.Manager",
934 if (!dbus_message_append_args(m,
935 DBUS_TYPE_STRING, &unit,
939 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
942 if (!dbus_message_get_args(reply, NULL,
943 DBUS_TYPE_OBJECT_PATH, &path,
947 dbus_message_unref(m);
948 if (!(m = dbus_message_new_method_call(
949 "org.freedesktop.systemd1",
951 "org.freedesktop.DBus.Properties",
955 if (!dbus_message_append_args(m,
956 DBUS_TYPE_STRING, &interface,
957 DBUS_TYPE_STRING, &property,
958 DBUS_TYPE_INVALID)) {
962 dbus_message_unref(reply);
963 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
966 if (!dbus_message_iter_init(reply, &iter) ||
967 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
970 dbus_message_iter_recurse(&iter, &sub);
972 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
975 dbus_message_iter_get_basic(&sub, &b);
979 dbus_message_unref(m);
982 dbus_message_unref(reply);
987 typedef struct WaitData {
992 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1000 dbus_error_init(&error);
1002 log_debug("Got D-Bus request: %s.%s() on %s",
1003 dbus_message_get_interface(message),
1004 dbus_message_get_member(message),
1005 dbus_message_get_path(message));
1007 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1008 log_error("Warning! D-Bus connection terminated.");
1009 dbus_connection_close(connection);
1011 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1014 dbus_bool_t success = true;
1016 if (!dbus_message_get_args(message, &error,
1017 DBUS_TYPE_UINT32, &id,
1018 DBUS_TYPE_OBJECT_PATH, &path,
1019 DBUS_TYPE_BOOLEAN, &success,
1021 log_error("Failed to parse message: %s", bus_error_message(&error));
1025 if ((p = set_remove(d->set, (char*) path)))
1033 dbus_error_free(&error);
1034 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1037 static int enable_wait_for_jobs(DBusConnection *bus) {
1045 dbus_error_init(&error);
1046 dbus_bus_add_match(bus,
1048 "sender='org.freedesktop.systemd1',"
1049 "interface='org.freedesktop.systemd1.Manager',"
1050 "member='JobRemoved',"
1051 "path='/org/freedesktop/systemd1'",
1054 if (dbus_error_is_set(&error)) {
1055 log_error("Failed to add match: %s", bus_error_message(&error));
1056 dbus_error_free(&error);
1060 /* This is slightly dirty, since we don't undo the match registrations. */
1064 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1075 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1076 log_error("Failed to add filter.");
1081 while (!set_isempty(s) &&
1082 dbus_connection_read_write_dispatch(bus, -1))
1085 if (!arg_quiet && d.failed)
1086 log_error("Job failed, see system logs for details.");
1088 r = d.failed ? -EIO : 0;
1091 /* This is slightly dirty, since we don't undo the filter registration. */
1096 static int start_unit_one(
1097 DBusConnection *bus,
1104 DBusMessage *m = NULL, *reply = NULL;
1113 assert(arg_no_block || s);
1115 if (!(m = dbus_message_new_method_call(
1116 "org.freedesktop.systemd1",
1117 "/org/freedesktop/systemd1",
1118 "org.freedesktop.systemd1.Manager",
1120 log_error("Could not allocate message.");
1125 if (!dbus_message_append_args(m,
1126 DBUS_TYPE_STRING, &name,
1127 DBUS_TYPE_STRING, &mode,
1128 DBUS_TYPE_INVALID)) {
1129 log_error("Could not append arguments to message.");
1134 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1136 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1137 /* There's always a fallback possible for
1138 * legacy actions. */
1143 log_error("Failed to issue method call: %s", bus_error_message(error));
1148 if (!dbus_message_get_args(reply, error,
1149 DBUS_TYPE_OBJECT_PATH, &path,
1150 DBUS_TYPE_INVALID)) {
1151 log_error("Failed to parse reply: %s", bus_error_message(error));
1156 if (need_daemon_reload(bus, name))
1157 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1158 arg_session ? "--session" : "--system");
1160 if (!arg_no_block) {
1163 if (!(p = strdup(path))) {
1164 log_error("Failed to duplicate path.");
1169 if ((r = set_put(s, p)) < 0) {
1171 log_error("Failed to add path to set.");
1180 dbus_message_unref(m);
1183 dbus_message_unref(reply);
1188 static enum action verb_to_action(const char *verb) {
1189 if (streq(verb, "halt"))
1191 else if (streq(verb, "poweroff"))
1192 return ACTION_POWEROFF;
1193 else if (streq(verb, "reboot"))
1194 return ACTION_REBOOT;
1195 else if (streq(verb, "rescue"))
1196 return ACTION_RESCUE;
1197 else if (streq(verb, "emergency"))
1198 return ACTION_EMERGENCY;
1199 else if (streq(verb, "default"))
1200 return ACTION_DEFAULT;
1202 return ACTION_INVALID;
1205 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1207 static const char * const table[_ACTION_MAX] = {
1208 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1209 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1210 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1211 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1212 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1213 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1214 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1215 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1216 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1217 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET
1222 const char *method, *mode, *one_name;
1226 dbus_error_init(&error);
1230 if (arg_action == ACTION_SYSTEMCTL) {
1232 streq(args[0], "stop") ? "StopUnit" :
1233 streq(args[0], "reload") ? "ReloadUnit" :
1234 streq(args[0], "restart") ? "RestartUnit" :
1235 streq(args[0], "try-restart") ? "TryRestartUnit" :
1236 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1237 streq(args[0], "reload-or-try-restart") ||
1238 streq(args[0], "force-reload") ||
1239 streq(args[0], "condrestart") ? "ReloadOrTryRestartUnit" :
1243 (streq(args[0], "isolate") ||
1244 streq(args[0], "rescue") ||
1245 streq(args[0], "emergency")) ? "isolate" :
1249 one_name = table[verb_to_action(args[0])];
1252 assert(arg_action < ELEMENTSOF(table));
1253 assert(table[arg_action]);
1255 method = "StartUnit";
1257 mode = (arg_action == ACTION_EMERGENCY ||
1258 arg_action == ACTION_RESCUE ||
1259 arg_action == ACTION_RUNLEVEL2 ||
1260 arg_action == ACTION_RUNLEVEL3 ||
1261 arg_action == ACTION_RUNLEVEL4 ||
1262 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1264 one_name = table[arg_action];
1267 if (!arg_no_block) {
1268 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1269 log_error("Could not watch jobs: %s", strerror(-ret));
1273 if (!(s = set_new(string_hash_func, string_compare_func))) {
1274 log_error("Failed to allocate set.");
1281 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1284 for (i = 1; i < n; i++)
1285 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1286 ret = translate_bus_error_to_exit_status(r, &error);
1287 dbus_error_free(&error);
1292 if ((r = wait_for_jobs(bus, s)) < 0) {
1301 dbus_error_free(&error);
1306 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1312 r = start_unit(bus, args, n);
1315 warn_wall(verb_to_action(args[0]));
1320 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1321 DBusMessage *m = NULL, *reply = NULL;
1323 *interface = "org.freedesktop.systemd1.Unit",
1324 *property = "ActiveState";
1325 int r = 3; /* According to LSB: "program is not running" */
1332 dbus_error_init(&error);
1334 for (i = 1; i < n; i++) {
1335 const char *path = NULL;
1337 DBusMessageIter iter, sub;
1339 if (!(m = dbus_message_new_method_call(
1340 "org.freedesktop.systemd1",
1341 "/org/freedesktop/systemd1",
1342 "org.freedesktop.systemd1.Manager",
1344 log_error("Could not allocate message.");
1349 if (!dbus_message_append_args(m,
1350 DBUS_TYPE_STRING, &args[i],
1351 DBUS_TYPE_INVALID)) {
1352 log_error("Could not append arguments to message.");
1357 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1359 /* Hmm, cannot figure out anything about this unit... */
1363 dbus_error_free(&error);
1367 if (!dbus_message_get_args(reply, &error,
1368 DBUS_TYPE_OBJECT_PATH, &path,
1369 DBUS_TYPE_INVALID)) {
1370 log_error("Failed to parse reply: %s", bus_error_message(&error));
1375 dbus_message_unref(m);
1376 if (!(m = dbus_message_new_method_call(
1377 "org.freedesktop.systemd1",
1379 "org.freedesktop.DBus.Properties",
1381 log_error("Could not allocate message.");
1386 if (!dbus_message_append_args(m,
1387 DBUS_TYPE_STRING, &interface,
1388 DBUS_TYPE_STRING, &property,
1389 DBUS_TYPE_INVALID)) {
1390 log_error("Could not append arguments to message.");
1395 dbus_message_unref(reply);
1396 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1397 log_error("Failed to issue method call: %s", bus_error_message(&error));
1402 if (!dbus_message_iter_init(reply, &iter) ||
1403 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1404 log_error("Failed to parse reply.");
1409 dbus_message_iter_recurse(&iter, &sub);
1411 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1412 log_error("Failed to parse reply.");
1417 dbus_message_iter_get_basic(&sub, &state);
1422 if (streq(state, "active") || streq(state, "reloading"))
1425 dbus_message_unref(m);
1426 dbus_message_unref(reply);
1432 dbus_message_unref(m);
1435 dbus_message_unref(reply);
1437 dbus_error_free(&error);
1442 typedef struct ExecStatusInfo {
1448 usec_t start_timestamp;
1449 usec_t exit_timestamp;
1454 LIST_FIELDS(struct ExecStatusInfo, exec);
1457 static void exec_status_info_free(ExecStatusInfo *i) {
1465 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1466 uint64_t start_timestamp, exit_timestamp;
1467 DBusMessageIter sub2, sub3;
1471 int32_t code, status;
1477 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1480 dbus_message_iter_recurse(sub, &sub2);
1482 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1485 if (!(i->path = strdup(path)))
1488 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1489 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1493 dbus_message_iter_recurse(&sub2, &sub3);
1494 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1495 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1496 dbus_message_iter_next(&sub3);
1501 if (!(i->argv = new0(char*, n+1)))
1505 dbus_message_iter_recurse(&sub2, &sub3);
1506 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1509 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1510 dbus_message_iter_get_basic(&sub3, &s);
1511 dbus_message_iter_next(&sub3);
1513 if (!(i->argv[n++] = strdup(s)))
1517 if (!dbus_message_iter_next(&sub2) ||
1518 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1519 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1520 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1521 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1522 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1523 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1527 i->start_timestamp = (usec_t) start_timestamp;
1528 i->exit_timestamp = (usec_t) exit_timestamp;
1529 i->pid = (pid_t) pid;
1536 typedef struct UnitStatusInfo {
1538 const char *load_state;
1539 const char *active_state;
1540 const char *sub_state;
1542 const char *description;
1545 const char *default_control_group;
1547 usec_t inactive_exit_timestamp;
1548 usec_t active_enter_timestamp;
1549 usec_t active_exit_timestamp;
1550 usec_t inactive_enter_timestamp;
1552 bool need_daemon_reload;
1557 const char *status_text;
1561 usec_t start_timestamp;
1562 usec_t exit_timestamp;
1564 int exit_code, exit_status;
1567 unsigned n_accepted;
1568 unsigned n_connections;
1572 const char *sysfs_path;
1574 /* Mount, Automount */
1580 LIST_HEAD(ExecStatusInfo, exec);
1583 static void print_status_info(UnitStatusInfo *i) {
1585 const char *on, *off, *ss;
1587 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1588 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1592 /* This shows pretty information about a unit. See
1593 * print_property() for a low-level property printer */
1595 printf("%s", strna(i->id));
1597 if (i->description && !streq_ptr(i->id, i->description))
1598 printf(" - %s", i->description);
1602 if (streq_ptr(i->load_state, "failed")) {
1603 on = ansi_highlight(true);
1604 off = ansi_highlight(false);
1609 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1611 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1613 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1615 if (streq_ptr(i->active_state, "failed")) {
1616 on = ansi_highlight(true);
1617 off = ansi_highlight(false);
1618 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1619 on = ansi_highlight_green(true);
1620 off = ansi_highlight_green(false);
1625 printf("\t Active: %s%s (%s)%s",
1627 strna(i->active_state),
1631 printf("\t Active: %s%s%s",
1633 strna(i->active_state),
1636 timestamp = (streq_ptr(i->active_state, "active") ||
1637 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1638 (streq_ptr(i->active_state, "inactive") ||
1639 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1640 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1641 i->active_exit_timestamp;
1643 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1644 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1647 printf(" since [%s; %s]\n", s2, s1);
1649 printf(" since [%s]\n", s2);
1654 printf("\t Device: %s\n", i->sysfs_path);
1656 printf("\t Where: %s\n", i->where);
1658 printf("\t What: %s\n", i->what);
1661 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1663 LIST_FOREACH(exec, p, i->exec) {
1666 /* Only show exited processes here */
1670 t = strv_join(p->argv, " ");
1671 printf("\t Process: %u (%s, code=%s, ", p->pid, strna(t), sigchld_code_to_string(p->code));
1674 if (p->code == CLD_EXITED) {
1677 printf("status=%i", p->status);
1679 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1683 printf("signal=%s", signal_to_string(p->status));
1686 if (i->main_pid == p->pid &&
1687 i->start_timestamp == p->start_timestamp &&
1688 i->exit_timestamp == p->start_timestamp)
1689 /* Let's not show this twice */
1692 if (p->pid == i->control_pid)
1696 if (i->main_pid > 0 || i->control_pid > 0) {
1699 if (i->main_pid > 0) {
1700 printf("Main PID: %u", (unsigned) i->main_pid);
1704 get_process_name(i->main_pid, &t);
1709 } else if (i->exit_code > 0) {
1710 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1712 if (i->exit_code == CLD_EXITED) {
1715 printf("status=%i", i->exit_status);
1717 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1721 printf("signal=%s", signal_to_string(i->exit_status));
1726 if (i->main_pid > 0 && i->control_pid > 0)
1729 if (i->control_pid > 0) {
1732 printf(" Control: %u", (unsigned) i->control_pid);
1734 get_process_name(i->control_pid, &t);
1745 printf("\t Status: \"%s\"\n", i->status_text);
1747 if (i->default_control_group) {
1750 printf("\t CGroup: %s\n", i->default_control_group);
1752 if ((c = columns()) > 18)
1757 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
1760 if (i->need_daemon_reload)
1761 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1762 ansi_highlight(true),
1763 ansi_highlight(false),
1764 arg_session ? "--session" : "--system");
1767 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1769 switch (dbus_message_iter_get_arg_type(iter)) {
1771 case DBUS_TYPE_STRING: {
1774 dbus_message_iter_get_basic(iter, &s);
1777 if (streq(name, "Id"))
1779 else if (streq(name, "LoadState"))
1781 else if (streq(name, "ActiveState"))
1782 i->active_state = s;
1783 else if (streq(name, "SubState"))
1785 else if (streq(name, "Description"))
1787 else if (streq(name, "FragmentPath"))
1789 else if (streq(name, "SysVPath")) {
1792 } else if (streq(name, "DefaultControlGroup"))
1793 i->default_control_group = s;
1794 else if (streq(name, "StatusText"))
1796 else if (streq(name, "SysFSPath"))
1798 else if (streq(name, "Where"))
1800 else if (streq(name, "What"))
1807 case DBUS_TYPE_BOOLEAN: {
1810 dbus_message_iter_get_basic(iter, &b);
1812 if (streq(name, "Accept"))
1814 else if (streq(name, "NeedDaemonReload"))
1815 i->need_daemon_reload = b;
1820 case DBUS_TYPE_UINT32: {
1823 dbus_message_iter_get_basic(iter, &u);
1825 if (streq(name, "MainPID")) {
1827 i->main_pid = (pid_t) u;
1830 } else if (streq(name, "ControlPID"))
1831 i->control_pid = (pid_t) u;
1832 else if (streq(name, "ExecMainPID")) {
1834 i->main_pid = (pid_t) u;
1835 } else if (streq(name, "NAccepted"))
1837 else if (streq(name, "NConnections"))
1838 i->n_connections = u;
1843 case DBUS_TYPE_INT32: {
1846 dbus_message_iter_get_basic(iter, &j);
1848 if (streq(name, "ExecMainCode"))
1849 i->exit_code = (int) j;
1850 else if (streq(name, "ExecMainStatus"))
1851 i->exit_status = (int) j;
1856 case DBUS_TYPE_UINT64: {
1859 dbus_message_iter_get_basic(iter, &u);
1861 if (streq(name, "ExecMainStartTimestamp"))
1862 i->start_timestamp = (usec_t) u;
1863 else if (streq(name, "ExecMainExitTimestamp"))
1864 i->exit_timestamp = (usec_t) u;
1865 else if (streq(name, "ActiveEnterTimestamp"))
1866 i->active_enter_timestamp = (usec_t) u;
1867 else if (streq(name, "InactiveEnterTimestamp"))
1868 i->inactive_enter_timestamp = (usec_t) u;
1869 else if (streq(name, "InactiveExitTimestamp"))
1870 i->inactive_exit_timestamp = (usec_t) u;
1871 else if (streq(name, "ActiveExitTimestamp"))
1872 i->active_exit_timestamp = (usec_t) u;
1877 case DBUS_TYPE_ARRAY: {
1879 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
1880 startswith(name, "Exec")) {
1881 DBusMessageIter sub;
1883 dbus_message_iter_recurse(iter, &sub);
1884 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1885 ExecStatusInfo *info;
1888 if (!(info = new0(ExecStatusInfo, 1)))
1891 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
1896 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
1898 dbus_message_iter_next(&sub);
1909 static int print_property(const char *name, DBusMessageIter *iter) {
1913 /* This is a low-level property printer, see
1914 * print_status_info() for the nicer output */
1916 if (arg_property && !strv_find(arg_property, name))
1919 switch (dbus_message_iter_get_arg_type(iter)) {
1921 case DBUS_TYPE_STRING: {
1923 dbus_message_iter_get_basic(iter, &s);
1925 if (arg_all || s[0])
1926 printf("%s=%s\n", name, s);
1931 case DBUS_TYPE_BOOLEAN: {
1933 dbus_message_iter_get_basic(iter, &b);
1934 printf("%s=%s\n", name, yes_no(b));
1939 case DBUS_TYPE_UINT64: {
1941 dbus_message_iter_get_basic(iter, &u);
1943 /* Yes, heuristics! But we can change this check
1944 * should it turn out to not be sufficient */
1946 if (strstr(name, "Timestamp")) {
1947 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
1949 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
1950 printf("%s=%s\n", name, strempty(t));
1951 } else if (strstr(name, "USec")) {
1952 char timespan[FORMAT_TIMESPAN_MAX];
1954 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
1956 printf("%s=%llu\n", name, (unsigned long long) u);
1961 case DBUS_TYPE_UINT32: {
1963 dbus_message_iter_get_basic(iter, &u);
1965 if (strstr(name, "UMask") || strstr(name, "Mode"))
1966 printf("%s=%04o\n", name, u);
1968 printf("%s=%u\n", name, (unsigned) u);
1973 case DBUS_TYPE_INT32: {
1975 dbus_message_iter_get_basic(iter, &i);
1977 printf("%s=%i\n", name, (int) i);
1981 case DBUS_TYPE_STRUCT: {
1982 DBusMessageIter sub;
1983 dbus_message_iter_recurse(iter, &sub);
1985 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
1988 dbus_message_iter_get_basic(&sub, &u);
1991 printf("%s=%u\n", name, (unsigned) u);
1993 printf("%s=\n", name);
1996 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
1999 dbus_message_iter_get_basic(&sub, &s);
2001 if (arg_all || s[0])
2002 printf("%s=%s\n", name, s);
2010 case DBUS_TYPE_ARRAY:
2012 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2013 DBusMessageIter sub;
2016 dbus_message_iter_recurse(iter, &sub);
2018 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2019 printf("%s=", name);
2021 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2024 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2025 dbus_message_iter_get_basic(&sub, &s);
2026 printf("%s%s", space ? " " : "", s);
2029 dbus_message_iter_next(&sub);
2037 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2038 DBusMessageIter sub;
2040 dbus_message_iter_recurse(iter, &sub);
2042 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2043 printf("%s=", name);
2045 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2048 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2049 dbus_message_iter_get_basic(&sub, &u);
2052 dbus_message_iter_next(&sub);
2060 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2061 DBusMessageIter sub, sub2;
2063 dbus_message_iter_recurse(iter, &sub);
2064 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2065 const char *type, *path;
2067 dbus_message_iter_recurse(&sub, &sub2);
2069 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2070 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2071 printf("%s=%s\n", type, path);
2073 dbus_message_iter_next(&sub);
2078 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2079 DBusMessageIter sub, sub2;
2081 dbus_message_iter_recurse(iter, &sub);
2082 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2084 uint64_t value, next_elapse;
2086 dbus_message_iter_recurse(&sub, &sub2);
2088 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2089 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2090 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2091 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2093 printf("%s={ value=%s ; next_elapse=%s }\n",
2095 format_timespan(timespan1, sizeof(timespan1), value),
2096 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2099 dbus_message_iter_next(&sub);
2104 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2105 DBusMessageIter sub;
2107 dbus_message_iter_recurse(iter, &sub);
2108 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2109 ExecStatusInfo info;
2112 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2113 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2116 t = strv_join(info.argv, " ");
2118 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2122 yes_no(info.ignore),
2123 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2124 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2125 (unsigned) info. pid,
2126 sigchld_code_to_string(info.code),
2128 info.code == CLD_EXITED ? "" : "/",
2129 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2135 strv_free(info.argv);
2137 dbus_message_iter_next(&sub);
2147 printf("%s=[unprintable]\n", name);
2152 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2153 DBusMessage *m = NULL, *reply = NULL;
2154 const char *interface = "";
2157 DBusMessageIter iter, sub, sub2, sub3;
2158 UnitStatusInfo info;
2166 dbus_error_init(&error);
2168 if (!(m = dbus_message_new_method_call(
2169 "org.freedesktop.systemd1",
2171 "org.freedesktop.DBus.Properties",
2173 log_error("Could not allocate message.");
2178 if (!dbus_message_append_args(m,
2179 DBUS_TYPE_STRING, &interface,
2180 DBUS_TYPE_INVALID)) {
2181 log_error("Could not append arguments to message.");
2186 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2187 log_error("Failed to issue method call: %s", bus_error_message(&error));
2192 if (!dbus_message_iter_init(reply, &iter) ||
2193 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2194 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2195 log_error("Failed to parse reply.");
2200 dbus_message_iter_recurse(&iter, &sub);
2207 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2210 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2211 log_error("Failed to parse reply.");
2216 dbus_message_iter_recurse(&sub, &sub2);
2218 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2219 log_error("Failed to parse reply.");
2224 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2225 log_error("Failed to parse reply.");
2230 dbus_message_iter_recurse(&sub2, &sub3);
2232 if (show_properties)
2233 r = print_property(name, &sub3);
2235 r = status_property(name, &sub3, &info);
2238 log_error("Failed to parse reply.");
2243 dbus_message_iter_next(&sub);
2248 if (!show_properties)
2249 print_status_info(&info);
2251 if (!streq_ptr(info.active_state, "active") &&
2252 !streq_ptr(info.active_state, "reloading"))
2253 /* According to LSB: "program not running" */
2256 while ((p = info.exec)) {
2257 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2258 exec_status_info_free(p);
2263 dbus_message_unref(m);
2266 dbus_message_unref(reply);
2268 dbus_error_free(&error);
2273 static int show(DBusConnection *bus, char **args, unsigned n) {
2274 DBusMessage *m = NULL, *reply = NULL;
2278 bool show_properties, new_line = false;
2283 dbus_error_init(&error);
2285 show_properties = !streq(args[0], "status");
2287 if (show_properties && n <= 1) {
2288 /* If not argument is specified inspect the manager
2291 ret = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2295 for (i = 1; i < n; i++) {
2296 const char *path = NULL;
2299 if (safe_atou32(args[i], &id) < 0) {
2301 /* Interpret as unit name */
2303 if (!(m = dbus_message_new_method_call(
2304 "org.freedesktop.systemd1",
2305 "/org/freedesktop/systemd1",
2306 "org.freedesktop.systemd1.Manager",
2308 log_error("Could not allocate message.");
2313 if (!dbus_message_append_args(m,
2314 DBUS_TYPE_STRING, &args[i],
2315 DBUS_TYPE_INVALID)) {
2316 log_error("Could not append arguments to message.");
2321 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2323 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2324 log_error("Failed to issue method call: %s", bus_error_message(&error));
2329 dbus_error_free(&error);
2331 dbus_message_unref(m);
2332 if (!(m = dbus_message_new_method_call(
2333 "org.freedesktop.systemd1",
2334 "/org/freedesktop/systemd1",
2335 "org.freedesktop.systemd1.Manager",
2337 log_error("Could not allocate message.");
2342 if (!dbus_message_append_args(m,
2343 DBUS_TYPE_STRING, &args[i],
2344 DBUS_TYPE_INVALID)) {
2345 log_error("Could not append arguments to message.");
2350 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2351 log_error("Failed to issue method call: %s", bus_error_message(&error));
2353 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2354 ret = 4; /* According to LSB: "program or service status is unknown" */
2361 } else if (show_properties) {
2363 /* Interpret as job id */
2365 if (!(m = dbus_message_new_method_call(
2366 "org.freedesktop.systemd1",
2367 "/org/freedesktop/systemd1",
2368 "org.freedesktop.systemd1.Manager",
2370 log_error("Could not allocate message.");
2375 if (!dbus_message_append_args(m,
2376 DBUS_TYPE_UINT32, &id,
2377 DBUS_TYPE_INVALID)) {
2378 log_error("Could not append arguments to message.");
2383 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2384 log_error("Failed to issue method call: %s", bus_error_message(&error));
2390 /* Interpret as PID */
2392 if (!(m = dbus_message_new_method_call(
2393 "org.freedesktop.systemd1",
2394 "/org/freedesktop/systemd1",
2395 "org.freedesktop.systemd1.Manager",
2397 log_error("Could not allocate message.");
2402 if (!dbus_message_append_args(m,
2403 DBUS_TYPE_UINT32, &id,
2404 DBUS_TYPE_INVALID)) {
2405 log_error("Could not append arguments to message.");
2410 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2411 log_error("Failed to issue method call: %s", bus_error_message(&error));
2417 if (!dbus_message_get_args(reply, &error,
2418 DBUS_TYPE_OBJECT_PATH, &path,
2419 DBUS_TYPE_INVALID)) {
2420 log_error("Failed to parse reply: %s", bus_error_message(&error));
2425 if ((r = show_one(bus, path, show_properties, &new_line)) != 0)
2428 dbus_message_unref(m);
2429 dbus_message_unref(reply);
2435 dbus_message_unref(m);
2438 dbus_message_unref(reply);
2440 dbus_error_free(&error);
2445 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2447 DBusMessage *m = NULL, *reply = NULL;
2452 dbus_error_init(&error);
2454 log_debug("Got D-Bus request: %s.%s() on %s",
2455 dbus_message_get_interface(message),
2456 dbus_message_get_member(message),
2457 dbus_message_get_path(message));
2459 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2460 log_error("Warning! D-Bus connection terminated.");
2461 dbus_connection_close(connection);
2463 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2464 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2465 const char *id, *path;
2467 if (!dbus_message_get_args(message, &error,
2468 DBUS_TYPE_STRING, &id,
2469 DBUS_TYPE_OBJECT_PATH, &path,
2471 log_error("Failed to parse message: %s", bus_error_message(&error));
2472 else if (streq(dbus_message_get_member(message), "UnitNew"))
2473 printf("Unit %s added.\n", id);
2475 printf("Unit %s removed.\n", id);
2477 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2478 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2482 if (!dbus_message_get_args(message, &error,
2483 DBUS_TYPE_UINT32, &id,
2484 DBUS_TYPE_OBJECT_PATH, &path,
2486 log_error("Failed to parse message: %s", bus_error_message(&error));
2487 else if (streq(dbus_message_get_member(message), "JobNew"))
2488 printf("Job %u added.\n", id);
2490 printf("Job %u removed.\n", id);
2493 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2495 const char *path, *interface, *property = "Id";
2496 DBusMessageIter iter, sub;
2498 path = dbus_message_get_path(message);
2500 if (!dbus_message_get_args(message, &error,
2501 DBUS_TYPE_STRING, &interface,
2502 DBUS_TYPE_INVALID)) {
2503 log_error("Failed to parse message: %s", bus_error_message(&error));
2507 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2508 !streq(interface, "org.freedesktop.systemd1.Unit"))
2511 if (!(m = dbus_message_new_method_call(
2512 "org.freedesktop.systemd1",
2514 "org.freedesktop.DBus.Properties",
2516 log_error("Could not allocate message.");
2520 if (!dbus_message_append_args(m,
2521 DBUS_TYPE_STRING, &interface,
2522 DBUS_TYPE_STRING, &property,
2523 DBUS_TYPE_INVALID)) {
2524 log_error("Could not append arguments to message.");
2528 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2529 log_error("Failed to issue method call: %s", bus_error_message(&error));
2533 if (!dbus_message_iter_init(reply, &iter) ||
2534 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2535 log_error("Failed to parse reply.");
2539 dbus_message_iter_recurse(&iter, &sub);
2541 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2544 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2545 log_error("Failed to parse reply.");
2549 dbus_message_iter_get_basic(&sub, &id);
2550 printf("Unit %s changed.\n", id);
2554 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2555 log_error("Failed to parse reply.");
2559 dbus_message_iter_get_basic(&sub, &id);
2560 printf("Job %u changed.\n", id);
2566 dbus_message_unref(m);
2569 dbus_message_unref(reply);
2571 dbus_error_free(&error);
2572 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2576 dbus_message_unref(m);
2579 dbus_message_unref(reply);
2581 dbus_error_free(&error);
2582 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2585 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2586 DBusMessage *m = NULL, *reply = NULL;
2590 dbus_error_init(&error);
2593 dbus_bus_add_match(bus,
2595 "sender='org.freedesktop.systemd1',"
2596 "interface='org.freedesktop.systemd1.Manager',"
2597 "path='/org/freedesktop/systemd1'",
2600 if (dbus_error_is_set(&error)) {
2601 log_error("Failed to add match: %s", bus_error_message(&error));
2606 dbus_bus_add_match(bus,
2608 "sender='org.freedesktop.systemd1',"
2609 "interface='org.freedesktop.DBus.Properties',"
2610 "member='PropertiesChanged'",
2613 if (dbus_error_is_set(&error)) {
2614 log_error("Failed to add match: %s", bus_error_message(&error));
2620 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2621 log_error("Failed to add filter.");
2626 if (!(m = dbus_message_new_method_call(
2627 "org.freedesktop.systemd1",
2628 "/org/freedesktop/systemd1",
2629 "org.freedesktop.systemd1.Manager",
2631 log_error("Could not allocate message.");
2636 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2637 log_error("Failed to issue method call: %s", bus_error_message(&error));
2642 while (dbus_connection_read_write_dispatch(bus, -1))
2649 /* This is slightly dirty, since we don't undo the filter or the matches. */
2652 dbus_message_unref(m);
2655 dbus_message_unref(reply);
2657 dbus_error_free(&error);
2662 static int dump(DBusConnection *bus, char **args, unsigned n) {
2663 DBusMessage *m = NULL, *reply = NULL;
2668 dbus_error_init(&error);
2670 if (!(m = dbus_message_new_method_call(
2671 "org.freedesktop.systemd1",
2672 "/org/freedesktop/systemd1",
2673 "org.freedesktop.systemd1.Manager",
2675 log_error("Could not allocate message.");
2679 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2680 log_error("Failed to issue method call: %s", bus_error_message(&error));
2685 if (!dbus_message_get_args(reply, &error,
2686 DBUS_TYPE_STRING, &text,
2687 DBUS_TYPE_INVALID)) {
2688 log_error("Failed to parse reply: %s", bus_error_message(&error));
2693 fputs(text, stdout);
2699 dbus_message_unref(m);
2702 dbus_message_unref(reply);
2704 dbus_error_free(&error);
2709 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2710 DBusMessage *m = NULL, *reply = NULL;
2713 const char *name = "", *path, *id;
2714 dbus_bool_t cleanup = FALSE;
2715 DBusMessageIter iter, sub;
2717 *interface = "org.freedesktop.systemd1.Unit",
2720 dbus_error_init(&error);
2722 if (!(m = dbus_message_new_method_call(
2723 "org.freedesktop.systemd1",
2724 "/org/freedesktop/systemd1",
2725 "org.freedesktop.systemd1.Manager",
2726 "CreateSnapshot"))) {
2727 log_error("Could not allocate message.");
2734 if (!dbus_message_append_args(m,
2735 DBUS_TYPE_STRING, &name,
2736 DBUS_TYPE_BOOLEAN, &cleanup,
2737 DBUS_TYPE_INVALID)) {
2738 log_error("Could not append arguments to message.");
2743 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2744 log_error("Failed to issue method call: %s", bus_error_message(&error));
2749 if (!dbus_message_get_args(reply, &error,
2750 DBUS_TYPE_OBJECT_PATH, &path,
2751 DBUS_TYPE_INVALID)) {
2752 log_error("Failed to parse reply: %s", bus_error_message(&error));
2757 dbus_message_unref(m);
2758 if (!(m = dbus_message_new_method_call(
2759 "org.freedesktop.systemd1",
2761 "org.freedesktop.DBus.Properties",
2763 log_error("Could not allocate message.");
2767 if (!dbus_message_append_args(m,
2768 DBUS_TYPE_STRING, &interface,
2769 DBUS_TYPE_STRING, &property,
2770 DBUS_TYPE_INVALID)) {
2771 log_error("Could not append arguments to message.");
2776 dbus_message_unref(reply);
2777 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2778 log_error("Failed to issue method call: %s", bus_error_message(&error));
2783 if (!dbus_message_iter_init(reply, &iter) ||
2784 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2785 log_error("Failed to parse reply.");
2790 dbus_message_iter_recurse(&iter, &sub);
2792 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2793 log_error("Failed to parse reply.");
2798 dbus_message_iter_get_basic(&sub, &id);
2806 dbus_message_unref(m);
2809 dbus_message_unref(reply);
2811 dbus_error_free(&error);
2816 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2817 DBusMessage *m = NULL, *reply = NULL;
2825 dbus_error_init(&error);
2827 for (i = 1; i < n; i++) {
2828 const char *path = NULL;
2830 if (!(m = dbus_message_new_method_call(
2831 "org.freedesktop.systemd1",
2832 "/org/freedesktop/systemd1",
2833 "org.freedesktop.systemd1.Manager",
2835 log_error("Could not allocate message.");
2840 if (!dbus_message_append_args(m,
2841 DBUS_TYPE_STRING, &args[i],
2842 DBUS_TYPE_INVALID)) {
2843 log_error("Could not append arguments to message.");
2848 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2849 log_error("Failed to issue method call: %s", bus_error_message(&error));
2854 if (!dbus_message_get_args(reply, &error,
2855 DBUS_TYPE_OBJECT_PATH, &path,
2856 DBUS_TYPE_INVALID)) {
2857 log_error("Failed to parse reply: %s", bus_error_message(&error));
2862 dbus_message_unref(m);
2863 if (!(m = dbus_message_new_method_call(
2864 "org.freedesktop.systemd1",
2866 "org.freedesktop.systemd1.Snapshot",
2868 log_error("Could not allocate message.");
2873 dbus_message_unref(reply);
2874 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2875 log_error("Failed to issue method call: %s", bus_error_message(&error));
2880 dbus_message_unref(m);
2881 dbus_message_unref(reply);
2889 dbus_message_unref(m);
2892 dbus_message_unref(reply);
2894 dbus_error_free(&error);
2899 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2900 DBusMessage *m = NULL, *reply = NULL;
2905 dbus_error_init(&error);
2907 if (arg_action == ACTION_RELOAD)
2909 else if (arg_action == ACTION_REEXEC)
2910 method = "Reexecute";
2912 assert(arg_action == ACTION_SYSTEMCTL);
2915 streq(args[0], "clear-jobs") ||
2916 streq(args[0], "cancel") ? "ClearJobs" :
2917 streq(args[0], "daemon-reexec") ? "Reexecute" :
2918 streq(args[0], "reset-failed") ? "ResetFailed" :
2919 streq(args[0], "daemon-exit") ? "Exit" :
2923 if (!(m = dbus_message_new_method_call(
2924 "org.freedesktop.systemd1",
2925 "/org/freedesktop/systemd1",
2926 "org.freedesktop.systemd1.Manager",
2928 log_error("Could not allocate message.");
2932 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2934 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
2935 /* There's always a fallback possible for
2936 * legacy actions. */
2941 log_error("Failed to issue method call: %s", bus_error_message(&error));
2950 dbus_message_unref(m);
2953 dbus_message_unref(reply);
2955 dbus_error_free(&error);
2960 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
2961 DBusMessage *m = NULL, *reply = NULL;
2967 dbus_error_init(&error);
2970 return daemon_reload(bus, args, n);
2972 for (i = 1; i < n; i++) {
2974 if (!(m = dbus_message_new_method_call(
2975 "org.freedesktop.systemd1",
2976 "/org/freedesktop/systemd1",
2977 "org.freedesktop.systemd1.Manager",
2978 "ResetFailedUnit"))) {
2979 log_error("Could not allocate message.");
2984 if (!dbus_message_append_args(m,
2985 DBUS_TYPE_STRING, args + i,
2986 DBUS_TYPE_INVALID)) {
2987 log_error("Could not append arguments to message.");
2992 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2993 log_error("Failed to issue method call: %s", bus_error_message(&error));
2998 dbus_message_unref(m);
2999 dbus_message_unref(reply);
3007 dbus_message_unref(m);
3010 dbus_message_unref(reply);
3012 dbus_error_free(&error);
3017 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3018 DBusMessage *m = NULL, *reply = NULL;
3020 DBusMessageIter iter, sub, sub2;
3023 *interface = "org.freedesktop.systemd1.Manager",
3024 *property = "Environment";
3026 dbus_error_init(&error);
3028 if (!(m = dbus_message_new_method_call(
3029 "org.freedesktop.systemd1",
3030 "/org/freedesktop/systemd1",
3031 "org.freedesktop.DBus.Properties",
3033 log_error("Could not allocate message.");
3037 if (!dbus_message_append_args(m,
3038 DBUS_TYPE_STRING, &interface,
3039 DBUS_TYPE_STRING, &property,
3040 DBUS_TYPE_INVALID)) {
3041 log_error("Could not append arguments to message.");
3046 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3047 log_error("Failed to issue method call: %s", bus_error_message(&error));
3052 if (!dbus_message_iter_init(reply, &iter) ||
3053 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3054 log_error("Failed to parse reply.");
3059 dbus_message_iter_recurse(&iter, &sub);
3061 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3062 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3063 log_error("Failed to parse reply.");
3068 dbus_message_iter_recurse(&sub, &sub2);
3070 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3073 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3074 log_error("Failed to parse reply.");
3079 dbus_message_iter_get_basic(&sub2, &text);
3080 printf("%s\n", text);
3082 dbus_message_iter_next(&sub2);
3089 dbus_message_unref(m);
3092 dbus_message_unref(reply);
3094 dbus_error_free(&error);
3099 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3100 DBusMessage *m = NULL, *reply = NULL;
3104 DBusMessageIter iter, sub;
3107 dbus_error_init(&error);
3109 method = streq(args[0], "set-environment")
3111 : "UnsetEnvironment";
3113 if (!(m = dbus_message_new_method_call(
3114 "org.freedesktop.systemd1",
3115 "/org/freedesktop/systemd1",
3116 "org.freedesktop.systemd1.Manager",
3119 log_error("Could not allocate message.");
3123 dbus_message_iter_init_append(m, &iter);
3125 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3126 log_error("Could not append arguments to message.");
3131 for (i = 1; i < n; i++)
3132 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3133 log_error("Could not append arguments to message.");
3138 if (!dbus_message_iter_close_container(&iter, &sub)) {
3139 log_error("Could not append arguments to message.");
3144 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3145 log_error("Failed to issue method call: %s", bus_error_message(&error));
3154 dbus_message_unref(m);
3157 dbus_message_unref(reply);
3159 dbus_error_free(&error);
3172 static Hashmap *will_install = NULL, *have_installed = NULL;
3173 static Set *remove_symlinks_to = NULL;
3175 static void install_info_free(InstallInfo *i) {
3180 strv_free(i->aliases);
3181 strv_free(i->wanted_by);
3185 static void install_info_hashmap_free(Hashmap *m) {
3188 while ((i = hashmap_steal_first(m)))
3189 install_info_free(i);
3194 static bool unit_name_valid(const char *name) {
3196 /* This is a minimal version of unit_name_valid() from
3202 if (ignore_file(name))
3208 static int install_info_add(const char *name) {
3212 assert(will_install);
3214 if (!unit_name_valid(name))
3217 if (hashmap_get(have_installed, name) ||
3218 hashmap_get(will_install, name))
3221 if (!(i = new0(InstallInfo, 1))) {
3226 if (!(i->name = strdup(name))) {
3231 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3238 install_info_free(i);
3243 static int config_parse_also(
3244 const char *filename,
3246 const char *section,
3260 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3264 if (!(n = strndup(w, l)))
3267 r = install_info_add(n);
3277 static int mark_symlink_for_removal(const char *p) {
3282 assert(path_is_absolute(p));
3284 if (!remove_symlinks_to)
3287 if (!(n = strdup(p)))
3290 path_kill_slashes(n);
3292 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3294 return r == -EEXIST ? 0 : r;
3300 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3309 if (!(d = fdopendir(fd))) {
3310 close_nointr_nofail(fd);
3316 while ((de = readdir(d))) {
3317 bool is_dir = false, is_link = false;
3319 if (ignore_file(de->d_name))
3322 if (de->d_type == DT_LNK)
3324 else if (de->d_type == DT_DIR)
3326 else if (de->d_type == DT_UNKNOWN) {
3329 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3330 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3337 is_link = S_ISLNK(st.st_mode);
3338 is_dir = S_ISDIR(st.st_mode);
3346 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3347 log_error("Failed to open %s/%s: %m", root, de->d_name);
3354 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3355 log_error("Failed to allocate directory string.");
3356 close_nointr_nofail(nfd);
3361 /* This will close nfd, regardless whether it succeeds or not */
3362 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3368 } else if (is_link) {
3372 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3373 log_error("Failed to allocate symlink string.");
3378 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3379 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3387 if ((c = canonicalize_file_name(dest))) {
3388 /* This might fail if the destination
3389 * is already removed */
3395 path_kill_slashes(dest);
3396 if (set_get(remove_symlinks_to, dest)) {
3399 log_info("rm '%s'", p);
3401 if (unlink(p) < 0) {
3402 log_error("Cannot unlink symlink %s: %m", p);
3407 rmdir_parents(p, config_path);
3408 path_kill_slashes(p);
3410 if (!set_get(remove_symlinks_to, p)) {
3412 if ((r = mark_symlink_for_removal(p)) < 0) {
3431 static int remove_marked_symlinks(const char *config_path) {
3435 assert(config_path);
3437 if (set_size(remove_symlinks_to) <= 0)
3440 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3447 if ((cfd = dup(fd)) < 0) {
3452 /* This takes possession of cfd and closes it */
3453 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3459 close_nointr_nofail(fd);
3464 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3471 if (streq(verb, "enable")) {
3474 mkdir_parents(new_path, 0755);
3476 if (symlink(old_path, new_path) >= 0) {
3479 log_info("ln -s '%s' '%s'", old_path, new_path);
3484 if (errno != EEXIST) {
3485 log_error("Cannot link %s to %s: %m", old_path, new_path);
3489 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3491 if (errno == EINVAL) {
3492 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3496 log_error("readlink() failed: %s", strerror(-r));
3500 if (streq(dest, old_path)) {
3506 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3515 log_info("ln -s '%s' '%s'", old_path, new_path);
3517 if (symlink(old_path, new_path) >= 0)
3520 log_error("Cannot link %s to %s: %m", old_path, new_path);
3523 } else if (streq(verb, "disable")) {
3526 if ((r = mark_symlink_for_removal(old_path)) < 0)
3529 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3530 if (errno == ENOENT)
3533 if (errno == EINVAL) {
3534 log_warning("File %s not a symlink, ignoring.", old_path);
3538 log_error("readlink() failed: %s", strerror(-r));
3542 if (!streq(dest, old_path)) {
3543 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3550 if ((r = mark_symlink_for_removal(new_path)) < 0)
3554 log_info("rm '%s'", new_path);
3556 if (unlink(new_path) >= 0)
3559 log_error("Cannot unlink %s: %m", new_path);
3562 } else if (streq(verb, "is-enabled")) {
3565 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3567 if (errno == ENOENT || errno == EINVAL)
3570 log_error("readlink() failed: %s", strerror(-r));
3574 if (streq(dest, old_path)) {
3582 assert_not_reached("Unknown action.");
3585 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3587 char *alias_path = NULL;
3592 assert(config_path);
3594 STRV_FOREACH(s, i->aliases) {
3596 if (!unit_name_valid(*s)) {
3597 log_error("Invalid name %s.", *s);
3603 if (!(alias_path = path_make_absolute(*s, config_path))) {
3604 log_error("Out of memory");
3609 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3612 if (streq(verb, "disable"))
3613 rmdir_parents(alias_path, config_path);
3624 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3626 char *alias_path = NULL;
3631 assert(config_path);
3633 STRV_FOREACH(s, i->wanted_by) {
3634 if (!unit_name_valid(*s)) {
3635 log_error("Invalid name %s.", *s);
3643 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3644 log_error("Out of memory");
3649 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3652 if (streq(verb, "disable"))
3653 rmdir_parents(alias_path, config_path);
3664 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3666 const ConfigItem items[] = {
3667 { "Alias", config_parse_strv, &i->aliases, "Install" },
3668 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3669 { "Also", config_parse_also, NULL, "Install" },
3671 { NULL, NULL, NULL, NULL }
3675 char *filename = NULL;
3682 STRV_FOREACH(p, paths->unit_path) {
3685 if (!(filename = path_make_absolute(i->name, *p))) {
3686 log_error("Out of memory");
3690 /* Ensure that we don't follow symlinks */
3691 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3692 if ((f = fdopen(fd, "re")))
3695 if (errno == ELOOP) {
3696 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3701 if (errno != ENOENT) {
3702 log_error("Failed to open %s: %m", filename);
3712 log_error("Couldn't find %s.", i->name);
3718 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3725 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3728 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3731 if ((r = mark_symlink_for_removal(filename)) < 0)
3734 if ((r = remove_marked_symlinks(config_path)) < 0)
3740 static char *get_config_path(void) {
3742 if (arg_session && arg_global)
3743 return strdup(SESSION_CONFIG_UNIT_PATH);
3748 if (session_config_home(&p) < 0)
3754 return strdup(SYSTEM_CONFIG_UNIT_PATH);
3757 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3761 char *config_path = NULL;
3764 const char *verb = args[0];
3766 dbus_error_init(&error);
3769 if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3770 log_error("Failed to determine lookup paths: %s", strerror(-r));
3774 if (!(config_path = get_config_path())) {
3775 log_error("Failed to determine config path");
3780 will_install = hashmap_new(string_hash_func, string_compare_func);
3781 have_installed = hashmap_new(string_hash_func, string_compare_func);
3783 if (!will_install || !have_installed) {
3784 log_error("Failed to allocate unit sets.");
3789 if (!arg_defaults && streq(verb, "disable"))
3790 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3791 log_error("Failed to allocate symlink sets.");
3796 for (j = 1; j < n; j++)
3797 if ((r = install_info_add(args[j])) < 0)
3800 while ((i = hashmap_first(will_install))) {
3803 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3805 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3813 /* In test mode and found something */
3819 if (streq(verb, "is-enabled"))
3820 r = r > 0 ? 0 : -ENOENT;
3822 /* Don't try to reload anything if the user asked us to not do this */
3824 /* Don't try to reload anything when updating a unit globally */
3826 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3827 (arg_session || sd_booted() > 0) &&
3828 /* Don't try to reload anything if we are running in a chroot environment */
3829 (arg_session || running_in_chroot() <= 0) ) {
3832 if ((q = daemon_reload(bus, args, n)) < 0)
3837 install_info_hashmap_free(will_install);
3838 install_info_hashmap_free(have_installed);
3840 set_free_free(remove_symlinks_to);
3842 lookup_paths_free(&paths);
3849 static int systemctl_help(void) {
3851 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3852 "Send control commands to or query the systemd manager.\n\n"
3853 " -h --help Show this help\n"
3854 " --version Show package version\n"
3855 " -t --type=TYPE List only units of a particular type\n"
3856 " -p --property=NAME Show only properties by this name\n"
3857 " -a --all Show all units/properties, including dead/empty ones\n"
3858 " --full Don't ellipsize unit names on output\n"
3859 " --fail When queueing a new job, fail if conflicting jobs are\n"
3861 " -q --quiet Suppress output\n"
3862 " --no-block Do not wait until operation finished\n"
3863 " --system Connect to system bus\n"
3864 " --session Connect to session bus\n"
3865 " --order When generating graph for dot, show only order\n"
3866 " --require When generating graph for dot, show only requirement\n"
3867 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3868 " --global Enable/disable unit files globally\n"
3869 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3871 " --force When enabling unit files, override existing symlinks\n"
3872 " --defaults When disabling unit files, remove default symlinks only\n\n"
3874 " list-units List units\n"
3875 " start [NAME...] Start (activate) one or more units\n"
3876 " stop [NAME...] Stop (deactivate) one or more units\n"
3877 " reload [NAME...] Reload one or more units\n"
3878 " restart [NAME...] Start or restart one or more units\n"
3879 " try-restart [NAME...] Restart one or more units if active\n"
3880 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3881 " otherwise start or restart\n"
3882 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3883 " otherwise restart if active\n"
3884 " isolate [NAME] Start one unit and stop all others\n"
3885 " is-active [NAME...] Check whether units are active\n"
3886 " status [NAME...|PID...] Show runtime status of one or more units\n"
3887 " show [NAME...|JOB...] Show properties of one or more\n"
3888 " units/jobs or the manager\n"
3889 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
3891 " enable [NAME...] Enable one or more unit files\n"
3892 " disable [NAME...] Disable one or more unit files\n"
3893 " is-enabled [NAME...] Check whether unit files are enabled\n"
3894 " load [NAME...] Load one or more units\n"
3895 " list-jobs List jobs\n"
3896 " cancel [JOB...] Cancel all, one, or more jobs\n"
3897 " monitor Monitor unit/job changes\n"
3898 " dump Dump server status\n"
3899 " dot Dump dependency graph for dot(1)\n"
3900 " snapshot [NAME] Create a snapshot\n"
3901 " delete [NAME...] Remove one or more snapshots\n"
3902 " daemon-reload Reload systemd manager configuration\n"
3903 " daemon-reexec Reexecute systemd manager\n"
3904 " daemon-exit Ask the systemd manager to quit\n"
3905 " show-environment Dump environment\n"
3906 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3907 " unset-environment [NAME...] Unset one or more environment variables\n"
3908 " halt Shut down and halt the system\n"
3909 " poweroff Shut down and power-off the system\n"
3910 " reboot Shut down and reboot the system\n"
3911 " rescue Enter system rescue mode\n"
3912 " emergency Enter system emergency mode\n"
3913 " default Enter system default mode\n",
3914 program_invocation_short_name);
3919 static int halt_help(void) {
3921 printf("%s [OPTIONS...]\n\n"
3922 "%s the system.\n\n"
3923 " --help Show this help\n"
3924 " --halt Halt the machine\n"
3925 " -p --poweroff Switch off the machine\n"
3926 " --reboot Reboot the machine\n"
3927 " -f --force Force immediate halt/power-off/reboot\n"
3928 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3929 " -d --no-wtmp Don't write wtmp record\n"
3930 " -n --no-sync Don't sync before halt/power-off/reboot\n"
3931 " --no-wall Don't send wall message before halt/power-off/reboot\n",
3932 program_invocation_short_name,
3933 arg_action == ACTION_REBOOT ? "Reboot" :
3934 arg_action == ACTION_POWEROFF ? "Power off" :
3940 static int shutdown_help(void) {
3942 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3943 "Shut down the system.\n\n"
3944 " --help Show this help\n"
3945 " -H --halt Halt the machine\n"
3946 " -P --poweroff Power-off the machine\n"
3947 " -r --reboot Reboot the machine\n"
3948 " -h Equivalent to --poweroff, overriden by --halt\n"
3949 " -k Don't halt/power-off/reboot, just send warnings\n"
3950 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3951 " -c Cancel a pending shutdown\n",
3952 program_invocation_short_name);
3957 static int telinit_help(void) {
3959 printf("%s [OPTIONS...] {COMMAND}\n\n"
3960 "Send control commands to the init daemon.\n\n"
3961 " --help Show this help\n"
3962 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
3964 " 0 Power-off the machine\n"
3965 " 6 Reboot the machine\n"
3966 " 2, 3, 4, 5 Start runlevelX.target unit\n"
3967 " 1, s, S Enter rescue mode\n"
3968 " q, Q Reload init daemon configuration\n"
3969 " u, U Reexecute init daemon\n",
3970 program_invocation_short_name);
3975 static int runlevel_help(void) {
3977 printf("%s [OPTIONS...]\n\n"
3978 "Prints the previous and current runlevel of the init system.\n\n"
3979 " --help Show this help\n",
3980 program_invocation_short_name);
3985 static int systemctl_parse_argv(int argc, char *argv[]) {
4003 static const struct option options[] = {
4004 { "help", no_argument, NULL, 'h' },
4005 { "version", no_argument, NULL, ARG_VERSION },
4006 { "type", required_argument, NULL, 't' },
4007 { "property", required_argument, NULL, 'p' },
4008 { "all", no_argument, NULL, 'a' },
4009 { "full", no_argument, NULL, ARG_FULL },
4010 { "fail", no_argument, NULL, ARG_FAIL },
4011 { "session", no_argument, NULL, ARG_SESSION },
4012 { "system", no_argument, NULL, ARG_SYSTEM },
4013 { "global", no_argument, NULL, ARG_GLOBAL },
4014 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4015 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4016 { "quiet", no_argument, NULL, 'q' },
4017 { "order", no_argument, NULL, ARG_ORDER },
4018 { "require", no_argument, NULL, ARG_REQUIRE },
4019 { "force", no_argument, NULL, ARG_FORCE },
4020 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4021 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4022 { NULL, 0, NULL, 0 }
4030 while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
4039 puts(PACKAGE_STRING);
4041 puts(SYSTEMD_FEATURES);
4051 if (!(l = strv_append(arg_property, optarg)))
4054 strv_free(arg_property);
4057 /* If the user asked for a particular
4058 * property, show it to him, even if it is
4077 arg_session = false;
4081 arg_no_block = true;
4089 arg_dot = DOT_ORDER;
4093 arg_dot = DOT_REQUIRE;
4109 arg_no_reload = true;
4118 arg_defaults = true;
4125 log_error("Unknown option code %c", c);
4133 static int halt_parse_argv(int argc, char *argv[]) {
4142 static const struct option options[] = {
4143 { "help", no_argument, NULL, ARG_HELP },
4144 { "halt", no_argument, NULL, ARG_HALT },
4145 { "poweroff", no_argument, NULL, 'p' },
4146 { "reboot", no_argument, NULL, ARG_REBOOT },
4147 { "force", no_argument, NULL, 'f' },
4148 { "wtmp-only", no_argument, NULL, 'w' },
4149 { "no-wtmp", no_argument, NULL, 'd' },
4150 { "no-sync", no_argument, NULL, 'n' },
4151 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4152 { NULL, 0, NULL, 0 }
4160 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4161 if (runlevel == '0' || runlevel == '6')
4162 arg_immediate = true;
4164 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4172 arg_action = ACTION_HALT;
4176 if (arg_action != ACTION_REBOOT)
4177 arg_action = ACTION_POWEROFF;
4181 arg_action = ACTION_REBOOT;
4185 arg_immediate = true;
4206 /* Compatibility nops */
4213 log_error("Unknown option code %c", c);
4218 if (optind < argc) {
4219 log_error("Too many arguments.");
4226 static int parse_time_spec(const char *t, usec_t *_u) {
4230 if (streq(t, "now"))
4232 else if (t[0] == '+') {
4235 if (safe_atou64(t + 1, &u) < 0)
4238 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4247 hour = strtol(t, &e, 10);
4248 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4251 minute = strtol(e+1, &e, 10);
4252 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4255 n = now(CLOCK_REALTIME);
4256 s = (time_t) (n / USEC_PER_SEC);
4259 assert_se(localtime_r(&s, &tm));
4261 tm.tm_hour = (int) hour;
4262 tm.tm_min = (int) minute;
4265 assert_se(s = mktime(&tm));
4267 *_u = (usec_t) s * USEC_PER_SEC;
4270 *_u += USEC_PER_DAY;
4276 static int shutdown_parse_argv(int argc, char *argv[]) {
4283 static const struct option options[] = {
4284 { "help", no_argument, NULL, ARG_HELP },
4285 { "halt", no_argument, NULL, 'H' },
4286 { "poweroff", no_argument, NULL, 'P' },
4287 { "reboot", no_argument, NULL, 'r' },
4288 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4289 { NULL, 0, NULL, 0 }
4297 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4305 arg_action = ACTION_HALT;
4309 arg_action = ACTION_POWEROFF;
4313 arg_action = ACTION_REBOOT;
4317 if (arg_action != ACTION_HALT)
4318 arg_action = ACTION_POWEROFF;
4331 /* Compatibility nops */
4335 arg_action = ACTION_CANCEL_SHUTDOWN;
4342 log_error("Unknown option code %c", c);
4347 if (argc > optind) {
4348 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4349 log_error("Failed to parse time specification: %s", argv[optind]);
4353 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4355 /* We skip the time argument */
4356 if (argc > optind + 1)
4357 arg_wall = argv + optind + 1;
4364 static int telinit_parse_argv(int argc, char *argv[]) {
4371 static const struct option options[] = {
4372 { "help", no_argument, NULL, ARG_HELP },
4373 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4374 { NULL, 0, NULL, 0 }
4377 static const struct {
4381 { '0', ACTION_POWEROFF },
4382 { '6', ACTION_REBOOT },
4383 { '1', ACTION_RESCUE },
4384 { '2', ACTION_RUNLEVEL2 },
4385 { '3', ACTION_RUNLEVEL3 },
4386 { '4', ACTION_RUNLEVEL4 },
4387 { '5', ACTION_RUNLEVEL5 },
4388 { 's', ACTION_RESCUE },
4389 { 'S', ACTION_RESCUE },
4390 { 'q', ACTION_RELOAD },
4391 { 'Q', ACTION_RELOAD },
4392 { 'u', ACTION_REEXEC },
4393 { 'U', ACTION_REEXEC }
4402 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4417 log_error("Unknown option code %c", c);
4422 if (optind >= argc) {
4427 if (optind + 1 < argc) {
4428 log_error("Too many arguments.");
4432 if (strlen(argv[optind]) != 1) {
4433 log_error("Expected single character argument.");
4437 for (i = 0; i < ELEMENTSOF(table); i++)
4438 if (table[i].from == argv[optind][0])
4441 if (i >= ELEMENTSOF(table)) {
4442 log_error("Unknown command %s.", argv[optind]);
4446 arg_action = table[i].to;
4453 static int runlevel_parse_argv(int argc, char *argv[]) {
4459 static const struct option options[] = {
4460 { "help", no_argument, NULL, ARG_HELP },
4461 { NULL, 0, NULL, 0 }
4469 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4480 log_error("Unknown option code %c", c);
4485 if (optind < argc) {
4486 log_error("Too many arguments.");
4493 static int parse_argv(int argc, char *argv[]) {
4497 if (program_invocation_short_name) {
4499 if (strstr(program_invocation_short_name, "halt")) {
4500 arg_action = ACTION_HALT;
4501 return halt_parse_argv(argc, argv);
4502 } else if (strstr(program_invocation_short_name, "poweroff")) {
4503 arg_action = ACTION_POWEROFF;
4504 return halt_parse_argv(argc, argv);
4505 } else if (strstr(program_invocation_short_name, "reboot")) {
4506 arg_action = ACTION_REBOOT;
4507 return halt_parse_argv(argc, argv);
4508 } else if (strstr(program_invocation_short_name, "shutdown")) {
4509 arg_action = ACTION_POWEROFF;
4510 return shutdown_parse_argv(argc, argv);
4511 } else if (strstr(program_invocation_short_name, "init")) {
4513 if (sd_booted() > 0) {
4514 arg_action = ACTION_INVALID;
4515 return telinit_parse_argv(argc, argv);
4517 /* Hmm, so some other init system is
4518 * running, we need to forward this
4519 * request to it. For now we simply
4520 * guess that it is Upstart. */
4522 execv("/lib/upstart/telinit", argv);
4524 log_error("Couldn't find an alternative telinit implementation to spawn.");
4528 } else if (strstr(program_invocation_short_name, "runlevel")) {
4529 arg_action = ACTION_RUNLEVEL;
4530 return runlevel_parse_argv(argc, argv);
4534 arg_action = ACTION_SYSTEMCTL;
4535 return systemctl_parse_argv(argc, argv);
4538 static int action_to_runlevel(void) {
4540 static const char table[_ACTION_MAX] = {
4541 [ACTION_HALT] = '0',
4542 [ACTION_POWEROFF] = '0',
4543 [ACTION_REBOOT] = '6',
4544 [ACTION_RUNLEVEL2] = '2',
4545 [ACTION_RUNLEVEL3] = '3',
4546 [ACTION_RUNLEVEL4] = '4',
4547 [ACTION_RUNLEVEL5] = '5',
4548 [ACTION_RESCUE] = '1'
4551 assert(arg_action < _ACTION_MAX);
4553 return table[arg_action];
4556 static int talk_upstart(void) {
4557 DBusMessage *m = NULL, *reply = NULL;
4559 int previous, rl, r;
4561 env1_buf[] = "RUNLEVEL=X",
4562 env2_buf[] = "PREVLEVEL=X";
4563 char *env1 = env1_buf, *env2 = env2_buf;
4564 const char *emit = "runlevel";
4565 dbus_bool_t b_false = FALSE;
4566 DBusMessageIter iter, sub;
4567 DBusConnection *bus;
4569 dbus_error_init(&error);
4571 if (!(rl = action_to_runlevel()))
4574 if (utmp_get_runlevel(&previous, NULL) < 0)
4577 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4578 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4583 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4588 if ((r = bus_check_peercred(bus)) < 0) {
4589 log_error("Failed to verify owner of bus.");
4593 if (!(m = dbus_message_new_method_call(
4594 "com.ubuntu.Upstart",
4595 "/com/ubuntu/Upstart",
4596 "com.ubuntu.Upstart0_6",
4599 log_error("Could not allocate message.");
4604 dbus_message_iter_init_append(m, &iter);
4606 env1_buf[sizeof(env1_buf)-2] = rl;
4607 env2_buf[sizeof(env2_buf)-2] = previous;
4609 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4610 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4611 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4612 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4613 !dbus_message_iter_close_container(&iter, &sub) ||
4614 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4615 log_error("Could not append arguments to message.");
4620 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4622 if (error_is_no_service(&error)) {
4627 log_error("Failed to issue method call: %s", bus_error_message(&error));
4636 dbus_message_unref(m);
4639 dbus_message_unref(reply);
4642 dbus_connection_flush(bus);
4643 dbus_connection_close(bus);
4644 dbus_connection_unref(bus);
4647 dbus_error_free(&error);
4652 static int talk_initctl(void) {
4653 struct init_request request;
4657 if (!(rl = action_to_runlevel()))
4661 request.magic = INIT_MAGIC;
4662 request.sleeptime = 0;
4663 request.cmd = INIT_CMD_RUNLVL;
4664 request.runlevel = rl;
4666 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4668 if (errno == ENOENT)
4671 log_error("Failed to open "INIT_FIFO": %m");
4676 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4677 close_nointr_nofail(fd);
4680 log_error("Failed to write to "INIT_FIFO": %m");
4681 return errno ? -errno : -EIO;
4687 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4689 static const struct {
4697 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4699 { "list-units", LESS, 1, list_units },
4700 { "list-jobs", EQUAL, 1, list_jobs },
4701 { "clear-jobs", EQUAL, 1, daemon_reload },
4702 { "load", MORE, 2, load_unit },
4703 { "cancel", MORE, 2, cancel_job },
4704 { "start", MORE, 2, start_unit },
4705 { "stop", MORE, 2, start_unit },
4706 { "reload", MORE, 2, start_unit },
4707 { "restart", MORE, 2, start_unit },
4708 { "try-restart", MORE, 2, start_unit },
4709 { "reload-or-restart", MORE, 2, start_unit },
4710 { "reload-or-try-restart", MORE, 2, start_unit },
4711 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4712 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4713 { "isolate", EQUAL, 2, start_unit },
4714 { "is-active", MORE, 2, check_unit },
4715 { "check", MORE, 2, check_unit },
4716 { "show", MORE, 1, show },
4717 { "status", MORE, 2, show },
4718 { "monitor", EQUAL, 1, monitor },
4719 { "dump", EQUAL, 1, dump },
4720 { "dot", EQUAL, 1, dot },
4721 { "snapshot", LESS, 2, snapshot },
4722 { "delete", MORE, 2, delete_snapshot },
4723 { "daemon-reload", EQUAL, 1, daemon_reload },
4724 { "daemon-reexec", EQUAL, 1, daemon_reload },
4725 { "daemon-exit", EQUAL, 1, daemon_reload },
4726 { "show-environment", EQUAL, 1, show_enviroment },
4727 { "set-environment", MORE, 2, set_environment },
4728 { "unset-environment", MORE, 2, set_environment },
4729 { "halt", EQUAL, 1, start_special },
4730 { "poweroff", EQUAL, 1, start_special },
4731 { "reboot", EQUAL, 1, start_special },
4732 { "default", EQUAL, 1, start_special },
4733 { "rescue", EQUAL, 1, start_special },
4734 { "emergency", EQUAL, 1, start_special },
4735 { "reset-failed", MORE, 1, reset_failed },
4736 { "enable", MORE, 2, enable_unit },
4737 { "disable", MORE, 2, enable_unit },
4738 { "is-enabled", MORE, 2, enable_unit }
4748 left = argc - optind;
4751 /* Special rule: no arguments means "list-units" */
4754 if (streq(argv[optind], "help")) {
4759 for (i = 0; i < ELEMENTSOF(verbs); i++)
4760 if (streq(argv[optind], verbs[i].verb))
4763 if (i >= ELEMENTSOF(verbs)) {
4764 log_error("Unknown operation %s", argv[optind]);
4769 switch (verbs[i].argc_cmp) {
4772 if (left != verbs[i].argc) {
4773 log_error("Invalid number of arguments.");
4780 if (left < verbs[i].argc) {
4781 log_error("Too few arguments.");
4788 if (left > verbs[i].argc) {
4789 log_error("Too many arguments.");
4796 assert_not_reached("Unknown comparison operator.");
4799 /* Require a bus connection for all operations but
4801 if (!streq(verbs[i].verb, "enable") &&
4802 !streq(verbs[i].verb, "disable") &&
4804 log_error("Failed to get D-Bus connection: %s", error->message);
4808 return verbs[i].dispatch(bus, argv + optind, left);
4811 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
4813 struct msghdr msghdr;
4815 union sockaddr_union sockaddr;
4816 struct shutdownd_command c;
4824 strncpy(c.wall_message, message, sizeof(c.wall_message));
4826 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4830 sockaddr.sa.sa_family = AF_UNIX;
4831 sockaddr.un.sun_path[0] = 0;
4832 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
4835 iovec.iov_base = (char*) &c;
4836 iovec.iov_len = sizeof(c);
4839 msghdr.msg_name = &sockaddr;
4840 msghdr.msg_namelen = sizeof(sa_family_t) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
4842 msghdr.msg_iov = &iovec;
4843 msghdr.msg_iovlen = 1;
4845 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
4846 close_nointr_nofail(fd);
4850 close_nointr_nofail(fd);
4854 static int reload_with_fallback(DBusConnection *bus) {
4857 /* First, try systemd via D-Bus. */
4858 if (daemon_reload(bus, NULL, 0) > 0)
4862 /* Nothing else worked, so let's try signals */
4863 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
4865 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
4866 log_error("kill() failed: %m");
4873 static int start_with_fallback(DBusConnection *bus) {
4876 /* First, try systemd via D-Bus. */
4877 if (start_unit(bus, NULL, 0) >= 0)
4881 /* Hmm, talking to systemd via D-Bus didn't work. Then
4882 * let's try to talk to Upstart via D-Bus. */
4883 if (talk_upstart() > 0)
4886 /* Nothing else worked, so let's try
4888 if (talk_initctl() > 0)
4891 log_error("Failed to talk to init daemon.");
4895 warn_wall(arg_action);
4899 static int halt_main(DBusConnection *bus) {
4902 if (geteuid() != 0) {
4903 log_error("Must be root.");
4909 char date[FORMAT_TIMESTAMP_MAX];
4911 m = strv_join(arg_wall, " ");
4912 r = send_shutdownd(arg_when,
4913 arg_action == ACTION_HALT ? 'H' :
4914 arg_action == ACTION_POWEROFF ? 'P' :
4921 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
4923 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
4924 format_timestamp(date, sizeof(date), arg_when));
4929 if (!arg_dry && !arg_immediate)
4930 return start_with_fallback(bus);
4933 if (sd_booted() > 0)
4934 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
4935 else if ((r = utmp_put_shutdown(0)) < 0)
4936 log_warning("Failed to write utmp record: %s", strerror(-r));
4945 /* Make sure C-A-D is handled by the kernel from this
4947 reboot(RB_ENABLE_CAD);
4949 switch (arg_action) {
4952 log_info("Halting.");
4953 reboot(RB_HALT_SYSTEM);
4956 case ACTION_POWEROFF:
4957 log_info("Powering off.");
4958 reboot(RB_POWER_OFF);
4962 log_info("Rebooting.");
4963 reboot(RB_AUTOBOOT);
4967 assert_not_reached("Unknown halt action.");
4970 /* We should never reach this. */
4974 static int runlevel_main(void) {
4975 int r, runlevel, previous;
4977 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
4978 printf("unknown\n");
4983 previous <= 0 ? 'N' : previous,
4984 runlevel <= 0 ? 'N' : runlevel);
4989 int main(int argc, char*argv[]) {
4990 int r, retval = EXIT_FAILURE;
4991 DBusConnection *bus = NULL;
4994 dbus_error_init(&error);
4996 log_parse_environment();
4999 if ((r = parse_argv(argc, argv)) < 0)
5002 retval = EXIT_SUCCESS;
5006 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5007 * let's shortcut this */
5008 if (arg_action == ACTION_RUNLEVEL) {
5009 r = runlevel_main();
5010 retval = r < 0 ? EXIT_FAILURE : r;
5014 bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5016 switch (arg_action) {
5018 case ACTION_SYSTEMCTL:
5019 r = systemctl_main(bus, argc, argv, &error);
5023 case ACTION_POWEROFF:
5028 case ACTION_RUNLEVEL2:
5029 case ACTION_RUNLEVEL3:
5030 case ACTION_RUNLEVEL4:
5031 case ACTION_RUNLEVEL5:
5033 case ACTION_EMERGENCY:
5034 case ACTION_DEFAULT:
5035 r = start_with_fallback(bus);
5040 r = reload_with_fallback(bus);
5043 case ACTION_CANCEL_SHUTDOWN:
5044 r = send_shutdownd(0, 0, false, NULL);
5047 case ACTION_INVALID:
5048 case ACTION_RUNLEVEL:
5050 assert_not_reached("Unknown action");
5053 retval = r < 0 ? EXIT_FAILURE : r;
5058 dbus_connection_flush(bus);
5059 dbus_connection_close(bus);
5060 dbus_connection_unref(bus);
5063 dbus_error_free(&error);
5067 strv_free(arg_property);