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"
55 static const char *arg_type = NULL;
56 static char **arg_property = NULL;
57 static bool arg_all = false;
58 static bool arg_fail = false;
59 static bool arg_session = false;
60 static bool arg_global = false;
61 static bool arg_immediate = false;
62 static bool arg_no_block = false;
63 static bool arg_no_wtmp = false;
64 static bool arg_no_sync = false;
65 static bool arg_no_wall = false;
66 static bool arg_no_reload = false;
67 static bool arg_dry = false;
68 static bool arg_quiet = false;
69 static bool arg_full = false;
70 static bool arg_force = false;
71 static bool arg_defaults = false;
72 static bool arg_sysv_compat = false; /* this is undocumented, and
73 * exists simply to make
74 * implementation of SysV
75 * compatible shell glue
77 static char **arg_wall = NULL;
78 static usec_t arg_when = 0;
95 ACTION_CANCEL_SHUTDOWN,
97 } arg_action = ACTION_SYSTEMCTL;
104 static bool private_bus = false;
106 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
108 static bool on_tty(void) {
111 if (_unlikely_(t < 0))
112 t = isatty(STDOUT_FILENO) > 0;
117 static const char *ansi_highlight(bool b) {
122 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
125 static const char *ansi_highlight_green(bool b) {
130 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
133 static bool error_is_no_service(DBusError *error) {
137 if (!dbus_error_is_set(error))
140 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
143 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
146 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
149 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
154 if (dbus_message_iter_get_arg_type(iter) != type)
157 dbus_message_iter_get_basic(iter, data);
159 if (!dbus_message_iter_next(iter) != !next)
165 static void warn_wall(enum action action) {
166 static const char *table[_ACTION_MAX] = {
167 [ACTION_HALT] = "The system is going down for system halt NOW!",
168 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
169 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
170 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
171 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
180 if (!(p = strv_join(arg_wall, " "))) {
181 log_error("Failed to join strings.");
197 utmp_wall(table[action]);
202 const char *description;
203 const char *load_state;
204 const char *active_state;
205 const char *sub_state;
206 const char *following;
207 const char *unit_path;
209 const char *job_type;
210 const char *job_path;
213 static int compare_unit_info(const void *a, const void *b) {
215 const struct unit_info *u = a, *v = b;
217 d1 = strrchr(u->id, '.');
218 d2 = strrchr(v->id, '.');
223 if ((r = strcasecmp(d1, d2)) != 0)
227 return strcasecmp(u->id, v->id);
230 static int list_units(DBusConnection *bus, char **args, unsigned n) {
231 DBusMessage *m = NULL, *reply = NULL;
234 DBusMessageIter iter, sub, sub2;
235 unsigned c = 0, k, n_units = 0;
236 struct unit_info *unit_infos = NULL;
238 dbus_error_init(&error);
242 if (!(m = dbus_message_new_method_call(
243 "org.freedesktop.systemd1",
244 "/org/freedesktop/systemd1",
245 "org.freedesktop.systemd1.Manager",
247 log_error("Could not allocate message.");
251 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
252 log_error("Failed to issue method call: %s", bus_error_message(&error));
257 if (!dbus_message_iter_init(reply, &iter) ||
258 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
259 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
260 log_error("Failed to parse reply.");
265 dbus_message_iter_recurse(&iter, &sub);
267 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
270 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
271 log_error("Failed to parse reply.");
279 n_units = MAX(2*c, 16);
280 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
283 log_error("Failed to allocate unit array.");
293 dbus_message_iter_recurse(&sub, &sub2);
295 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
296 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
297 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
298 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
299 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
300 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
301 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
302 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
303 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
304 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
305 log_error("Failed to parse reply.");
310 dbus_message_iter_next(&sub);
314 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
316 if (isatty(STDOUT_FILENO))
317 printf("%-45s %-6s %-12s %-12s %-15s %s\n", "UNIT", "LOAD", "ACTIVE", "SUB", "JOB", "DESCRIPTION");
319 for (k = 0; k < c; k++) {
321 struct unit_info *u = unit_infos+k;
323 if ((!arg_type || ((dot = strrchr(u->id, '.')) &&
324 streq(dot+1, arg_type))) &&
325 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0)) {
328 const char *on, *off;
330 if (streq(u->active_state, "maintenance")) {
331 on = ansi_highlight(true);
332 off = ansi_highlight(false);
336 e = arg_full ? NULL : ellipsize(u->id, 45, 33);
337 printf("%-45s %-6s %s%-12s %-12s%s%n", e ? e : u->id, u->load_state, on, u->active_state, u->sub_state, off, &a);
340 a -= strlen(on) + strlen(off);
343 printf(" => %-12s%n", u->job_type, &b);
347 if (a + b + 2 < columns()) {
351 printf(" %.*s", columns() - a - b - 2, u->description);
358 if (isatty(STDOUT_FILENO)) {
360 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
361 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
362 "SUB = The low-level unit activation state, values depend on unit type.\n"
363 "JOB = Pending job for the unit.\n");
366 printf("\n%u units listed.\n", c);
368 printf("\n%u units listed. Pass --all to see inactive units, too.\n", c);
375 dbus_message_unref(m);
378 dbus_message_unref(reply);
382 dbus_error_free(&error);
387 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
388 static const char * const colors[] = {
389 "Requires", "[color=\"black\"]",
390 "RequiresOverridable", "[color=\"black\"]",
391 "Requisite", "[color=\"darkblue\"]",
392 "RequisiteOverridable", "[color=\"darkblue\"]",
393 "Wants", "[color=\"darkgrey\"]",
394 "Conflicts", "[color=\"red\"]",
395 "ConflictedBy", "[color=\"red\"]",
396 "After", "[color=\"green\"]"
399 const char *c = NULL;
406 for (i = 0; i < ELEMENTSOF(colors); i += 2)
407 if (streq(colors[i], prop)) {
415 if (arg_dot != DOT_ALL)
416 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
419 switch (dbus_message_iter_get_arg_type(iter)) {
421 case DBUS_TYPE_ARRAY:
423 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
426 dbus_message_iter_recurse(iter, &sub);
428 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
431 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
432 dbus_message_iter_get_basic(&sub, &s);
433 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
435 dbus_message_iter_next(&sub);
445 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
446 DBusMessage *m = NULL, *reply = NULL;
447 const char *interface = "org.freedesktop.systemd1.Unit";
450 DBusMessageIter iter, sub, sub2, sub3;
455 dbus_error_init(&error);
457 if (!(m = dbus_message_new_method_call(
458 "org.freedesktop.systemd1",
460 "org.freedesktop.DBus.Properties",
462 log_error("Could not allocate message.");
467 if (!dbus_message_append_args(m,
468 DBUS_TYPE_STRING, &interface,
469 DBUS_TYPE_INVALID)) {
470 log_error("Could not append arguments to message.");
475 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
476 log_error("Failed to issue method call: %s", bus_error_message(&error));
481 if (!dbus_message_iter_init(reply, &iter) ||
482 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
483 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
484 log_error("Failed to parse reply.");
489 dbus_message_iter_recurse(&iter, &sub);
491 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
494 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
495 log_error("Failed to parse reply.");
500 dbus_message_iter_recurse(&sub, &sub2);
502 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
503 log_error("Failed to parse reply.");
508 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
509 log_error("Failed to parse reply.");
514 dbus_message_iter_recurse(&sub2, &sub3);
516 if (dot_one_property(name, prop, &sub3)) {
517 log_error("Failed to parse reply.");
522 dbus_message_iter_next(&sub);
529 dbus_message_unref(m);
532 dbus_message_unref(reply);
534 dbus_error_free(&error);
539 static int dot(DBusConnection *bus, char **args, unsigned n) {
540 DBusMessage *m = NULL, *reply = NULL;
543 DBusMessageIter iter, sub, sub2;
545 dbus_error_init(&error);
549 if (!(m = dbus_message_new_method_call(
550 "org.freedesktop.systemd1",
551 "/org/freedesktop/systemd1",
552 "org.freedesktop.systemd1.Manager",
554 log_error("Could not allocate message.");
558 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
559 log_error("Failed to issue method call: %s", bus_error_message(&error));
564 if (!dbus_message_iter_init(reply, &iter) ||
565 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
566 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
567 log_error("Failed to parse reply.");
572 printf("digraph systemd {\n");
574 dbus_message_iter_recurse(&iter, &sub);
575 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
576 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
578 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
579 log_error("Failed to parse reply.");
584 dbus_message_iter_recurse(&sub, &sub2);
586 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
587 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
588 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
589 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
590 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
591 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
592 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
593 log_error("Failed to parse reply.");
598 if ((r = dot_one(bus, id, unit_path)) < 0)
601 /* printf("\t\"%s\";\n", id); */
602 dbus_message_iter_next(&sub);
607 log_info(" Color legend: black = Requires\n"
608 " dark blue = Requisite\n"
609 " dark grey = Wants\n"
613 if (isatty(fileno(stdout)))
614 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
615 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
621 dbus_message_unref(m);
624 dbus_message_unref(reply);
626 dbus_error_free(&error);
631 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
632 DBusMessage *m = NULL, *reply = NULL;
635 DBusMessageIter iter, sub, sub2;
638 dbus_error_init(&error);
642 if (!(m = dbus_message_new_method_call(
643 "org.freedesktop.systemd1",
644 "/org/freedesktop/systemd1",
645 "org.freedesktop.systemd1.Manager",
647 log_error("Could not allocate message.");
651 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
652 log_error("Failed to issue method call: %s", bus_error_message(&error));
657 if (!dbus_message_iter_init(reply, &iter) ||
658 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
659 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
660 log_error("Failed to parse reply.");
665 dbus_message_iter_recurse(&iter, &sub);
667 printf("%4s %-45s %-17s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
669 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
670 const char *name, *type, *state, *job_path, *unit_path;
674 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
675 log_error("Failed to parse reply.");
680 dbus_message_iter_recurse(&sub, &sub2);
682 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
683 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
684 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
685 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
686 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
687 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
688 log_error("Failed to parse reply.");
693 e = arg_full ? NULL : ellipsize(name, 45, 33);
694 printf("%4u %-45s %-17s %-7s\n", id, e ? e : name, type, state);
699 dbus_message_iter_next(&sub);
702 printf("\n%u jobs listed.\n", k);
707 dbus_message_unref(m);
710 dbus_message_unref(reply);
712 dbus_error_free(&error);
717 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
718 DBusMessage *m = NULL, *reply = NULL;
723 dbus_error_init(&error);
728 for (i = 1; i < n; i++) {
730 if (!(m = dbus_message_new_method_call(
731 "org.freedesktop.systemd1",
732 "/org/freedesktop/systemd1",
733 "org.freedesktop.systemd1.Manager",
735 log_error("Could not allocate message.");
740 if (!dbus_message_append_args(m,
741 DBUS_TYPE_STRING, &args[i],
742 DBUS_TYPE_INVALID)) {
743 log_error("Could not append arguments to message.");
748 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
749 log_error("Failed to issue method call: %s", bus_error_message(&error));
754 dbus_message_unref(m);
755 dbus_message_unref(reply);
764 dbus_message_unref(m);
767 dbus_message_unref(reply);
769 dbus_error_free(&error);
774 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
775 DBusMessage *m = NULL, *reply = NULL;
780 dbus_error_init(&error);
786 return daemon_reload(bus, args, n);
788 for (i = 1; i < n; i++) {
792 if (!(m = dbus_message_new_method_call(
793 "org.freedesktop.systemd1",
794 "/org/freedesktop/systemd1",
795 "org.freedesktop.systemd1.Manager",
797 log_error("Could not allocate message.");
802 if ((r = safe_atou(args[i], &id)) < 0) {
803 log_error("Failed to parse job id: %s", strerror(-r));
807 assert_cc(sizeof(uint32_t) == sizeof(id));
808 if (!dbus_message_append_args(m,
809 DBUS_TYPE_UINT32, &id,
810 DBUS_TYPE_INVALID)) {
811 log_error("Could not append arguments to message.");
816 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
817 log_error("Failed to issue method call: %s", bus_error_message(&error));
822 if (!dbus_message_get_args(reply, &error,
823 DBUS_TYPE_OBJECT_PATH, &path,
824 DBUS_TYPE_INVALID)) {
825 log_error("Failed to parse reply: %s", bus_error_message(&error));
830 dbus_message_unref(m);
831 if (!(m = dbus_message_new_method_call(
832 "org.freedesktop.systemd1",
834 "org.freedesktop.systemd1.Job",
836 log_error("Could not allocate message.");
841 dbus_message_unref(reply);
842 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
843 log_error("Failed to issue method call: %s", bus_error_message(&error));
848 dbus_message_unref(m);
849 dbus_message_unref(reply);
857 dbus_message_unref(m);
860 dbus_message_unref(reply);
862 dbus_error_free(&error);
867 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
868 DBusMessage *m = NULL, *reply = NULL;
869 dbus_bool_t b = FALSE;
870 DBusMessageIter iter, sub;
872 *interface = "org.freedesktop.systemd1.Unit",
873 *property = "NeedDaemonReload",
876 /* We ignore all errors here, since this is used to show a warning only */
878 if (!(m = dbus_message_new_method_call(
879 "org.freedesktop.systemd1",
880 "/org/freedesktop/systemd1",
881 "org.freedesktop.systemd1.Manager",
885 if (!dbus_message_append_args(m,
886 DBUS_TYPE_STRING, &unit,
890 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
893 if (!dbus_message_get_args(reply, NULL,
894 DBUS_TYPE_OBJECT_PATH, &path,
898 dbus_message_unref(m);
899 if (!(m = dbus_message_new_method_call(
900 "org.freedesktop.systemd1",
902 "org.freedesktop.DBus.Properties",
906 if (!dbus_message_append_args(m,
907 DBUS_TYPE_STRING, &interface,
908 DBUS_TYPE_STRING, &property,
909 DBUS_TYPE_INVALID)) {
913 dbus_message_unref(reply);
914 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
917 if (!dbus_message_iter_init(reply, &iter) ||
918 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
921 dbus_message_iter_recurse(&iter, &sub);
923 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
926 dbus_message_iter_get_basic(&sub, &b);
930 dbus_message_unref(m);
933 dbus_message_unref(reply);
938 typedef struct WaitData {
943 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
951 dbus_error_init(&error);
953 log_debug("Got D-Bus request: %s.%s() on %s",
954 dbus_message_get_interface(message),
955 dbus_message_get_member(message),
956 dbus_message_get_path(message));
958 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
959 log_error("Warning! D-Bus connection terminated.");
960 dbus_connection_close(connection);
962 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
965 dbus_bool_t success = true;
967 if (!dbus_message_get_args(message, &error,
968 DBUS_TYPE_UINT32, &id,
969 DBUS_TYPE_OBJECT_PATH, &path,
970 DBUS_TYPE_BOOLEAN, &success,
972 log_error("Failed to parse message: %s", bus_error_message(&error));
976 if ((p = set_remove(d->set, (char*) path)))
984 dbus_error_free(&error);
985 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
988 static int enable_wait_for_jobs(DBusConnection *bus) {
996 dbus_error_init(&error);
997 dbus_bus_add_match(bus,
999 "sender='org.freedesktop.systemd1',"
1000 "interface='org.freedesktop.systemd1.Manager',"
1001 "member='JobRemoved',"
1002 "path='/org/freedesktop/systemd1'",
1005 if (dbus_error_is_set(&error)) {
1006 log_error("Failed to add match: %s", bus_error_message(&error));
1007 dbus_error_free(&error);
1011 /* This is slightly dirty, since we don't undo the match registrations. */
1015 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1026 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1027 log_error("Failed to add filter.");
1032 while (!set_isempty(s) &&
1033 dbus_connection_read_write_dispatch(bus, -1))
1036 if (!arg_quiet && d.failed)
1037 log_error("Job failed, see logs for details.");
1039 r = d.failed ? -EIO : 0;
1042 /* This is slightly dirty, since we don't undo the filter registration. */
1047 static int start_unit_one(
1048 DBusConnection *bus,
1054 DBusMessage *m = NULL, *reply = NULL;
1063 assert(arg_no_block || s);
1065 dbus_error_init(&error);
1067 if (!(m = dbus_message_new_method_call(
1068 "org.freedesktop.systemd1",
1069 "/org/freedesktop/systemd1",
1070 "org.freedesktop.systemd1.Manager",
1072 log_error("Could not allocate message.");
1077 if (!dbus_message_append_args(m,
1078 DBUS_TYPE_STRING, &name,
1079 DBUS_TYPE_STRING, &mode,
1080 DBUS_TYPE_INVALID)) {
1081 log_error("Could not append arguments to message.");
1086 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1088 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
1089 /* There's always a fallback possible for
1090 * legacy actions. */
1095 log_error("Failed to issue method call: %s", bus_error_message(&error));
1100 if (!dbus_message_get_args(reply, &error,
1101 DBUS_TYPE_OBJECT_PATH, &path,
1102 DBUS_TYPE_INVALID)) {
1103 log_error("Failed to parse reply: %s", bus_error_message(&error));
1108 if (need_daemon_reload(bus, name))
1109 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1110 arg_session ? "--session" : "--system");
1112 if (!arg_no_block) {
1115 if (!(p = strdup(path))) {
1116 log_error("Failed to duplicate path.");
1121 if ((r = set_put(s, p)) < 0) {
1123 log_error("Failed to add path to set.");
1132 dbus_message_unref(m);
1135 dbus_message_unref(reply);
1137 dbus_error_free(&error);
1142 static enum action verb_to_action(const char *verb) {
1143 if (streq(verb, "halt"))
1145 else if (streq(verb, "poweroff"))
1146 return ACTION_POWEROFF;
1147 else if (streq(verb, "reboot"))
1148 return ACTION_REBOOT;
1149 else if (streq(verb, "rescue"))
1150 return ACTION_RESCUE;
1151 else if (streq(verb, "emergency"))
1152 return ACTION_EMERGENCY;
1153 else if (streq(verb, "default"))
1154 return ACTION_DEFAULT;
1156 return ACTION_INVALID;
1159 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1161 static const char * const table[_ACTION_MAX] = {
1162 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1163 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1164 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1165 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1166 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1167 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1168 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1169 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1170 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1171 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET
1176 const char *method, *mode, *one_name;
1181 if (arg_action == ACTION_SYSTEMCTL) {
1183 streq(args[0], "stop") ? "StopUnit" :
1184 streq(args[0], "reload") ? "ReloadUnit" :
1185 streq(args[0], "restart") ? "RestartUnit" :
1186 streq(args[0], "try-restart") ? "TryRestartUnit" :
1187 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1188 streq(args[0], "reload-or-try-restart") ||
1189 streq(args[0], "force-reload") ||
1190 streq(args[0], "condrestart") ? "ReloadOrTryRestartUnit" :
1194 (streq(args[0], "isolate") ||
1195 streq(args[0], "rescue") ||
1196 streq(args[0], "emergency")) ? "isolate" :
1200 one_name = table[verb_to_action(args[0])];
1203 assert(arg_action < ELEMENTSOF(table));
1204 assert(table[arg_action]);
1206 method = "StartUnit";
1208 mode = (arg_action == ACTION_EMERGENCY ||
1209 arg_action == ACTION_RESCUE) ? "isolate" : "replace";
1211 one_name = table[arg_action];
1214 if (!arg_no_block) {
1215 if ((r = enable_wait_for_jobs(bus)) < 0) {
1216 log_error("Could not watch jobs: %s", strerror(-r));
1220 if (!(s = set_new(string_hash_func, string_compare_func))) {
1221 log_error("Failed to allocate set.");
1230 if ((r = start_unit_one(bus, method, one_name, mode, s)) <= 0)
1233 for (i = 1; i < n; i++)
1234 if ((r = start_unit_one(bus, method, args[i], mode, s)) < 0)
1239 if ((r = wait_for_jobs(bus, s)) < 0)
1251 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1257 r = start_unit(bus, args, n);
1260 warn_wall(verb_to_action(args[0]));
1265 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1266 DBusMessage *m = NULL, *reply = NULL;
1268 *interface = "org.freedesktop.systemd1.Unit",
1269 *property = "ActiveState";
1270 int r = -EADDRNOTAVAIL;
1277 dbus_error_init(&error);
1279 for (i = 1; i < n; i++) {
1280 const char *path = NULL;
1282 DBusMessageIter iter, sub;
1284 if (!(m = dbus_message_new_method_call(
1285 "org.freedesktop.systemd1",
1286 "/org/freedesktop/systemd1",
1287 "org.freedesktop.systemd1.Manager",
1289 log_error("Could not allocate message.");
1294 if (!dbus_message_append_args(m,
1295 DBUS_TYPE_STRING, &args[i],
1296 DBUS_TYPE_INVALID)) {
1297 log_error("Could not append arguments to message.");
1302 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1304 /* Hmm, cannot figure out anything about this unit... */
1308 dbus_error_free(&error);
1312 if (!dbus_message_get_args(reply, &error,
1313 DBUS_TYPE_OBJECT_PATH, &path,
1314 DBUS_TYPE_INVALID)) {
1315 log_error("Failed to parse reply: %s", bus_error_message(&error));
1320 dbus_message_unref(m);
1321 if (!(m = dbus_message_new_method_call(
1322 "org.freedesktop.systemd1",
1324 "org.freedesktop.DBus.Properties",
1326 log_error("Could not allocate message.");
1331 if (!dbus_message_append_args(m,
1332 DBUS_TYPE_STRING, &interface,
1333 DBUS_TYPE_STRING, &property,
1334 DBUS_TYPE_INVALID)) {
1335 log_error("Could not append arguments to message.");
1340 dbus_message_unref(reply);
1341 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1342 log_error("Failed to issue method call: %s", bus_error_message(&error));
1347 if (!dbus_message_iter_init(reply, &iter) ||
1348 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1349 log_error("Failed to parse reply.");
1354 dbus_message_iter_recurse(&iter, &sub);
1356 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1357 log_error("Failed to parse reply.");
1362 dbus_message_iter_get_basic(&sub, &state);
1367 if (streq(state, "active") || streq(state, "reloading"))
1370 dbus_message_unref(m);
1371 dbus_message_unref(reply);
1377 dbus_message_unref(m);
1380 dbus_message_unref(reply);
1382 dbus_error_free(&error);
1387 typedef struct ExecStatusInfo {
1393 usec_t start_timestamp;
1394 usec_t exit_timestamp;
1399 LIST_FIELDS(struct ExecStatusInfo, exec);
1402 static void exec_status_info_free(ExecStatusInfo *i) {
1410 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1411 uint64_t start_timestamp, exit_timestamp;
1412 DBusMessageIter sub2, sub3;
1416 int32_t code, status;
1422 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1425 dbus_message_iter_recurse(sub, &sub2);
1427 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1430 if (!(i->path = strdup(path)))
1433 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1434 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1438 dbus_message_iter_recurse(&sub2, &sub3);
1439 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1440 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1441 dbus_message_iter_next(&sub3);
1446 if (!(i->argv = new0(char*, n+1)))
1450 dbus_message_iter_recurse(&sub2, &sub3);
1451 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1454 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1455 dbus_message_iter_get_basic(&sub3, &s);
1456 dbus_message_iter_next(&sub3);
1458 if (!(i->argv[n++] = strdup(s)))
1462 if (!dbus_message_iter_next(&sub2) ||
1463 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1464 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1465 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1466 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1467 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1468 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1472 i->start_timestamp = (usec_t) start_timestamp;
1473 i->exit_timestamp = (usec_t) exit_timestamp;
1474 i->pid = (pid_t) pid;
1481 typedef struct UnitStatusInfo {
1483 const char *load_state;
1484 const char *active_state;
1485 const char *sub_state;
1487 const char *description;
1490 const char *default_control_group;
1492 usec_t inactive_exit_timestamp;
1493 usec_t active_enter_timestamp;
1494 usec_t active_exit_timestamp;
1495 usec_t inactive_enter_timestamp;
1497 bool need_daemon_reload;
1502 const char *status_text;
1506 usec_t start_timestamp;
1507 usec_t exit_timestamp;
1509 int exit_code, exit_status;
1512 unsigned n_accepted;
1513 unsigned n_connections;
1517 const char *sysfs_path;
1519 /* Mount, Automount */
1525 LIST_HEAD(ExecStatusInfo, exec);
1528 static void print_status_info(UnitStatusInfo *i) {
1530 const char *on, *off, *ss;
1532 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1533 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1537 /* This shows pretty information about a unit. See
1538 * print_property() for a low-level property printer */
1540 printf("%s", strna(i->id));
1542 if (i->description && !streq_ptr(i->id, i->description))
1543 printf(" - %s", i->description);
1547 if (streq_ptr(i->load_state, "failed")) {
1548 on = ansi_highlight(true);
1549 off = ansi_highlight(false);
1554 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1556 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1558 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1560 if (streq_ptr(i->active_state, "maintenance")) {
1561 on = ansi_highlight(true);
1562 off = ansi_highlight(false);
1563 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1564 on = ansi_highlight_green(true);
1565 off = ansi_highlight_green(false);
1570 printf("\t Active: %s%s (%s)%s",
1572 strna(i->active_state),
1576 printf("\t Active: %s%s%s",
1578 strna(i->active_state),
1581 timestamp = (streq_ptr(i->active_state, "active") ||
1582 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1583 (streq_ptr(i->active_state, "inactive") ||
1584 streq_ptr(i->active_state, "maintenance")) ? i->inactive_enter_timestamp :
1585 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1586 i->active_exit_timestamp;
1588 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1589 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1592 printf(" since [%s; %s]\n", s2, s1);
1594 printf(" since [%s]\n", s2);
1599 printf("\t Device: %s\n", i->sysfs_path);
1601 printf("\t Where: %s\n", i->where);
1603 printf("\t What: %s\n", i->what);
1606 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1608 LIST_FOREACH(exec, p, i->exec) {
1611 /* Only show exited processes here */
1615 t = strv_join(p->argv, " ");
1616 printf("\t Process: %u (%s, code=%s, ", p->pid, strna(t), sigchld_code_to_string(p->code));
1619 if (p->code == CLD_EXITED) {
1622 printf("status=%i", p->status);
1624 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1628 printf("signal=%s", signal_to_string(p->status));
1631 if (i->main_pid == p->pid &&
1632 i->start_timestamp == p->start_timestamp &&
1633 i->exit_timestamp == p->start_timestamp)
1634 /* Let's not show this twice */
1637 if (p->pid == i->control_pid)
1641 if (i->main_pid > 0 || i->control_pid > 0) {
1644 if (i->main_pid > 0) {
1645 printf("Main PID: %u", (unsigned) i->main_pid);
1649 get_process_name(i->main_pid, &t);
1654 } else if (i->exit_code > 0) {
1655 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1657 if (i->exit_code == CLD_EXITED) {
1660 printf("status=%i", i->exit_status);
1662 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1666 printf("signal=%s", signal_to_string(i->exit_status));
1671 if (i->main_pid > 0 && i->control_pid > 0)
1674 if (i->control_pid > 0) {
1677 printf(" Control: %u", (unsigned) i->control_pid);
1679 get_process_name(i->control_pid, &t);
1690 printf("\t Status: \"%s\"\n", i->status_text);
1692 if (i->default_control_group) {
1695 printf("\t CGroup: %s\n", i->default_control_group);
1697 if ((c = columns()) > 18)
1702 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
1705 if (i->need_daemon_reload)
1706 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1707 ansi_highlight(true),
1708 ansi_highlight(false),
1709 arg_session ? "--session" : "--system");
1712 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1714 switch (dbus_message_iter_get_arg_type(iter)) {
1716 case DBUS_TYPE_STRING: {
1719 dbus_message_iter_get_basic(iter, &s);
1722 if (streq(name, "Id"))
1724 else if (streq(name, "LoadState"))
1726 else if (streq(name, "ActiveState"))
1727 i->active_state = s;
1728 else if (streq(name, "SubState"))
1730 else if (streq(name, "Description"))
1732 else if (streq(name, "FragmentPath"))
1734 else if (streq(name, "SysVPath")) {
1737 } else if (streq(name, "DefaultControlGroup"))
1738 i->default_control_group = s;
1739 else if (streq(name, "StatusText"))
1741 else if (streq(name, "SysFSPath"))
1743 else if (streq(name, "Where"))
1745 else if (streq(name, "What"))
1752 case DBUS_TYPE_BOOLEAN: {
1755 dbus_message_iter_get_basic(iter, &b);
1757 if (streq(name, "Accept"))
1759 else if (streq(name, "NeedDaemonReload"))
1760 i->need_daemon_reload = b;
1765 case DBUS_TYPE_UINT32: {
1768 dbus_message_iter_get_basic(iter, &u);
1770 if (streq(name, "MainPID")) {
1772 i->main_pid = (pid_t) u;
1775 } else if (streq(name, "ControlPID"))
1776 i->control_pid = (pid_t) u;
1777 else if (streq(name, "ExecMainPID")) {
1779 i->main_pid = (pid_t) u;
1780 } else if (streq(name, "NAccepted"))
1782 else if (streq(name, "NConnections"))
1783 i->n_connections = u;
1788 case DBUS_TYPE_INT32: {
1791 dbus_message_iter_get_basic(iter, &j);
1793 if (streq(name, "ExecMainCode"))
1794 i->exit_code = (int) j;
1795 else if (streq(name, "ExecMainStatus"))
1796 i->exit_status = (int) j;
1801 case DBUS_TYPE_UINT64: {
1804 dbus_message_iter_get_basic(iter, &u);
1806 if (streq(name, "ExecMainStartTimestamp"))
1807 i->start_timestamp = (usec_t) u;
1808 else if (streq(name, "ExecMainExitTimestamp"))
1809 i->exit_timestamp = (usec_t) u;
1810 else if (streq(name, "ActiveEnterTimestamp"))
1811 i->active_enter_timestamp = (usec_t) u;
1812 else if (streq(name, "InactiveEnterTimestamp"))
1813 i->inactive_enter_timestamp = (usec_t) u;
1814 else if (streq(name, "InactiveExitTimestamp"))
1815 i->inactive_exit_timestamp = (usec_t) u;
1816 else if (streq(name, "ActiveExitTimestamp"))
1817 i->active_exit_timestamp = (usec_t) u;
1822 case DBUS_TYPE_ARRAY: {
1824 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
1825 startswith(name, "Exec")) {
1826 DBusMessageIter sub;
1828 dbus_message_iter_recurse(iter, &sub);
1829 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1830 ExecStatusInfo *info;
1833 if (!(info = new0(ExecStatusInfo, 1)))
1836 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
1841 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
1843 dbus_message_iter_next(&sub);
1854 static int print_property(const char *name, DBusMessageIter *iter) {
1858 /* This is a low-level property printer, see
1859 * print_status_info() for the nicer output */
1861 if (arg_property && !strv_find(arg_property, name))
1864 switch (dbus_message_iter_get_arg_type(iter)) {
1866 case DBUS_TYPE_STRING: {
1868 dbus_message_iter_get_basic(iter, &s);
1870 if (arg_all || s[0])
1871 printf("%s=%s\n", name, s);
1876 case DBUS_TYPE_BOOLEAN: {
1878 dbus_message_iter_get_basic(iter, &b);
1879 printf("%s=%s\n", name, yes_no(b));
1884 case DBUS_TYPE_UINT64: {
1886 dbus_message_iter_get_basic(iter, &u);
1888 /* Yes, heuristics! But we can change this check
1889 * should it turn out to not be sufficient */
1891 if (strstr(name, "Timestamp")) {
1892 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
1894 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
1895 printf("%s=%s\n", name, strempty(t));
1896 } else if (strstr(name, "USec")) {
1897 char timespan[FORMAT_TIMESPAN_MAX];
1899 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
1901 printf("%s=%llu\n", name, (unsigned long long) u);
1906 case DBUS_TYPE_UINT32: {
1908 dbus_message_iter_get_basic(iter, &u);
1910 if (strstr(name, "UMask") || strstr(name, "Mode"))
1911 printf("%s=%04o\n", name, u);
1913 printf("%s=%u\n", name, (unsigned) u);
1918 case DBUS_TYPE_INT32: {
1920 dbus_message_iter_get_basic(iter, &i);
1922 printf("%s=%i\n", name, (int) i);
1926 case DBUS_TYPE_STRUCT: {
1927 DBusMessageIter sub;
1928 dbus_message_iter_recurse(iter, &sub);
1930 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
1933 dbus_message_iter_get_basic(&sub, &u);
1936 printf("%s=%u\n", name, (unsigned) u);
1938 printf("%s=\n", name);
1941 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
1944 dbus_message_iter_get_basic(&sub, &s);
1946 if (arg_all || s[0])
1947 printf("%s=%s\n", name, s);
1955 case DBUS_TYPE_ARRAY:
1957 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
1958 DBusMessageIter sub;
1961 dbus_message_iter_recurse(iter, &sub);
1963 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1964 printf("%s=", name);
1966 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1969 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
1970 dbus_message_iter_get_basic(&sub, &s);
1971 printf("%s%s", space ? " " : "", s);
1974 dbus_message_iter_next(&sub);
1982 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
1983 DBusMessageIter sub;
1985 dbus_message_iter_recurse(iter, &sub);
1987 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1988 printf("%s=", name);
1990 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1993 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
1994 dbus_message_iter_get_basic(&sub, &u);
1997 dbus_message_iter_next(&sub);
2005 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2006 DBusMessageIter sub, sub2;
2008 dbus_message_iter_recurse(iter, &sub);
2009 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2010 const char *type, *path;
2012 dbus_message_iter_recurse(&sub, &sub2);
2014 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2015 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2016 printf("%s=%s\n", type, path);
2018 dbus_message_iter_next(&sub);
2023 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2024 DBusMessageIter sub, sub2;
2026 dbus_message_iter_recurse(iter, &sub);
2027 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2029 uint64_t value, next_elapse;
2031 dbus_message_iter_recurse(&sub, &sub2);
2033 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2034 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2035 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2036 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2038 printf("%s={ value=%s ; next_elapse=%s }\n",
2040 format_timespan(timespan1, sizeof(timespan1), value),
2041 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2044 dbus_message_iter_next(&sub);
2049 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2050 DBusMessageIter sub;
2052 dbus_message_iter_recurse(iter, &sub);
2053 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2054 ExecStatusInfo info;
2057 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2058 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2061 t = strv_join(info.argv, " ");
2063 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2067 yes_no(info.ignore),
2068 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2069 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2070 (unsigned) info. pid,
2071 sigchld_code_to_string(info.code),
2073 info.code == CLD_EXITED ? "" : "/",
2074 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2080 strv_free(info.argv);
2082 dbus_message_iter_next(&sub);
2092 printf("%s=[unprintable]\n", name);
2097 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2098 DBusMessage *m = NULL, *reply = NULL;
2099 const char *interface = "";
2102 DBusMessageIter iter, sub, sub2, sub3;
2103 UnitStatusInfo info;
2111 dbus_error_init(&error);
2113 if (!(m = dbus_message_new_method_call(
2114 "org.freedesktop.systemd1",
2116 "org.freedesktop.DBus.Properties",
2118 log_error("Could not allocate message.");
2123 if (!dbus_message_append_args(m,
2124 DBUS_TYPE_STRING, &interface,
2125 DBUS_TYPE_INVALID)) {
2126 log_error("Could not append arguments to message.");
2131 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2132 log_error("Failed to issue method call: %s", bus_error_message(&error));
2137 if (!dbus_message_iter_init(reply, &iter) ||
2138 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2139 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2140 log_error("Failed to parse reply.");
2145 dbus_message_iter_recurse(&iter, &sub);
2152 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2155 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2156 log_error("Failed to parse reply.");
2161 dbus_message_iter_recurse(&sub, &sub2);
2163 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2164 log_error("Failed to parse reply.");
2169 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2170 log_error("Failed to parse reply.");
2175 dbus_message_iter_recurse(&sub2, &sub3);
2177 if (show_properties)
2178 r = print_property(name, &sub3);
2180 r = status_property(name, &sub3, &info);
2183 log_error("Failed to parse reply.");
2188 dbus_message_iter_next(&sub);
2193 if (!show_properties) {
2194 if (arg_sysv_compat &&
2195 !streq_ptr(info.active_state, "active") &&
2196 !streq_ptr(info.active_state, "reloading")) {
2198 /* If the SysV compatibility mode is on, we
2199 * will refuse to run "status" on units that
2201 log_error("Unit not active.");
2204 print_status_info(&info);
2207 while ((p = info.exec)) {
2208 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2209 exec_status_info_free(p);
2214 dbus_message_unref(m);
2217 dbus_message_unref(reply);
2219 dbus_error_free(&error);
2224 static int show(DBusConnection *bus, char **args, unsigned n) {
2225 DBusMessage *m = NULL, *reply = NULL;
2229 bool show_properties, new_line = false;
2234 dbus_error_init(&error);
2236 show_properties = !streq(args[0], "status");
2238 if (show_properties && n <= 1) {
2239 /* If not argument is specified inspect the manager
2242 r = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2246 for (i = 1; i < n; i++) {
2247 const char *path = NULL;
2250 if (safe_atou32(args[i], &id) < 0) {
2252 /* Interpret as unit name */
2254 if (!(m = dbus_message_new_method_call(
2255 "org.freedesktop.systemd1",
2256 "/org/freedesktop/systemd1",
2257 "org.freedesktop.systemd1.Manager",
2259 log_error("Could not allocate message.");
2264 if (!dbus_message_append_args(m,
2265 DBUS_TYPE_STRING, &args[i],
2266 DBUS_TYPE_INVALID)) {
2267 log_error("Could not append arguments to message.");
2272 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2274 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2275 log_error("Failed to issue method call: %s", bus_error_message(&error));
2280 dbus_error_free(&error);
2282 dbus_message_unref(m);
2283 if (!(m = dbus_message_new_method_call(
2284 "org.freedesktop.systemd1",
2285 "/org/freedesktop/systemd1",
2286 "org.freedesktop.systemd1.Manager",
2288 log_error("Could not allocate message.");
2293 if (!dbus_message_append_args(m,
2294 DBUS_TYPE_STRING, &args[i],
2295 DBUS_TYPE_INVALID)) {
2296 log_error("Could not append arguments to message.");
2301 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2302 log_error("Failed to issue method call: %s", bus_error_message(&error));
2308 } else if (show_properties) {
2310 /* Interpret as job id */
2312 if (!(m = dbus_message_new_method_call(
2313 "org.freedesktop.systemd1",
2314 "/org/freedesktop/systemd1",
2315 "org.freedesktop.systemd1.Manager",
2317 log_error("Could not allocate message.");
2322 if (!dbus_message_append_args(m,
2323 DBUS_TYPE_UINT32, &id,
2324 DBUS_TYPE_INVALID)) {
2325 log_error("Could not append arguments to message.");
2330 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2331 log_error("Failed to issue method call: %s", bus_error_message(&error));
2337 /* Interpret as PID */
2339 if (!(m = dbus_message_new_method_call(
2340 "org.freedesktop.systemd1",
2341 "/org/freedesktop/systemd1",
2342 "org.freedesktop.systemd1.Manager",
2344 log_error("Could not allocate message.");
2349 if (!dbus_message_append_args(m,
2350 DBUS_TYPE_UINT32, &id,
2351 DBUS_TYPE_INVALID)) {
2352 log_error("Could not append arguments to message.");
2357 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2358 log_error("Failed to issue method call: %s", bus_error_message(&error));
2364 if (!dbus_message_get_args(reply, &error,
2365 DBUS_TYPE_OBJECT_PATH, &path,
2366 DBUS_TYPE_INVALID)) {
2367 log_error("Failed to parse reply: %s", bus_error_message(&error));
2372 if ((r = show_one(bus, path, show_properties, &new_line)) < 0)
2375 dbus_message_unref(m);
2376 dbus_message_unref(reply);
2384 dbus_message_unref(m);
2387 dbus_message_unref(reply);
2389 dbus_error_free(&error);
2394 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2396 DBusMessage *m = NULL, *reply = NULL;
2401 dbus_error_init(&error);
2403 log_debug("Got D-Bus request: %s.%s() on %s",
2404 dbus_message_get_interface(message),
2405 dbus_message_get_member(message),
2406 dbus_message_get_path(message));
2408 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2409 log_error("Warning! D-Bus connection terminated.");
2410 dbus_connection_close(connection);
2412 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2413 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2414 const char *id, *path;
2416 if (!dbus_message_get_args(message, &error,
2417 DBUS_TYPE_STRING, &id,
2418 DBUS_TYPE_OBJECT_PATH, &path,
2420 log_error("Failed to parse message: %s", bus_error_message(&error));
2421 else if (streq(dbus_message_get_member(message), "UnitNew"))
2422 printf("Unit %s added.\n", id);
2424 printf("Unit %s removed.\n", id);
2426 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2427 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2431 if (!dbus_message_get_args(message, &error,
2432 DBUS_TYPE_UINT32, &id,
2433 DBUS_TYPE_OBJECT_PATH, &path,
2435 log_error("Failed to parse message: %s", bus_error_message(&error));
2436 else if (streq(dbus_message_get_member(message), "JobNew"))
2437 printf("Job %u added.\n", id);
2439 printf("Job %u removed.\n", id);
2442 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2444 const char *path, *interface, *property = "Id";
2445 DBusMessageIter iter, sub;
2447 path = dbus_message_get_path(message);
2449 if (!dbus_message_get_args(message, &error,
2450 DBUS_TYPE_STRING, &interface,
2451 DBUS_TYPE_INVALID)) {
2452 log_error("Failed to parse message: %s", bus_error_message(&error));
2456 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2457 !streq(interface, "org.freedesktop.systemd1.Unit"))
2460 if (!(m = dbus_message_new_method_call(
2461 "org.freedesktop.systemd1",
2463 "org.freedesktop.DBus.Properties",
2465 log_error("Could not allocate message.");
2469 if (!dbus_message_append_args(m,
2470 DBUS_TYPE_STRING, &interface,
2471 DBUS_TYPE_STRING, &property,
2472 DBUS_TYPE_INVALID)) {
2473 log_error("Could not append arguments to message.");
2477 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2478 log_error("Failed to issue method call: %s", bus_error_message(&error));
2482 if (!dbus_message_iter_init(reply, &iter) ||
2483 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2484 log_error("Failed to parse reply.");
2488 dbus_message_iter_recurse(&iter, &sub);
2490 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2493 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2494 log_error("Failed to parse reply.");
2498 dbus_message_iter_get_basic(&sub, &id);
2499 printf("Unit %s changed.\n", id);
2503 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2504 log_error("Failed to parse reply.");
2508 dbus_message_iter_get_basic(&sub, &id);
2509 printf("Job %u changed.\n", id);
2515 dbus_message_unref(m);
2518 dbus_message_unref(reply);
2520 dbus_error_free(&error);
2521 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2525 dbus_message_unref(m);
2528 dbus_message_unref(reply);
2530 dbus_error_free(&error);
2531 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2534 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2535 DBusMessage *m = NULL, *reply = NULL;
2539 dbus_error_init(&error);
2542 dbus_bus_add_match(bus,
2544 "sender='org.freedesktop.systemd1',"
2545 "interface='org.freedesktop.systemd1.Manager',"
2546 "path='/org/freedesktop/systemd1'",
2549 if (dbus_error_is_set(&error)) {
2550 log_error("Failed to add match: %s", bus_error_message(&error));
2555 dbus_bus_add_match(bus,
2557 "sender='org.freedesktop.systemd1',"
2558 "interface='org.freedesktop.DBus.Properties',"
2559 "member='PropertiesChanged'",
2562 if (dbus_error_is_set(&error)) {
2563 log_error("Failed to add match: %s", bus_error_message(&error));
2569 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2570 log_error("Failed to add filter.");
2575 if (!(m = dbus_message_new_method_call(
2576 "org.freedesktop.systemd1",
2577 "/org/freedesktop/systemd1",
2578 "org.freedesktop.systemd1.Manager",
2580 log_error("Could not allocate message.");
2585 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2586 log_error("Failed to issue method call: %s", bus_error_message(&error));
2591 while (dbus_connection_read_write_dispatch(bus, -1))
2598 /* This is slightly dirty, since we don't undo the filter or the matches. */
2601 dbus_message_unref(m);
2604 dbus_message_unref(reply);
2606 dbus_error_free(&error);
2611 static int dump(DBusConnection *bus, char **args, unsigned n) {
2612 DBusMessage *m = NULL, *reply = NULL;
2617 dbus_error_init(&error);
2619 if (!(m = dbus_message_new_method_call(
2620 "org.freedesktop.systemd1",
2621 "/org/freedesktop/systemd1",
2622 "org.freedesktop.systemd1.Manager",
2624 log_error("Could not allocate message.");
2628 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2629 log_error("Failed to issue method call: %s", bus_error_message(&error));
2634 if (!dbus_message_get_args(reply, &error,
2635 DBUS_TYPE_STRING, &text,
2636 DBUS_TYPE_INVALID)) {
2637 log_error("Failed to parse reply: %s", bus_error_message(&error));
2642 fputs(text, stdout);
2648 dbus_message_unref(m);
2651 dbus_message_unref(reply);
2653 dbus_error_free(&error);
2658 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2659 DBusMessage *m = NULL, *reply = NULL;
2662 const char *name = "", *path, *id;
2663 dbus_bool_t cleanup = FALSE;
2664 DBusMessageIter iter, sub;
2666 *interface = "org.freedesktop.systemd1.Unit",
2669 dbus_error_init(&error);
2671 if (!(m = dbus_message_new_method_call(
2672 "org.freedesktop.systemd1",
2673 "/org/freedesktop/systemd1",
2674 "org.freedesktop.systemd1.Manager",
2675 "CreateSnapshot"))) {
2676 log_error("Could not allocate message.");
2683 if (!dbus_message_append_args(m,
2684 DBUS_TYPE_STRING, &name,
2685 DBUS_TYPE_BOOLEAN, &cleanup,
2686 DBUS_TYPE_INVALID)) {
2687 log_error("Could not append arguments to message.");
2692 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2693 log_error("Failed to issue method call: %s", bus_error_message(&error));
2698 if (!dbus_message_get_args(reply, &error,
2699 DBUS_TYPE_OBJECT_PATH, &path,
2700 DBUS_TYPE_INVALID)) {
2701 log_error("Failed to parse reply: %s", bus_error_message(&error));
2706 dbus_message_unref(m);
2707 if (!(m = dbus_message_new_method_call(
2708 "org.freedesktop.systemd1",
2710 "org.freedesktop.DBus.Properties",
2712 log_error("Could not allocate message.");
2716 if (!dbus_message_append_args(m,
2717 DBUS_TYPE_STRING, &interface,
2718 DBUS_TYPE_STRING, &property,
2719 DBUS_TYPE_INVALID)) {
2720 log_error("Could not append arguments to message.");
2725 dbus_message_unref(reply);
2726 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2727 log_error("Failed to issue method call: %s", bus_error_message(&error));
2732 if (!dbus_message_iter_init(reply, &iter) ||
2733 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2734 log_error("Failed to parse reply.");
2739 dbus_message_iter_recurse(&iter, &sub);
2741 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2742 log_error("Failed to parse reply.");
2747 dbus_message_iter_get_basic(&sub, &id);
2755 dbus_message_unref(m);
2758 dbus_message_unref(reply);
2760 dbus_error_free(&error);
2765 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2766 DBusMessage *m = NULL, *reply = NULL;
2774 dbus_error_init(&error);
2776 for (i = 1; i < n; i++) {
2777 const char *path = NULL;
2779 if (!(m = dbus_message_new_method_call(
2780 "org.freedesktop.systemd1",
2781 "/org/freedesktop/systemd1",
2782 "org.freedesktop.systemd1.Manager",
2784 log_error("Could not allocate message.");
2789 if (!dbus_message_append_args(m,
2790 DBUS_TYPE_STRING, &args[i],
2791 DBUS_TYPE_INVALID)) {
2792 log_error("Could not append arguments to message.");
2797 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2798 log_error("Failed to issue method call: %s", bus_error_message(&error));
2803 if (!dbus_message_get_args(reply, &error,
2804 DBUS_TYPE_OBJECT_PATH, &path,
2805 DBUS_TYPE_INVALID)) {
2806 log_error("Failed to parse reply: %s", bus_error_message(&error));
2811 dbus_message_unref(m);
2812 if (!(m = dbus_message_new_method_call(
2813 "org.freedesktop.systemd1",
2815 "org.freedesktop.systemd1.Snapshot",
2817 log_error("Could not allocate message.");
2822 dbus_message_unref(reply);
2823 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2824 log_error("Failed to issue method call: %s", bus_error_message(&error));
2829 dbus_message_unref(m);
2830 dbus_message_unref(reply);
2838 dbus_message_unref(m);
2841 dbus_message_unref(reply);
2843 dbus_error_free(&error);
2848 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2849 DBusMessage *m = NULL, *reply = NULL;
2854 dbus_error_init(&error);
2856 if (arg_action == ACTION_RELOAD)
2858 else if (arg_action == ACTION_REEXEC)
2859 method = "Reexecute";
2861 assert(arg_action == ACTION_SYSTEMCTL);
2864 streq(args[0], "clear-jobs") ||
2865 streq(args[0], "cancel") ? "ClearJobs" :
2866 streq(args[0], "daemon-reexec") ? "Reexecute" :
2867 streq(args[0], "reset-maintenance") ? "ResetMaintenance" :
2868 streq(args[0], "daemon-exit") ? "Exit" :
2872 if (!(m = dbus_message_new_method_call(
2873 "org.freedesktop.systemd1",
2874 "/org/freedesktop/systemd1",
2875 "org.freedesktop.systemd1.Manager",
2877 log_error("Could not allocate message.");
2881 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2883 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
2884 /* There's always a fallback possible for
2885 * legacy actions. */
2890 log_error("Failed to issue method call: %s", bus_error_message(&error));
2899 dbus_message_unref(m);
2902 dbus_message_unref(reply);
2904 dbus_error_free(&error);
2909 static int reset_maintenance(DBusConnection *bus, char **args, unsigned n) {
2910 DBusMessage *m = NULL, *reply = NULL;
2916 dbus_error_init(&error);
2919 return daemon_reload(bus, args, n);
2921 for (i = 1; i < n; i++) {
2923 if (!(m = dbus_message_new_method_call(
2924 "org.freedesktop.systemd1",
2925 "/org/freedesktop/systemd1",
2926 "org.freedesktop.systemd1.Manager",
2927 "ResetMaintenanceUnit"))) {
2928 log_error("Could not allocate message.");
2933 if (!dbus_message_append_args(m,
2934 DBUS_TYPE_STRING, args + i,
2935 DBUS_TYPE_INVALID)) {
2936 log_error("Could not append arguments to message.");
2941 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2942 log_error("Failed to issue method call: %s", bus_error_message(&error));
2947 dbus_message_unref(m);
2948 dbus_message_unref(reply);
2956 dbus_message_unref(m);
2959 dbus_message_unref(reply);
2961 dbus_error_free(&error);
2966 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
2967 DBusMessage *m = NULL, *reply = NULL;
2969 DBusMessageIter iter, sub, sub2;
2972 *interface = "org.freedesktop.systemd1.Manager",
2973 *property = "Environment";
2975 dbus_error_init(&error);
2977 if (!(m = dbus_message_new_method_call(
2978 "org.freedesktop.systemd1",
2979 "/org/freedesktop/systemd1",
2980 "org.freedesktop.DBus.Properties",
2982 log_error("Could not allocate message.");
2986 if (!dbus_message_append_args(m,
2987 DBUS_TYPE_STRING, &interface,
2988 DBUS_TYPE_STRING, &property,
2989 DBUS_TYPE_INVALID)) {
2990 log_error("Could not append arguments to message.");
2995 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2996 log_error("Failed to issue method call: %s", bus_error_message(&error));
3001 if (!dbus_message_iter_init(reply, &iter) ||
3002 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3003 log_error("Failed to parse reply.");
3008 dbus_message_iter_recurse(&iter, &sub);
3010 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3011 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3012 log_error("Failed to parse reply.");
3017 dbus_message_iter_recurse(&sub, &sub2);
3019 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3022 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3023 log_error("Failed to parse reply.");
3028 dbus_message_iter_get_basic(&sub2, &text);
3029 printf("%s\n", text);
3031 dbus_message_iter_next(&sub2);
3038 dbus_message_unref(m);
3041 dbus_message_unref(reply);
3043 dbus_error_free(&error);
3048 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3049 DBusMessage *m = NULL, *reply = NULL;
3053 DBusMessageIter iter, sub;
3056 dbus_error_init(&error);
3058 method = streq(args[0], "set-environment")
3060 : "UnsetEnvironment";
3062 if (!(m = dbus_message_new_method_call(
3063 "org.freedesktop.systemd1",
3064 "/org/freedesktop/systemd1",
3065 "org.freedesktop.systemd1.Manager",
3068 log_error("Could not allocate message.");
3072 dbus_message_iter_init_append(m, &iter);
3074 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3075 log_error("Could not append arguments to message.");
3080 for (i = 1; i < n; i++)
3081 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3082 log_error("Could not append arguments to message.");
3087 if (!dbus_message_iter_close_container(&iter, &sub)) {
3088 log_error("Could not append arguments to message.");
3093 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3094 log_error("Failed to issue method call: %s", bus_error_message(&error));
3103 dbus_message_unref(m);
3106 dbus_message_unref(reply);
3108 dbus_error_free(&error);
3121 static Hashmap *will_install = NULL, *have_installed = NULL;
3122 static Set *remove_symlinks_to = NULL;
3124 static void install_info_free(InstallInfo *i) {
3129 strv_free(i->aliases);
3130 strv_free(i->wanted_by);
3134 static void install_info_hashmap_free(Hashmap *m) {
3137 while ((i = hashmap_steal_first(m)))
3138 install_info_free(i);
3143 static bool unit_name_valid(const char *name) {
3145 /* This is a minimal version of unit_name_valid() from
3151 if (ignore_file(name))
3157 static int install_info_add(const char *name) {
3161 assert(will_install);
3163 if (!unit_name_valid(name))
3166 if (hashmap_get(have_installed, name) ||
3167 hashmap_get(will_install, name))
3170 if (!(i = new0(InstallInfo, 1))) {
3175 if (!(i->name = strdup(name))) {
3180 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3187 install_info_free(i);
3192 static int config_parse_also(
3193 const char *filename,
3195 const char *section,
3209 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3213 if (!(n = strndup(w, l)))
3216 r = install_info_add(n);
3226 static int mark_symlink_for_removal(const char *p) {
3231 assert(path_is_absolute(p));
3233 if (!remove_symlinks_to)
3236 if (!(n = strdup(p)))
3239 path_kill_slashes(n);
3241 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3243 return r == -EEXIST ? 0 : r;
3249 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3258 if (!(d = fdopendir(fd))) {
3259 close_nointr_nofail(fd);
3265 while ((de = readdir(d))) {
3266 bool is_dir = false, is_link = false;
3268 if (ignore_file(de->d_name))
3271 if (de->d_type == DT_LNK)
3273 else if (de->d_type == DT_DIR)
3275 else if (de->d_type == DT_UNKNOWN) {
3278 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3279 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3286 is_link = S_ISLNK(st.st_mode);
3287 is_dir = S_ISDIR(st.st_mode);
3295 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3296 log_error("Failed to open %s/%s: %m", root, de->d_name);
3303 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3304 log_error("Failed to allocate directory string.");
3305 close_nointr_nofail(nfd);
3310 /* This will close nfd, regardless whether it succeeds or not */
3311 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3317 } else if (is_link) {
3321 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3322 log_error("Failed to allocate symlink string.");
3327 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3328 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3336 if ((c = canonicalize_file_name(dest))) {
3337 /* This might fail if the destination
3338 * is already removed */
3344 path_kill_slashes(dest);
3345 if (set_get(remove_symlinks_to, dest)) {
3348 log_info("rm '%s'", p);
3350 if (unlink(p) < 0) {
3351 log_error("Cannot unlink symlink %s: %m", p);
3356 rmdir_parents(p, config_path);
3357 path_kill_slashes(p);
3359 if (!set_get(remove_symlinks_to, p)) {
3361 if ((r = mark_symlink_for_removal(p)) < 0) {
3380 static int remove_marked_symlinks(const char *config_path) {
3384 assert(config_path);
3386 if (set_size(remove_symlinks_to) <= 0)
3389 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3396 if ((cfd = dup(fd)) < 0) {
3401 /* This takes possession of cfd and closes it */
3402 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3408 close_nointr_nofail(fd);
3413 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3420 if (streq(verb, "enable")) {
3423 mkdir_parents(new_path, 0755);
3425 if (symlink(old_path, new_path) >= 0) {
3428 log_info("ln -s '%s' '%s'", old_path, new_path);
3433 if (errno != EEXIST) {
3434 log_error("Cannot link %s to %s: %m", old_path, new_path);
3438 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3440 if (errno == EINVAL) {
3441 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3445 log_error("readlink() failed: %s", strerror(-r));
3449 if (streq(dest, old_path)) {
3455 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3464 log_info("ln -s '%s' '%s'", old_path, new_path);
3466 if (symlink(old_path, new_path) >= 0)
3469 log_error("Cannot link %s to %s: %m", old_path, new_path);
3472 } else if (streq(verb, "disable")) {
3475 if ((r = mark_symlink_for_removal(old_path)) < 0)
3478 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3479 if (errno == ENOENT)
3482 if (errno == EINVAL) {
3483 log_warning("File %s not a symlink, ignoring.", old_path);
3487 log_error("readlink() failed: %s", strerror(-r));
3491 if (!streq(dest, old_path)) {
3492 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3499 if ((r = mark_symlink_for_removal(new_path)) < 0)
3503 log_info("rm '%s'", new_path);
3505 if (unlink(new_path) >= 0)
3508 log_error("Cannot unlink %s: %m", new_path);
3511 } else if (streq(verb, "is-enabled")) {
3514 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3516 if (errno == ENOENT || errno == EINVAL)
3519 log_error("readlink() failed: %s", strerror(-r));
3523 if (streq(dest, old_path)) {
3531 assert_not_reached("Unknown action.");
3534 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3536 char *alias_path = NULL;
3541 assert(config_path);
3543 STRV_FOREACH(s, i->aliases) {
3545 if (!unit_name_valid(*s)) {
3546 log_error("Invalid name %s.", *s);
3552 if (!(alias_path = path_make_absolute(*s, config_path))) {
3553 log_error("Out of memory");
3558 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3561 if (streq(verb, "disable"))
3562 rmdir_parents(alias_path, config_path);
3573 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3575 char *alias_path = NULL;
3580 assert(config_path);
3582 STRV_FOREACH(s, i->wanted_by) {
3583 if (!unit_name_valid(*s)) {
3584 log_error("Invalid name %s.", *s);
3592 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3593 log_error("Out of memory");
3598 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3601 if (streq(verb, "disable"))
3602 rmdir_parents(alias_path, config_path);
3613 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3615 const ConfigItem items[] = {
3616 { "Alias", config_parse_strv, &i->aliases, "Install" },
3617 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3618 { "Also", config_parse_also, NULL, "Install" },
3620 { NULL, NULL, NULL, NULL }
3624 char *filename = NULL;
3631 STRV_FOREACH(p, paths->unit_path) {
3634 if (!(filename = path_make_absolute(i->name, *p))) {
3635 log_error("Out of memory");
3639 /* Ensure that we don't follow symlinks */
3640 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3641 if ((f = fdopen(fd, "re")))
3644 if (errno == ELOOP) {
3645 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3650 if (errno != ENOENT) {
3651 log_error("Failed to open %s: %m", filename);
3661 log_error("Couldn't find %s.", i->name);
3667 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3674 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3677 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3680 if ((r = mark_symlink_for_removal(filename)) < 0)
3683 if ((r = remove_marked_symlinks(config_path)) < 0)
3689 static char *get_config_path(void) {
3691 if (arg_session && arg_global)
3692 return strdup(SESSION_CONFIG_UNIT_PATH);
3697 if (session_config_home(&p) < 0)
3703 return strdup(SYSTEM_CONFIG_UNIT_PATH);
3706 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3710 char *config_path = NULL;
3713 const char *verb = args[0];
3715 dbus_error_init(&error);
3718 if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3719 log_error("Failed to determine lookup paths: %s", strerror(-r));
3723 if (!(config_path = get_config_path())) {
3724 log_error("Failed to determine config path");
3729 will_install = hashmap_new(string_hash_func, string_compare_func);
3730 have_installed = hashmap_new(string_hash_func, string_compare_func);
3732 if (!will_install || !have_installed) {
3733 log_error("Failed to allocate unit sets.");
3738 if (!arg_defaults && streq(verb, "disable"))
3739 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3740 log_error("Failed to allocate symlink sets.");
3745 for (j = 1; j < n; j++)
3746 if ((r = install_info_add(args[j])) < 0)
3749 while ((i = hashmap_first(will_install))) {
3752 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3754 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3762 /* In test mode and found something */
3768 if (streq(verb, "is-enabled"))
3769 r = r > 0 ? 0 : -ENOENT;
3771 /* Don't try to reload anything if the user asked us to not do this */
3773 /* Don't try to reload anything when updating a unit globally */
3775 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3776 (arg_session || sd_booted() > 0) &&
3777 /* Don't try to reload anything if we are running in a chroot environment */
3778 (arg_session || running_in_chroot() <= 0) ) {
3781 if ((q = daemon_reload(bus, args, n)) < 0)
3786 install_info_hashmap_free(will_install);
3787 install_info_hashmap_free(have_installed);
3789 set_free_free(remove_symlinks_to);
3791 lookup_paths_free(&paths);
3798 static int systemctl_help(void) {
3800 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3801 "Send control commands to or query the systemd manager.\n\n"
3802 " -h --help Show this help\n"
3803 " -t --type=TYPE List only units of a particular type\n"
3804 " -p --property=NAME Show only properties by this name\n"
3805 " -a --all Show all units/properties, including dead/empty ones\n"
3806 " --full Don't ellipsize unit names on output\n"
3807 " --fail When queueing a new job, fail if conflicting jobs are\n"
3809 " -q --quiet Suppress output\n"
3810 " --no-block Do not wait until operation finished\n"
3811 " --system Connect to system bus\n"
3812 " --session Connect to session bus\n"
3813 " --order When generating graph for dot, show only order\n"
3814 " --require When generating graph for dot, show only requirement\n"
3815 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3816 " --global Enable/disable unit files globally\n"
3817 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3819 " --force When enabling unit files, override existing symlinks\n"
3820 " --defaults When disabling unit files, remove default symlinks only\n\n"
3822 " list-units List units\n"
3823 " start [NAME...] Start (activate) one or more units\n"
3824 " stop [NAME...] Stop (deactivate) one or more units\n"
3825 " reload [NAME...] Reload one or more units\n"
3826 " restart [NAME...] Start or restart one or more units\n"
3827 " try-restart [NAME...] Restart one or more units if active\n"
3828 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3829 " otherwise start or restart\n"
3830 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3831 " otherwise restart if active\n"
3832 " isolate [NAME] Start one unit and stop all others\n"
3833 " is-active [NAME...] Check whether units are active\n"
3834 " status [NAME...|PID...] Show runtime status of one or more units\n"
3835 " show [NAME...|JOB...] Show properties of one or more\n"
3836 " units/jobs or the manager\n"
3837 " reset-maintenance [NAME...] Reset maintenance state for all, one,\n"
3839 " enable [NAME...] Enable one or more unit files\n"
3840 " disable [NAME...] Disable one or more unit files\n"
3841 " is-enabled [NAME...] Check whether unit files are enabled\n"
3842 " load [NAME...] Load one or more units\n"
3843 " list-jobs List jobs\n"
3844 " cancel [JOB...] Cancel all, one, or more jobs\n"
3845 " monitor Monitor unit/job changes\n"
3846 " dump Dump server status\n"
3847 " dot Dump dependency graph for dot(1)\n"
3848 " snapshot [NAME] Create a snapshot\n"
3849 " delete [NAME...] Remove one or more snapshots\n"
3850 " daemon-reload Reload systemd manager configuration\n"
3851 " daemon-reexec Reexecute systemd manager\n"
3852 " daemon-exit Ask the systemd manager to quit\n"
3853 " show-environment Dump environment\n"
3854 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3855 " unset-environment [NAME...] Unset one or more environment variables\n"
3856 " halt Shut down and halt the system\n"
3857 " poweroff Shut down and power-off the system\n"
3858 " reboot Shut down and reboot the system\n"
3859 " rescue Enter system rescue mode\n"
3860 " emergency Enter system emergency mode\n"
3861 " default Enter system default mode\n",
3862 program_invocation_short_name);
3867 static int halt_help(void) {
3869 printf("%s [OPTIONS...]\n\n"
3870 "%s the system.\n\n"
3871 " --help Show this help\n"
3872 " --halt Halt the machine\n"
3873 " -p --poweroff Switch off the machine\n"
3874 " --reboot Reboot the machine\n"
3875 " -f --force Force immediate halt/power-off/reboot\n"
3876 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3877 " -d --no-wtmp Don't write wtmp record\n"
3878 " -n --no-sync Don't sync before halt/power-off/reboot\n"
3879 " --no-wall Don't send wall message before halt/power-off/reboot\n",
3880 program_invocation_short_name,
3881 arg_action == ACTION_REBOOT ? "Reboot" :
3882 arg_action == ACTION_POWEROFF ? "Power off" :
3888 static int shutdown_help(void) {
3890 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3891 "Shut down the system.\n\n"
3892 " --help Show this help\n"
3893 " -H --halt Halt the machine\n"
3894 " -P --poweroff Power-off the machine\n"
3895 " -r --reboot Reboot the machine\n"
3896 " -h Equivalent to --poweroff, overriden by --halt\n"
3897 " -k Don't halt/power-off/reboot, just send warnings\n"
3898 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3899 " -c Cancel a pending shutdown\n",
3900 program_invocation_short_name);
3905 static int telinit_help(void) {
3907 printf("%s [OPTIONS...] {COMMAND}\n\n"
3908 "Send control commands to the init daemon.\n\n"
3909 " --help Show this help\n"
3910 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
3912 " 0 Power-off the machine\n"
3913 " 6 Reboot the machine\n"
3914 " 2, 3, 4, 5 Start runlevelX.target unit\n"
3915 " 1, s, S Enter rescue mode\n"
3916 " q, Q Reload init daemon configuration\n"
3917 " u, U Reexecute init daemon\n",
3918 program_invocation_short_name);
3923 static int runlevel_help(void) {
3925 printf("%s [OPTIONS...]\n\n"
3926 "Prints the previous and current runlevel of the init system.\n\n"
3927 " --help Show this help\n",
3928 program_invocation_short_name);
3933 static int systemctl_parse_argv(int argc, char *argv[]) {
3951 static const struct option options[] = {
3952 { "help", no_argument, NULL, 'h' },
3953 { "type", required_argument, NULL, 't' },
3954 { "property", required_argument, NULL, 'p' },
3955 { "all", no_argument, NULL, 'a' },
3956 { "full", no_argument, NULL, ARG_FULL },
3957 { "fail", no_argument, NULL, ARG_FAIL },
3958 { "session", no_argument, NULL, ARG_SESSION },
3959 { "system", no_argument, NULL, ARG_SYSTEM },
3960 { "global", no_argument, NULL, ARG_GLOBAL },
3961 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
3962 { "no-wall", no_argument, NULL, ARG_NO_WALL },
3963 { "quiet", no_argument, NULL, 'q' },
3964 { "order", no_argument, NULL, ARG_ORDER },
3965 { "require", no_argument, NULL, ARG_REQUIRE },
3966 { "force", no_argument, NULL, ARG_FORCE },
3967 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
3968 { "defaults", no_argument, NULL, ARG_DEFAULTS },
3969 { "sysv-compat", no_argument, NULL, ARG_SYSV_COMPAT },
3970 { NULL, 0, NULL, 0 }
3978 while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
3993 if (!(l = strv_append(arg_property, optarg)))
3996 strv_free(arg_property);
3999 /* If the user asked for a particular
4000 * property, show it to him, even if it is
4019 arg_session = false;
4023 arg_no_block = true;
4031 arg_dot = DOT_ORDER;
4035 arg_dot = DOT_REQUIRE;
4051 arg_no_reload = true;
4060 arg_defaults = true;
4063 case ARG_SYSV_COMPAT:
4064 arg_sysv_compat = true;
4071 log_error("Unknown option code %c", c);
4079 static int halt_parse_argv(int argc, char *argv[]) {
4088 static const struct option options[] = {
4089 { "help", no_argument, NULL, ARG_HELP },
4090 { "halt", no_argument, NULL, ARG_HALT },
4091 { "poweroff", no_argument, NULL, 'p' },
4092 { "reboot", no_argument, NULL, ARG_REBOOT },
4093 { "force", no_argument, NULL, 'f' },
4094 { "wtmp-only", no_argument, NULL, 'w' },
4095 { "no-wtmp", no_argument, NULL, 'd' },
4096 { "no-sync", no_argument, NULL, 'n' },
4097 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4098 { NULL, 0, NULL, 0 }
4106 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4107 if (runlevel == '0' || runlevel == '6')
4108 arg_immediate = true;
4110 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4118 arg_action = ACTION_HALT;
4122 if (arg_action != ACTION_REBOOT)
4123 arg_action = ACTION_POWEROFF;
4127 arg_action = ACTION_REBOOT;
4131 arg_immediate = true;
4152 /* Compatibility nops */
4159 log_error("Unknown option code %c", c);
4164 if (optind < argc) {
4165 log_error("Too many arguments.");
4172 static int parse_time_spec(const char *t, usec_t *_u) {
4176 if (streq(t, "now"))
4178 else if (t[0] == '+') {
4181 if (safe_atou64(t + 1, &u) < 0)
4184 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4193 hour = strtol(t, &e, 10);
4194 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4197 minute = strtol(e+1, &e, 10);
4198 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4201 n = now(CLOCK_REALTIME);
4202 s = (time_t) (n / USEC_PER_SEC);
4205 assert_se(localtime_r(&s, &tm));
4207 tm.tm_hour = (int) hour;
4208 tm.tm_min = (int) minute;
4211 assert_se(s = mktime(&tm));
4213 *_u = (usec_t) s * USEC_PER_SEC;
4216 *_u += USEC_PER_DAY;
4222 static int shutdown_parse_argv(int argc, char *argv[]) {
4229 static const struct option options[] = {
4230 { "help", no_argument, NULL, ARG_HELP },
4231 { "halt", no_argument, NULL, 'H' },
4232 { "poweroff", no_argument, NULL, 'P' },
4233 { "reboot", no_argument, NULL, 'r' },
4234 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4235 { NULL, 0, NULL, 0 }
4243 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4251 arg_action = ACTION_HALT;
4255 arg_action = ACTION_POWEROFF;
4259 arg_action = ACTION_REBOOT;
4263 if (arg_action != ACTION_HALT)
4264 arg_action = ACTION_POWEROFF;
4277 /* Compatibility nops */
4281 arg_action = ACTION_CANCEL_SHUTDOWN;
4288 log_error("Unknown option code %c", c);
4293 if (argc > optind) {
4294 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4295 log_error("Failed to parse time specification: %s", argv[optind]);
4299 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4301 /* We skip the time argument */
4302 if (argc > optind + 1)
4303 arg_wall = argv + optind + 1;
4310 static int telinit_parse_argv(int argc, char *argv[]) {
4317 static const struct option options[] = {
4318 { "help", no_argument, NULL, ARG_HELP },
4319 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4320 { NULL, 0, NULL, 0 }
4323 static const struct {
4327 { '0', ACTION_POWEROFF },
4328 { '6', ACTION_REBOOT },
4329 { '1', ACTION_RESCUE },
4330 { '2', ACTION_RUNLEVEL2 },
4331 { '3', ACTION_RUNLEVEL3 },
4332 { '4', ACTION_RUNLEVEL4 },
4333 { '5', ACTION_RUNLEVEL5 },
4334 { 's', ACTION_RESCUE },
4335 { 'S', ACTION_RESCUE },
4336 { 'q', ACTION_RELOAD },
4337 { 'Q', ACTION_RELOAD },
4338 { 'u', ACTION_REEXEC },
4339 { 'U', ACTION_REEXEC }
4348 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4363 log_error("Unknown option code %c", c);
4368 if (optind >= argc) {
4373 if (optind + 1 < argc) {
4374 log_error("Too many arguments.");
4378 if (strlen(argv[optind]) != 1) {
4379 log_error("Expected single character argument.");
4383 for (i = 0; i < ELEMENTSOF(table); i++)
4384 if (table[i].from == argv[optind][0])
4387 if (i >= ELEMENTSOF(table)) {
4388 log_error("Unknown command %s.", argv[optind]);
4392 arg_action = table[i].to;
4399 static int runlevel_parse_argv(int argc, char *argv[]) {
4405 static const struct option options[] = {
4406 { "help", no_argument, NULL, ARG_HELP },
4407 { NULL, 0, NULL, 0 }
4415 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4426 log_error("Unknown option code %c", c);
4431 if (optind < argc) {
4432 log_error("Too many arguments.");
4439 static int parse_argv(int argc, char *argv[]) {
4443 if (program_invocation_short_name) {
4445 if (strstr(program_invocation_short_name, "halt")) {
4446 arg_action = ACTION_HALT;
4447 return halt_parse_argv(argc, argv);
4448 } else if (strstr(program_invocation_short_name, "poweroff")) {
4449 arg_action = ACTION_POWEROFF;
4450 return halt_parse_argv(argc, argv);
4451 } else if (strstr(program_invocation_short_name, "reboot")) {
4452 arg_action = ACTION_REBOOT;
4453 return halt_parse_argv(argc, argv);
4454 } else if (strstr(program_invocation_short_name, "shutdown")) {
4455 arg_action = ACTION_POWEROFF;
4456 return shutdown_parse_argv(argc, argv);
4457 } else if (strstr(program_invocation_short_name, "init")) {
4459 if (sd_booted() > 0) {
4460 arg_action = ACTION_INVALID;
4461 return telinit_parse_argv(argc, argv);
4463 /* Hmm, so some other init system is
4464 * running, we need to forward this
4465 * request to it. For now we simply
4466 * guess that it is Upstart. */
4468 execv("/lib/upstart/telinit", argv);
4470 log_error("Couldn't find an alternative telinit implementation to spawn.");
4474 } else if (strstr(program_invocation_short_name, "runlevel")) {
4475 arg_action = ACTION_RUNLEVEL;
4476 return runlevel_parse_argv(argc, argv);
4480 arg_action = ACTION_SYSTEMCTL;
4481 return systemctl_parse_argv(argc, argv);
4484 static int action_to_runlevel(void) {
4486 static const char table[_ACTION_MAX] = {
4487 [ACTION_HALT] = '0',
4488 [ACTION_POWEROFF] = '0',
4489 [ACTION_REBOOT] = '6',
4490 [ACTION_RUNLEVEL2] = '2',
4491 [ACTION_RUNLEVEL3] = '3',
4492 [ACTION_RUNLEVEL4] = '4',
4493 [ACTION_RUNLEVEL5] = '5',
4494 [ACTION_RESCUE] = '1'
4497 assert(arg_action < _ACTION_MAX);
4499 return table[arg_action];
4502 static int talk_upstart(void) {
4503 DBusMessage *m = NULL, *reply = NULL;
4505 int previous, rl, r;
4507 env1_buf[] = "RUNLEVEL=X",
4508 env2_buf[] = "PREVLEVEL=X";
4509 char *env1 = env1_buf, *env2 = env2_buf;
4510 const char *emit = "runlevel";
4511 dbus_bool_t b_false = FALSE;
4512 DBusMessageIter iter, sub;
4513 DBusConnection *bus;
4515 dbus_error_init(&error);
4517 if (!(rl = action_to_runlevel()))
4520 if (utmp_get_runlevel(&previous, NULL) < 0)
4523 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4524 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4529 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4534 if ((r = bus_check_peercred(bus)) < 0) {
4535 log_error("Failed to verify owner of bus.");
4539 if (!(m = dbus_message_new_method_call(
4540 "com.ubuntu.Upstart",
4541 "/com/ubuntu/Upstart",
4542 "com.ubuntu.Upstart0_6",
4545 log_error("Could not allocate message.");
4550 dbus_message_iter_init_append(m, &iter);
4552 env1_buf[sizeof(env1_buf)-2] = rl;
4553 env2_buf[sizeof(env2_buf)-2] = previous;
4555 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4556 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4557 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4558 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4559 !dbus_message_iter_close_container(&iter, &sub) ||
4560 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4561 log_error("Could not append arguments to message.");
4566 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4568 if (error_is_no_service(&error)) {
4573 log_error("Failed to issue method call: %s", bus_error_message(&error));
4582 dbus_message_unref(m);
4585 dbus_message_unref(reply);
4588 dbus_connection_close(bus);
4589 dbus_connection_unref(bus);
4592 dbus_error_free(&error);
4597 static int talk_initctl(void) {
4598 struct init_request request;
4602 if (!(rl = action_to_runlevel()))
4606 request.magic = INIT_MAGIC;
4607 request.sleeptime = 0;
4608 request.cmd = INIT_CMD_RUNLVL;
4609 request.runlevel = rl;
4611 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4613 if (errno == ENOENT)
4616 log_error("Failed to open "INIT_FIFO": %m");
4621 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4622 close_nointr_nofail(fd);
4625 log_error("Failed to write to "INIT_FIFO": %m");
4626 return errno ? -errno : -EIO;
4632 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4634 static const struct {
4642 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4644 { "list-units", LESS, 1, list_units },
4645 { "list-jobs", EQUAL, 1, list_jobs },
4646 { "clear-jobs", EQUAL, 1, daemon_reload },
4647 { "load", MORE, 2, load_unit },
4648 { "cancel", MORE, 2, cancel_job },
4649 { "start", MORE, 2, start_unit },
4650 { "stop", MORE, 2, start_unit },
4651 { "reload", MORE, 2, start_unit },
4652 { "restart", MORE, 2, start_unit },
4653 { "try-restart", MORE, 2, start_unit },
4654 { "reload-or-restart", MORE, 2, start_unit },
4655 { "reload-or-try-restart", MORE, 2, start_unit },
4656 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4657 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4658 { "isolate", EQUAL, 2, start_unit },
4659 { "is-active", MORE, 2, check_unit },
4660 { "check", MORE, 2, check_unit },
4661 { "show", MORE, 1, show },
4662 { "status", MORE, 2, show },
4663 { "monitor", EQUAL, 1, monitor },
4664 { "dump", EQUAL, 1, dump },
4665 { "dot", EQUAL, 1, dot },
4666 { "snapshot", LESS, 2, snapshot },
4667 { "delete", MORE, 2, delete_snapshot },
4668 { "daemon-reload", EQUAL, 1, daemon_reload },
4669 { "daemon-reexec", EQUAL, 1, daemon_reload },
4670 { "daemon-exit", EQUAL, 1, daemon_reload },
4671 { "show-environment", EQUAL, 1, show_enviroment },
4672 { "set-environment", MORE, 2, set_environment },
4673 { "unset-environment", MORE, 2, set_environment },
4674 { "halt", EQUAL, 1, start_special },
4675 { "poweroff", EQUAL, 1, start_special },
4676 { "reboot", EQUAL, 1, start_special },
4677 { "default", EQUAL, 1, start_special },
4678 { "rescue", EQUAL, 1, start_special },
4679 { "emergency", EQUAL, 1, start_special },
4680 { "reset-maintenance", MORE, 1, reset_maintenance },
4681 { "enable", MORE, 2, enable_unit },
4682 { "disable", MORE, 2, enable_unit },
4683 { "is-enabled", MORE, 2, enable_unit }
4693 left = argc - optind;
4696 /* Special rule: no arguments means "list-units" */
4699 if (streq(argv[optind], "help")) {
4704 for (i = 0; i < ELEMENTSOF(verbs); i++)
4705 if (streq(argv[optind], verbs[i].verb))
4708 if (i >= ELEMENTSOF(verbs)) {
4709 log_error("Unknown operation %s", argv[optind]);
4714 switch (verbs[i].argc_cmp) {
4717 if (left != verbs[i].argc) {
4718 log_error("Invalid number of arguments.");
4725 if (left < verbs[i].argc) {
4726 log_error("Too few arguments.");
4733 if (left > verbs[i].argc) {
4734 log_error("Too many arguments.");
4741 assert_not_reached("Unknown comparison operator.");
4744 /* Require a bus connection for all operations but
4746 if (!streq(verbs[i].verb, "enable") &&
4747 !streq(verbs[i].verb, "disable") &&
4749 log_error("Failed to get D-Bus connection: %s", error->message);
4753 return verbs[i].dispatch(bus, argv + optind, left);
4756 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
4758 struct msghdr msghdr;
4760 union sockaddr_union sockaddr;
4761 struct ucred *ucred;
4763 struct cmsghdr cmsghdr;
4764 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
4766 struct shutdownd_command c;
4774 strncpy(c.wall_message, message, sizeof(c.wall_message));
4776 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4780 sockaddr.sa.sa_family = AF_UNIX;
4781 sockaddr.un.sun_path[0] = 0;
4782 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
4785 iovec.iov_base = (char*) &c;
4786 iovec.iov_len = sizeof(c);
4789 control.cmsghdr.cmsg_level = SOL_SOCKET;
4790 control.cmsghdr.cmsg_type = SCM_CREDENTIALS;
4791 control.cmsghdr.cmsg_len = CMSG_LEN(sizeof(struct ucred));
4793 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
4794 ucred->pid = getpid();
4795 ucred->uid = getuid();
4796 ucred->gid = getgid();
4799 msghdr.msg_name = &sockaddr;
4800 msghdr.msg_namelen = sizeof(sa_family_t) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
4802 msghdr.msg_iov = &iovec;
4803 msghdr.msg_iovlen = 1;
4804 msghdr.msg_control = &control;
4805 msghdr.msg_controllen = control.cmsghdr.cmsg_len;
4807 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
4808 close_nointr_nofail(fd);
4812 close_nointr_nofail(fd);
4816 static int reload_with_fallback(DBusConnection *bus) {
4819 /* First, try systemd via D-Bus. */
4820 if (daemon_reload(bus, NULL, 0) > 0)
4824 /* Nothing else worked, so let's try signals */
4825 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
4827 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
4828 log_error("kill() failed: %m");
4835 static int start_with_fallback(DBusConnection *bus) {
4838 /* First, try systemd via D-Bus. */
4839 if (start_unit(bus, NULL, 0) > 0)
4843 /* Hmm, talking to systemd via D-Bus didn't work. Then
4844 * let's try to talk to Upstart via D-Bus. */
4845 if (talk_upstart() > 0)
4848 /* Nothing else worked, so let's try
4850 if (talk_initctl() > 0)
4853 log_error("Failed to talk to init daemon.");
4857 warn_wall(arg_action);
4861 static int halt_main(DBusConnection *bus) {
4864 if (geteuid() != 0) {
4865 log_error("Must to be root.");
4871 char date[FORMAT_TIMESTAMP_MAX];
4873 m = strv_join(arg_wall, " ");
4874 r = send_shutdownd(arg_when,
4875 arg_action == ACTION_HALT ? 'H' :
4876 arg_action == ACTION_POWEROFF ? 'P' :
4883 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
4885 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
4886 format_timestamp(date, sizeof(date), arg_when));
4891 if (!arg_dry && !arg_immediate)
4892 return start_with_fallback(bus);
4895 if (sd_booted() > 0)
4896 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
4897 else if ((r = utmp_put_shutdown(0)) < 0)
4898 log_warning("Failed to write utmp record: %s", strerror(-r));
4907 /* Make sure C-A-D is handled by the kernel from this
4909 reboot(RB_ENABLE_CAD);
4911 switch (arg_action) {
4914 log_info("Halting.");
4915 reboot(RB_HALT_SYSTEM);
4918 case ACTION_POWEROFF:
4919 log_info("Powering off.");
4920 reboot(RB_POWER_OFF);
4924 log_info("Rebooting.");
4925 reboot(RB_AUTOBOOT);
4929 assert_not_reached("Unknown halt action.");
4932 /* We should never reach this. */
4936 static int runlevel_main(void) {
4937 int r, runlevel, previous;
4939 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
4940 printf("unknown\n");
4945 previous <= 0 ? 'N' : previous,
4946 runlevel <= 0 ? 'N' : runlevel);
4951 int main(int argc, char*argv[]) {
4953 DBusConnection *bus = NULL;
4956 dbus_error_init(&error);
4958 log_parse_environment();
4961 if ((r = parse_argv(argc, argv)) < 0)
4968 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
4969 * let's shortcut this */
4970 if (arg_action == ACTION_RUNLEVEL) {
4971 retval = runlevel_main() < 0;
4975 bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
4977 switch (arg_action) {
4979 case ACTION_SYSTEMCTL: {
4980 retval = systemctl_main(bus, argc, argv, &error) < 0;
4985 case ACTION_POWEROFF:
4987 retval = halt_main(bus) < 0;
4990 case ACTION_RUNLEVEL2:
4991 case ACTION_RUNLEVEL3:
4992 case ACTION_RUNLEVEL4:
4993 case ACTION_RUNLEVEL5:
4995 case ACTION_EMERGENCY:
4996 case ACTION_DEFAULT:
4997 retval = start_with_fallback(bus) < 0;
5002 retval = reload_with_fallback(bus) < 0;
5005 case ACTION_CANCEL_SHUTDOWN:
5006 retval = send_shutdownd(0, 0, false, NULL) < 0;
5009 case ACTION_INVALID:
5010 case ACTION_RUNLEVEL:
5012 assert_not_reached("Unknown action");
5018 dbus_connection_close(bus);
5019 dbus_connection_unref(bus);
5022 dbus_error_free(&error);
5026 strv_free(arg_property);