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", error.message);
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", error.message);
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", error.message);
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", error.message);
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", error.message);
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", error.message);
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", error.message);
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", error.message);
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", error.message);
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", error.message);
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", error.message);
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", error.message);
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", error.message);
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", error.message);
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 bool need_daemon_reload;
1497 const char *status_text;
1501 usec_t start_timestamp;
1502 usec_t exit_timestamp;
1504 int exit_code, exit_status;
1507 unsigned n_accepted;
1508 unsigned n_connections;
1512 const char *sysfs_path;
1514 /* Mount, Automount */
1520 LIST_HEAD(ExecStatusInfo, exec);
1523 static void print_status_info(UnitStatusInfo *i) {
1525 const char *on, *off, *ss;
1529 /* This shows pretty information about a unit. See
1530 * print_property() for a low-level property printer */
1532 printf("%s", strna(i->id));
1534 if (i->description && !streq_ptr(i->id, i->description))
1535 printf(" - %s", i->description);
1539 if (streq_ptr(i->load_state, "failed")) {
1540 on = ansi_highlight(true);
1541 off = ansi_highlight(false);
1546 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1548 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1550 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1552 if (streq_ptr(i->active_state, "maintenance")) {
1553 on = ansi_highlight(true);
1554 off = ansi_highlight(false);
1555 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1556 on = ansi_highlight_green(true);
1557 off = ansi_highlight_green(false);
1562 printf("\t Active: %s%s (%s)%s\n",
1564 strna(i->active_state),
1568 printf("\t Active: %s%s%s\n",
1570 strna(i->active_state),
1574 printf("\t Device: %s\n", i->sysfs_path);
1576 printf("\t Where: %s\n", i->where);
1578 printf("\t What: %s\n", i->what);
1581 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1583 LIST_FOREACH(exec, p, i->exec) {
1586 /* Only show exited processes here */
1590 t = strv_join(p->argv, " ");
1591 printf("\t Exited: %u (%s, code=%s, ", p->pid, strna(t), sigchld_code_to_string(p->code));
1594 if (p->code == CLD_EXITED) {
1597 printf("status=%i", p->status);
1599 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1603 printf("signal=%s", signal_to_string(p->status));
1606 if (i->main_pid == p->pid &&
1607 i->start_timestamp == p->start_timestamp &&
1608 i->exit_timestamp == p->start_timestamp)
1609 /* Let's not show this twice */
1612 if (p->pid == i->control_pid)
1616 if (i->main_pid > 0 || i->control_pid > 0) {
1619 if (i->main_pid > 0) {
1620 printf(" Main: %u", (unsigned) i->main_pid);
1624 get_process_name(i->main_pid, &t);
1629 } else if (i->exit_code > 0) {
1630 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1632 if (i->exit_code == CLD_EXITED) {
1635 printf("status=%i", i->exit_status);
1637 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1641 printf("signal=%s", signal_to_string(i->exit_status));
1646 if (i->main_pid > 0 && i->control_pid > 0)
1649 if (i->control_pid > 0) {
1652 printf(" Control: %u", (unsigned) i->control_pid);
1654 get_process_name(i->control_pid, &t);
1665 printf("\t Status: \"%s\"\n", i->status_text);
1667 if (i->default_control_group) {
1670 printf("\t CGroup: %s\n", i->default_control_group);
1672 if ((c = columns()) > 18)
1677 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
1680 if (i->need_daemon_reload)
1681 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1682 ansi_highlight(true),
1683 ansi_highlight(false),
1684 arg_session ? "--session" : "--system");
1687 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1689 switch (dbus_message_iter_get_arg_type(iter)) {
1691 case DBUS_TYPE_STRING: {
1694 dbus_message_iter_get_basic(iter, &s);
1697 if (streq(name, "Id"))
1699 else if (streq(name, "LoadState"))
1701 else if (streq(name, "ActiveState"))
1702 i->active_state = s;
1703 else if (streq(name, "SubState"))
1705 else if (streq(name, "Description"))
1707 else if (streq(name, "FragmentPath"))
1709 else if (streq(name, "SysVPath")) {
1712 } else if (streq(name, "DefaultControlGroup"))
1713 i->default_control_group = s;
1714 else if (streq(name, "StatusText"))
1716 else if (streq(name, "SysFSPath"))
1718 else if (streq(name, "Where"))
1720 else if (streq(name, "What"))
1727 case DBUS_TYPE_BOOLEAN: {
1730 dbus_message_iter_get_basic(iter, &b);
1732 if (streq(name, "Accept"))
1734 else if (streq(name, "NeedDaemonReload"))
1735 i->need_daemon_reload = b;
1740 case DBUS_TYPE_UINT32: {
1743 dbus_message_iter_get_basic(iter, &u);
1745 if (streq(name, "MainPID")) {
1747 i->main_pid = (pid_t) u;
1750 } else if (streq(name, "ControlPID"))
1751 i->control_pid = (pid_t) u;
1752 else if (streq(name, "ExecMainPID")) {
1754 i->main_pid = (pid_t) u;
1755 } else if (streq(name, "NAccepted"))
1757 else if (streq(name, "NConnections"))
1758 i->n_connections = u;
1763 case DBUS_TYPE_INT32: {
1766 dbus_message_iter_get_basic(iter, &j);
1768 if (streq(name, "ExecMainCode"))
1769 i->exit_code = (int) j;
1770 else if (streq(name, "ExecMainStatus"))
1771 i->exit_status = (int) j;
1776 case DBUS_TYPE_UINT64: {
1779 dbus_message_iter_get_basic(iter, &u);
1781 if (streq(name, "ExecMainStartTimestamp"))
1782 i->start_timestamp = (usec_t) u;
1783 else if (streq(name, "ExecMainExitTimestamp"))
1784 i->exit_timestamp = (usec_t) u;
1789 case DBUS_TYPE_ARRAY: {
1791 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
1792 startswith(name, "Exec")) {
1793 DBusMessageIter sub;
1795 dbus_message_iter_recurse(iter, &sub);
1796 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1797 ExecStatusInfo *info;
1800 if (!(info = new0(ExecStatusInfo, 1)))
1803 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
1808 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
1810 dbus_message_iter_next(&sub);
1821 static int print_property(const char *name, DBusMessageIter *iter) {
1825 /* This is a low-level property printer, see
1826 * print_status_info() for the nicer output */
1828 if (arg_property && !strv_find(arg_property, name))
1831 switch (dbus_message_iter_get_arg_type(iter)) {
1833 case DBUS_TYPE_STRING: {
1835 dbus_message_iter_get_basic(iter, &s);
1837 if (arg_all || s[0])
1838 printf("%s=%s\n", name, s);
1843 case DBUS_TYPE_BOOLEAN: {
1845 dbus_message_iter_get_basic(iter, &b);
1846 printf("%s=%s\n", name, yes_no(b));
1851 case DBUS_TYPE_UINT64: {
1853 dbus_message_iter_get_basic(iter, &u);
1855 /* Yes, heuristics! But we can change this check
1856 * should it turn out to not be sufficient */
1858 if (strstr(name, "Timestamp")) {
1859 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
1861 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
1862 printf("%s=%s\n", name, strempty(t));
1863 } else if (strstr(name, "USec")) {
1864 char timespan[FORMAT_TIMESPAN_MAX];
1866 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
1868 printf("%s=%llu\n", name, (unsigned long long) u);
1873 case DBUS_TYPE_UINT32: {
1875 dbus_message_iter_get_basic(iter, &u);
1877 if (strstr(name, "UMask") || strstr(name, "Mode"))
1878 printf("%s=%04o\n", name, u);
1880 printf("%s=%u\n", name, (unsigned) u);
1885 case DBUS_TYPE_INT32: {
1887 dbus_message_iter_get_basic(iter, &i);
1889 printf("%s=%i\n", name, (int) i);
1893 case DBUS_TYPE_STRUCT: {
1894 DBusMessageIter sub;
1895 dbus_message_iter_recurse(iter, &sub);
1897 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
1900 dbus_message_iter_get_basic(&sub, &u);
1903 printf("%s=%u\n", name, (unsigned) u);
1905 printf("%s=\n", name);
1908 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
1911 dbus_message_iter_get_basic(&sub, &s);
1913 if (arg_all || s[0])
1914 printf("%s=%s\n", name, s);
1922 case DBUS_TYPE_ARRAY:
1924 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
1925 DBusMessageIter sub;
1928 dbus_message_iter_recurse(iter, &sub);
1930 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1931 printf("%s=", name);
1933 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1936 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
1937 dbus_message_iter_get_basic(&sub, &s);
1938 printf("%s%s", space ? " " : "", s);
1941 dbus_message_iter_next(&sub);
1949 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
1950 DBusMessageIter sub;
1952 dbus_message_iter_recurse(iter, &sub);
1954 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1955 printf("%s=", name);
1957 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1960 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
1961 dbus_message_iter_get_basic(&sub, &u);
1964 dbus_message_iter_next(&sub);
1972 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
1973 DBusMessageIter sub, sub2;
1975 dbus_message_iter_recurse(iter, &sub);
1976 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1977 const char *type, *path;
1979 dbus_message_iter_recurse(&sub, &sub2);
1981 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
1982 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
1983 printf("%s=%s\n", type, path);
1985 dbus_message_iter_next(&sub);
1990 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
1991 DBusMessageIter sub, sub2;
1993 dbus_message_iter_recurse(iter, &sub);
1994 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1996 uint64_t value, next_elapse;
1998 dbus_message_iter_recurse(&sub, &sub2);
2000 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2001 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2002 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2003 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2005 printf("%s={ value=%s ; next_elapse=%s }\n",
2007 format_timespan(timespan1, sizeof(timespan1), value),
2008 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2011 dbus_message_iter_next(&sub);
2016 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2017 DBusMessageIter sub;
2019 dbus_message_iter_recurse(iter, &sub);
2020 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2021 ExecStatusInfo info;
2024 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2025 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2028 t = strv_join(info.argv, " ");
2030 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2034 yes_no(info.ignore),
2035 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2036 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2037 (unsigned) info. pid,
2038 sigchld_code_to_string(info.code),
2040 info.code == CLD_EXITED ? "" : "/",
2041 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2047 strv_free(info.argv);
2049 dbus_message_iter_next(&sub);
2059 printf("%s=[unprintable]\n", name);
2064 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2065 DBusMessage *m = NULL, *reply = NULL;
2066 const char *interface = "";
2069 DBusMessageIter iter, sub, sub2, sub3;
2070 UnitStatusInfo info;
2078 dbus_error_init(&error);
2080 if (!(m = dbus_message_new_method_call(
2081 "org.freedesktop.systemd1",
2083 "org.freedesktop.DBus.Properties",
2085 log_error("Could not allocate message.");
2090 if (!dbus_message_append_args(m,
2091 DBUS_TYPE_STRING, &interface,
2092 DBUS_TYPE_INVALID)) {
2093 log_error("Could not append arguments to message.");
2098 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2099 log_error("Failed to issue method call: %s", error.message);
2104 if (!dbus_message_iter_init(reply, &iter) ||
2105 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2106 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2107 log_error("Failed to parse reply.");
2112 dbus_message_iter_recurse(&iter, &sub);
2119 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2122 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2123 log_error("Failed to parse reply.");
2128 dbus_message_iter_recurse(&sub, &sub2);
2130 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2131 log_error("Failed to parse reply.");
2136 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2137 log_error("Failed to parse reply.");
2142 dbus_message_iter_recurse(&sub2, &sub3);
2144 if (show_properties)
2145 r = print_property(name, &sub3);
2147 r = status_property(name, &sub3, &info);
2150 log_error("Failed to parse reply.");
2155 dbus_message_iter_next(&sub);
2160 if (!show_properties) {
2161 if (arg_sysv_compat &&
2162 !streq_ptr(info.active_state, "active") &&
2163 !streq_ptr(info.active_state, "reloading")) {
2165 /* If the SysV compatibility mode is on, we
2166 * will refuse to run "status" on units that
2168 log_error("Unit not active.");
2171 print_status_info(&info);
2174 while ((p = info.exec)) {
2175 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2176 exec_status_info_free(p);
2181 dbus_message_unref(m);
2184 dbus_message_unref(reply);
2186 dbus_error_free(&error);
2191 static int show(DBusConnection *bus, char **args, unsigned n) {
2192 DBusMessage *m = NULL, *reply = NULL;
2196 bool show_properties, new_line = false;
2201 dbus_error_init(&error);
2203 show_properties = !streq(args[0], "status");
2205 if (show_properties && n <= 1) {
2206 /* If not argument is specified inspect the manager
2209 r = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2213 for (i = 1; i < n; i++) {
2214 const char *path = NULL;
2217 if (safe_atou32(args[i], &id) < 0) {
2219 /* Interpret as unit name */
2221 if (!(m = dbus_message_new_method_call(
2222 "org.freedesktop.systemd1",
2223 "/org/freedesktop/systemd1",
2224 "org.freedesktop.systemd1.Manager",
2226 log_error("Could not allocate message.");
2231 if (!dbus_message_append_args(m,
2232 DBUS_TYPE_STRING, &args[i],
2233 DBUS_TYPE_INVALID)) {
2234 log_error("Could not append arguments to message.");
2239 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2241 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2242 log_error("Failed to issue method call: %s", error.message);
2247 dbus_error_free(&error);
2249 dbus_message_unref(m);
2250 if (!(m = dbus_message_new_method_call(
2251 "org.freedesktop.systemd1",
2252 "/org/freedesktop/systemd1",
2253 "org.freedesktop.systemd1.Manager",
2255 log_error("Could not allocate message.");
2260 if (!dbus_message_append_args(m,
2261 DBUS_TYPE_STRING, &args[i],
2262 DBUS_TYPE_INVALID)) {
2263 log_error("Could not append arguments to message.");
2268 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2269 log_error("Failed to issue method call: %s", error.message);
2275 } else if (show_properties) {
2277 /* Interpret as job id */
2279 if (!(m = dbus_message_new_method_call(
2280 "org.freedesktop.systemd1",
2281 "/org/freedesktop/systemd1",
2282 "org.freedesktop.systemd1.Manager",
2284 log_error("Could not allocate message.");
2289 if (!dbus_message_append_args(m,
2290 DBUS_TYPE_UINT32, &id,
2291 DBUS_TYPE_INVALID)) {
2292 log_error("Could not append arguments to message.");
2297 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2298 log_error("Failed to issue method call: %s", error.message);
2304 /* Interpret as PID */
2306 if (!(m = dbus_message_new_method_call(
2307 "org.freedesktop.systemd1",
2308 "/org/freedesktop/systemd1",
2309 "org.freedesktop.systemd1.Manager",
2311 log_error("Could not allocate message.");
2316 if (!dbus_message_append_args(m,
2317 DBUS_TYPE_UINT32, &id,
2318 DBUS_TYPE_INVALID)) {
2319 log_error("Could not append arguments to message.");
2324 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2325 log_error("Failed to issue method call: %s", error.message);
2331 if (!dbus_message_get_args(reply, &error,
2332 DBUS_TYPE_OBJECT_PATH, &path,
2333 DBUS_TYPE_INVALID)) {
2334 log_error("Failed to parse reply: %s", error.message);
2339 if ((r = show_one(bus, path, show_properties, &new_line)) < 0)
2342 dbus_message_unref(m);
2343 dbus_message_unref(reply);
2351 dbus_message_unref(m);
2354 dbus_message_unref(reply);
2356 dbus_error_free(&error);
2361 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2363 DBusMessage *m = NULL, *reply = NULL;
2368 dbus_error_init(&error);
2370 log_debug("Got D-Bus request: %s.%s() on %s",
2371 dbus_message_get_interface(message),
2372 dbus_message_get_member(message),
2373 dbus_message_get_path(message));
2375 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2376 log_error("Warning! D-Bus connection terminated.");
2377 dbus_connection_close(connection);
2379 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2380 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2381 const char *id, *path;
2383 if (!dbus_message_get_args(message, &error,
2384 DBUS_TYPE_STRING, &id,
2385 DBUS_TYPE_OBJECT_PATH, &path,
2387 log_error("Failed to parse message: %s", error.message);
2388 else if (streq(dbus_message_get_member(message), "UnitNew"))
2389 printf("Unit %s added.\n", id);
2391 printf("Unit %s removed.\n", id);
2393 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2394 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2398 if (!dbus_message_get_args(message, &error,
2399 DBUS_TYPE_UINT32, &id,
2400 DBUS_TYPE_OBJECT_PATH, &path,
2402 log_error("Failed to parse message: %s", error.message);
2403 else if (streq(dbus_message_get_member(message), "JobNew"))
2404 printf("Job %u added.\n", id);
2406 printf("Job %u removed.\n", id);
2409 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2411 const char *path, *interface, *property = "Id";
2412 DBusMessageIter iter, sub;
2414 path = dbus_message_get_path(message);
2416 if (!dbus_message_get_args(message, &error,
2417 DBUS_TYPE_STRING, &interface,
2418 DBUS_TYPE_INVALID)) {
2419 log_error("Failed to parse message: %s", error.message);
2423 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2424 !streq(interface, "org.freedesktop.systemd1.Unit"))
2427 if (!(m = dbus_message_new_method_call(
2428 "org.freedesktop.systemd1",
2430 "org.freedesktop.DBus.Properties",
2432 log_error("Could not allocate message.");
2436 if (!dbus_message_append_args(m,
2437 DBUS_TYPE_STRING, &interface,
2438 DBUS_TYPE_STRING, &property,
2439 DBUS_TYPE_INVALID)) {
2440 log_error("Could not append arguments to message.");
2444 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2445 log_error("Failed to issue method call: %s", error.message);
2449 if (!dbus_message_iter_init(reply, &iter) ||
2450 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2451 log_error("Failed to parse reply.");
2455 dbus_message_iter_recurse(&iter, &sub);
2457 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2460 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2461 log_error("Failed to parse reply.");
2465 dbus_message_iter_get_basic(&sub, &id);
2466 printf("Unit %s changed.\n", id);
2470 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2471 log_error("Failed to parse reply.");
2475 dbus_message_iter_get_basic(&sub, &id);
2476 printf("Job %u changed.\n", id);
2482 dbus_message_unref(m);
2485 dbus_message_unref(reply);
2487 dbus_error_free(&error);
2488 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2492 dbus_message_unref(m);
2495 dbus_message_unref(reply);
2497 dbus_error_free(&error);
2498 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2501 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2502 DBusMessage *m = NULL, *reply = NULL;
2506 dbus_error_init(&error);
2509 dbus_bus_add_match(bus,
2511 "sender='org.freedesktop.systemd1',"
2512 "interface='org.freedesktop.systemd1.Manager',"
2513 "path='/org/freedesktop/systemd1'",
2516 if (dbus_error_is_set(&error)) {
2517 log_error("Failed to add match: %s", error.message);
2522 dbus_bus_add_match(bus,
2524 "sender='org.freedesktop.systemd1',"
2525 "interface='org.freedesktop.DBus.Properties',"
2526 "member='PropertiesChanged'",
2529 if (dbus_error_is_set(&error)) {
2530 log_error("Failed to add match: %s", error.message);
2536 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2537 log_error("Failed to add filter.");
2542 if (!(m = dbus_message_new_method_call(
2543 "org.freedesktop.systemd1",
2544 "/org/freedesktop/systemd1",
2545 "org.freedesktop.systemd1.Manager",
2547 log_error("Could not allocate message.");
2552 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2553 log_error("Failed to issue method call: %s", error.message);
2558 while (dbus_connection_read_write_dispatch(bus, -1))
2565 /* This is slightly dirty, since we don't undo the filter or the matches. */
2568 dbus_message_unref(m);
2571 dbus_message_unref(reply);
2573 dbus_error_free(&error);
2578 static int dump(DBusConnection *bus, char **args, unsigned n) {
2579 DBusMessage *m = NULL, *reply = NULL;
2584 dbus_error_init(&error);
2586 if (!(m = dbus_message_new_method_call(
2587 "org.freedesktop.systemd1",
2588 "/org/freedesktop/systemd1",
2589 "org.freedesktop.systemd1.Manager",
2591 log_error("Could not allocate message.");
2595 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2596 log_error("Failed to issue method call: %s", error.message);
2601 if (!dbus_message_get_args(reply, &error,
2602 DBUS_TYPE_STRING, &text,
2603 DBUS_TYPE_INVALID)) {
2604 log_error("Failed to parse reply: %s", error.message);
2609 fputs(text, stdout);
2615 dbus_message_unref(m);
2618 dbus_message_unref(reply);
2620 dbus_error_free(&error);
2625 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2626 DBusMessage *m = NULL, *reply = NULL;
2629 const char *name = "", *path, *id;
2630 dbus_bool_t cleanup = FALSE;
2631 DBusMessageIter iter, sub;
2633 *interface = "org.freedesktop.systemd1.Unit",
2636 dbus_error_init(&error);
2638 if (!(m = dbus_message_new_method_call(
2639 "org.freedesktop.systemd1",
2640 "/org/freedesktop/systemd1",
2641 "org.freedesktop.systemd1.Manager",
2642 "CreateSnapshot"))) {
2643 log_error("Could not allocate message.");
2650 if (!dbus_message_append_args(m,
2651 DBUS_TYPE_STRING, &name,
2652 DBUS_TYPE_BOOLEAN, &cleanup,
2653 DBUS_TYPE_INVALID)) {
2654 log_error("Could not append arguments to message.");
2659 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2660 log_error("Failed to issue method call: %s", error.message);
2665 if (!dbus_message_get_args(reply, &error,
2666 DBUS_TYPE_OBJECT_PATH, &path,
2667 DBUS_TYPE_INVALID)) {
2668 log_error("Failed to parse reply: %s", error.message);
2673 dbus_message_unref(m);
2674 if (!(m = dbus_message_new_method_call(
2675 "org.freedesktop.systemd1",
2677 "org.freedesktop.DBus.Properties",
2679 log_error("Could not allocate message.");
2683 if (!dbus_message_append_args(m,
2684 DBUS_TYPE_STRING, &interface,
2685 DBUS_TYPE_STRING, &property,
2686 DBUS_TYPE_INVALID)) {
2687 log_error("Could not append arguments to message.");
2692 dbus_message_unref(reply);
2693 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2694 log_error("Failed to issue method call: %s", error.message);
2699 if (!dbus_message_iter_init(reply, &iter) ||
2700 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2701 log_error("Failed to parse reply.");
2706 dbus_message_iter_recurse(&iter, &sub);
2708 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2709 log_error("Failed to parse reply.");
2714 dbus_message_iter_get_basic(&sub, &id);
2722 dbus_message_unref(m);
2725 dbus_message_unref(reply);
2727 dbus_error_free(&error);
2732 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2733 DBusMessage *m = NULL, *reply = NULL;
2741 dbus_error_init(&error);
2743 for (i = 1; i < n; i++) {
2744 const char *path = NULL;
2746 if (!(m = dbus_message_new_method_call(
2747 "org.freedesktop.systemd1",
2748 "/org/freedesktop/systemd1",
2749 "org.freedesktop.systemd1.Manager",
2751 log_error("Could not allocate message.");
2756 if (!dbus_message_append_args(m,
2757 DBUS_TYPE_STRING, &args[i],
2758 DBUS_TYPE_INVALID)) {
2759 log_error("Could not append arguments to message.");
2764 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2765 log_error("Failed to issue method call: %s", error.message);
2770 if (!dbus_message_get_args(reply, &error,
2771 DBUS_TYPE_OBJECT_PATH, &path,
2772 DBUS_TYPE_INVALID)) {
2773 log_error("Failed to parse reply: %s", error.message);
2778 dbus_message_unref(m);
2779 if (!(m = dbus_message_new_method_call(
2780 "org.freedesktop.systemd1",
2782 "org.freedesktop.systemd1.Snapshot",
2784 log_error("Could not allocate message.");
2789 dbus_message_unref(reply);
2790 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2791 log_error("Failed to issue method call: %s", error.message);
2796 dbus_message_unref(m);
2797 dbus_message_unref(reply);
2805 dbus_message_unref(m);
2808 dbus_message_unref(reply);
2810 dbus_error_free(&error);
2815 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2816 DBusMessage *m = NULL, *reply = NULL;
2821 dbus_error_init(&error);
2823 if (arg_action == ACTION_RELOAD)
2825 else if (arg_action == ACTION_REEXEC)
2826 method = "Reexecute";
2828 assert(arg_action == ACTION_SYSTEMCTL);
2831 streq(args[0], "clear-jobs") ||
2832 streq(args[0], "cancel") ? "ClearJobs" :
2833 streq(args[0], "daemon-reexec") ? "Reexecute" :
2834 streq(args[0], "reset-maintenance") ? "ResetMaintenance" :
2835 streq(args[0], "daemon-exit") ? "Exit" :
2839 if (!(m = dbus_message_new_method_call(
2840 "org.freedesktop.systemd1",
2841 "/org/freedesktop/systemd1",
2842 "org.freedesktop.systemd1.Manager",
2844 log_error("Could not allocate message.");
2848 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2850 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
2851 /* There's always a fallback possible for
2852 * legacy actions. */
2857 log_error("Failed to issue method call: %s", error.message);
2866 dbus_message_unref(m);
2869 dbus_message_unref(reply);
2871 dbus_error_free(&error);
2876 static int reset_maintenance(DBusConnection *bus, char **args, unsigned n) {
2877 DBusMessage *m = NULL, *reply = NULL;
2883 dbus_error_init(&error);
2886 return daemon_reload(bus, args, n);
2888 for (i = 1; i < n; i++) {
2890 if (!(m = dbus_message_new_method_call(
2891 "org.freedesktop.systemd1",
2892 "/org/freedesktop/systemd1",
2893 "org.freedesktop.systemd1.Manager",
2894 "ResetMaintenanceUnit"))) {
2895 log_error("Could not allocate message.");
2900 if (!dbus_message_append_args(m,
2901 DBUS_TYPE_STRING, args + i,
2902 DBUS_TYPE_INVALID)) {
2903 log_error("Could not append arguments to message.");
2908 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2909 log_error("Failed to issue method call: %s", error.message);
2914 dbus_message_unref(m);
2915 dbus_message_unref(reply);
2923 dbus_message_unref(m);
2926 dbus_message_unref(reply);
2928 dbus_error_free(&error);
2933 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
2934 DBusMessage *m = NULL, *reply = NULL;
2936 DBusMessageIter iter, sub, sub2;
2939 *interface = "org.freedesktop.systemd1.Manager",
2940 *property = "Environment";
2942 dbus_error_init(&error);
2944 if (!(m = dbus_message_new_method_call(
2945 "org.freedesktop.systemd1",
2946 "/org/freedesktop/systemd1",
2947 "org.freedesktop.DBus.Properties",
2949 log_error("Could not allocate message.");
2953 if (!dbus_message_append_args(m,
2954 DBUS_TYPE_STRING, &interface,
2955 DBUS_TYPE_STRING, &property,
2956 DBUS_TYPE_INVALID)) {
2957 log_error("Could not append arguments to message.");
2962 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2963 log_error("Failed to issue method call: %s", error.message);
2968 if (!dbus_message_iter_init(reply, &iter) ||
2969 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2970 log_error("Failed to parse reply.");
2975 dbus_message_iter_recurse(&iter, &sub);
2977 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
2978 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
2979 log_error("Failed to parse reply.");
2984 dbus_message_iter_recurse(&sub, &sub2);
2986 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
2989 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
2990 log_error("Failed to parse reply.");
2995 dbus_message_iter_get_basic(&sub2, &text);
2996 printf("%s\n", text);
2998 dbus_message_iter_next(&sub2);
3005 dbus_message_unref(m);
3008 dbus_message_unref(reply);
3010 dbus_error_free(&error);
3015 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3016 DBusMessage *m = NULL, *reply = NULL;
3020 DBusMessageIter iter, sub;
3023 dbus_error_init(&error);
3025 method = streq(args[0], "set-environment")
3027 : "UnsetEnvironment";
3029 if (!(m = dbus_message_new_method_call(
3030 "org.freedesktop.systemd1",
3031 "/org/freedesktop/systemd1",
3032 "org.freedesktop.systemd1.Manager",
3035 log_error("Could not allocate message.");
3039 dbus_message_iter_init_append(m, &iter);
3041 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3042 log_error("Could not append arguments to message.");
3047 for (i = 1; i < n; i++)
3048 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3049 log_error("Could not append arguments to message.");
3054 if (!dbus_message_iter_close_container(&iter, &sub)) {
3055 log_error("Could not append arguments to message.");
3060 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3061 log_error("Failed to issue method call: %s", error.message);
3070 dbus_message_unref(m);
3073 dbus_message_unref(reply);
3075 dbus_error_free(&error);
3088 static Hashmap *will_install = NULL, *have_installed = NULL;
3089 static Set *remove_symlinks_to = NULL;
3091 static void install_info_free(InstallInfo *i) {
3096 strv_free(i->aliases);
3097 strv_free(i->wanted_by);
3101 static void install_info_hashmap_free(Hashmap *m) {
3104 while ((i = hashmap_steal_first(m)))
3105 install_info_free(i);
3110 static bool unit_name_valid(const char *name) {
3112 /* This is a minimal version of unit_name_valid() from
3118 if (ignore_file(name))
3124 static int install_info_add(const char *name) {
3128 assert(will_install);
3130 if (!unit_name_valid(name))
3133 if (hashmap_get(have_installed, name) ||
3134 hashmap_get(will_install, name))
3137 if (!(i = new0(InstallInfo, 1))) {
3142 if (!(i->name = strdup(name))) {
3147 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3154 install_info_free(i);
3159 static int config_parse_also(
3160 const char *filename,
3162 const char *section,
3176 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3180 if (!(n = strndup(w, l)))
3183 r = install_info_add(n);
3193 static int mark_symlink_for_removal(const char *p) {
3198 assert(path_is_absolute(p));
3200 if (!remove_symlinks_to)
3203 if (!(n = strdup(p)))
3206 path_kill_slashes(n);
3208 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3210 return r == -EEXIST ? 0 : r;
3216 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3225 if (!(d = fdopendir(fd))) {
3226 close_nointr_nofail(fd);
3232 while ((de = readdir(d))) {
3233 bool is_dir = false, is_link = false;
3235 if (ignore_file(de->d_name))
3238 if (de->d_type == DT_LNK)
3240 else if (de->d_type == DT_DIR)
3242 else if (de->d_type == DT_UNKNOWN) {
3245 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3246 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3253 is_link = S_ISLNK(st.st_mode);
3254 is_dir = S_ISDIR(st.st_mode);
3262 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3263 log_error("Failed to open %s/%s: %m", root, de->d_name);
3270 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3271 log_error("Failed to allocate directory string.");
3272 close_nointr_nofail(nfd);
3277 /* This will close nfd, regardless whether it succeeds or not */
3278 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3284 } else if (is_link) {
3288 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3289 log_error("Failed to allocate symlink string.");
3294 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3295 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3303 if ((c = canonicalize_file_name(dest))) {
3304 /* This might fail if the destination
3305 * is already removed */
3311 path_kill_slashes(dest);
3312 if (set_get(remove_symlinks_to, dest)) {
3315 log_info("rm '%s'", p);
3317 if (unlink(p) < 0) {
3318 log_error("Cannot unlink symlink %s: %m", p);
3323 rmdir_parents(p, config_path);
3324 path_kill_slashes(p);
3326 if (!set_get(remove_symlinks_to, p)) {
3328 if ((r = mark_symlink_for_removal(p)) < 0) {
3347 static int remove_marked_symlinks(const char *config_path) {
3351 assert(config_path);
3353 if (set_size(remove_symlinks_to) <= 0)
3356 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3363 if ((cfd = dup(fd)) < 0) {
3368 /* This takes possession of cfd and closes it */
3369 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3375 close_nointr_nofail(fd);
3380 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3387 if (streq(verb, "enable")) {
3390 mkdir_parents(new_path, 0755);
3392 if (symlink(old_path, new_path) >= 0) {
3395 log_info("ln -s '%s' '%s'", old_path, new_path);
3400 if (errno != EEXIST) {
3401 log_error("Cannot link %s to %s: %m", old_path, new_path);
3405 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3407 if (errno == EINVAL) {
3408 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3412 log_error("readlink() failed: %s", strerror(-r));
3416 if (streq(dest, old_path)) {
3422 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3431 log_info("ln -s '%s' '%s'", old_path, new_path);
3433 if (symlink(old_path, new_path) >= 0)
3436 log_error("Cannot link %s to %s: %m", old_path, new_path);
3439 } else if (streq(verb, "disable")) {
3442 if ((r = mark_symlink_for_removal(old_path)) < 0)
3445 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3446 if (errno == ENOENT)
3449 if (errno == EINVAL) {
3450 log_warning("File %s not a symlink, ignoring.", old_path);
3454 log_error("readlink() failed: %s", strerror(-r));
3458 if (!streq(dest, old_path)) {
3459 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3466 if ((r = mark_symlink_for_removal(new_path)) < 0)
3470 log_info("rm '%s'", new_path);
3472 if (unlink(new_path) >= 0)
3475 log_error("Cannot unlink %s: %m", new_path);
3478 } else if (streq(verb, "is-enabled")) {
3481 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3483 if (errno == ENOENT || errno == EINVAL)
3486 log_error("readlink() failed: %s", strerror(-r));
3490 if (streq(dest, old_path)) {
3498 assert_not_reached("Unknown action.");
3501 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3503 char *alias_path = NULL;
3508 assert(config_path);
3510 STRV_FOREACH(s, i->aliases) {
3512 if (!unit_name_valid(*s)) {
3513 log_error("Invalid name %s.", *s);
3519 if (!(alias_path = path_make_absolute(*s, config_path))) {
3520 log_error("Out of memory");
3525 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3528 if (streq(verb, "disable"))
3529 rmdir_parents(alias_path, config_path);
3540 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3542 char *alias_path = NULL;
3547 assert(config_path);
3549 STRV_FOREACH(s, i->wanted_by) {
3550 if (!unit_name_valid(*s)) {
3551 log_error("Invalid name %s.", *s);
3559 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3560 log_error("Out of memory");
3565 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3568 if (streq(verb, "disable"))
3569 rmdir_parents(alias_path, config_path);
3580 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3582 const ConfigItem items[] = {
3583 { "Alias", config_parse_strv, &i->aliases, "Install" },
3584 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3585 { "Also", config_parse_also, NULL, "Install" },
3587 { NULL, NULL, NULL, NULL }
3591 char *filename = NULL;
3598 STRV_FOREACH(p, paths->unit_path) {
3601 if (!(filename = path_make_absolute(i->name, *p))) {
3602 log_error("Out of memory");
3606 /* Ensure that we don't follow symlinks */
3607 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3608 if ((f = fdopen(fd, "re")))
3611 if (errno == ELOOP) {
3612 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3617 if (errno != ENOENT) {
3618 log_error("Failed to open %s: %m", filename);
3628 log_error("Couldn't find %s.", i->name);
3634 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3641 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3644 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3647 if ((r = mark_symlink_for_removal(filename)) < 0)
3650 if ((r = remove_marked_symlinks(config_path)) < 0)
3656 static char *get_config_path(void) {
3658 if (arg_session && arg_global)
3659 return strdup(SESSION_CONFIG_UNIT_PATH);
3664 if (session_config_home(&p) < 0)
3670 return strdup(SYSTEM_CONFIG_UNIT_PATH);
3673 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3677 char *config_path = NULL;
3680 const char *verb = args[0];
3682 dbus_error_init(&error);
3685 if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3686 log_error("Failed to determine lookup paths: %s", strerror(-r));
3690 if (!(config_path = get_config_path())) {
3691 log_error("Failed to determine config path");
3696 will_install = hashmap_new(string_hash_func, string_compare_func);
3697 have_installed = hashmap_new(string_hash_func, string_compare_func);
3699 if (!will_install || !have_installed) {
3700 log_error("Failed to allocate unit sets.");
3705 if (!arg_defaults && streq(verb, "disable"))
3706 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3707 log_error("Failed to allocate symlink sets.");
3712 for (j = 1; j < n; j++)
3713 if ((r = install_info_add(args[j])) < 0)
3716 while ((i = hashmap_first(will_install))) {
3719 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3721 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3729 /* In test mode and found something */
3735 if (streq(verb, "is-enabled"))
3736 r = r > 0 ? 0 : -ENOENT;
3738 /* Don't try to reload anything if the user asked us to not do this */
3740 /* Don't try to reload anything when updating a unit globally */
3742 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3743 (arg_session || sd_booted() > 0) &&
3744 /* Don't try to reload anything if we are running in a chroot environment */
3745 (arg_session || running_in_chroot() <= 0) ) {
3748 if ((q = daemon_reload(bus, args, n)) < 0)
3753 install_info_hashmap_free(will_install);
3754 install_info_hashmap_free(have_installed);
3756 set_free_free(remove_symlinks_to);
3758 lookup_paths_free(&paths);
3765 static int systemctl_help(void) {
3767 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3768 "Send control commands to or query the systemd manager.\n\n"
3769 " -h --help Show this help\n"
3770 " -t --type=TYPE List only units of a particular type\n"
3771 " -p --property=NAME Show only properties by this name\n"
3772 " -a --all Show all units/properties, including dead/empty ones\n"
3773 " --full Don't ellipsize unit names on output\n"
3774 " --fail When queueing a new job, fail if conflicting jobs are\n"
3776 " -q --quiet Suppress output\n"
3777 " --no-block Do not wait until operation finished\n"
3778 " --system Connect to system bus\n"
3779 " --session Connect to session bus\n"
3780 " --order When generating graph for dot, show only order\n"
3781 " --require When generating graph for dot, show only requirement\n"
3782 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3783 " --global Enable/disable unit files globally\n"
3784 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3786 " --force When enabling unit files, override existing symlinks\n"
3787 " --defaults When disabling unit files, remove default symlinks only\n\n"
3789 " list-units List units\n"
3790 " start [NAME...] Start (activate) one or more units\n"
3791 " stop [NAME...] Stop (deactivate) one or more units\n"
3792 " reload [NAME...] Reload one or more units\n"
3793 " restart [NAME...] Start or restart one or more units\n"
3794 " try-restart [NAME...] Restart one or more units if active\n"
3795 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3796 " otherwise start or restart\n"
3797 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3798 " otherwise restart if active\n"
3799 " isolate [NAME] Start one unit and stop all others\n"
3800 " is-active [NAME...] Check whether units are active\n"
3801 " status [NAME...|PID...] Show runtime status of one or more units\n"
3802 " show [NAME...|JOB...] Show properties of one or more\n"
3803 " units/jobs or the manager\n"
3804 " reset-maintenance [NAME...] Reset maintenance state for all, one,\n"
3806 " enable [NAME...] Enable one or more unit files\n"
3807 " disable [NAME...] Disable one or more unit files\n"
3808 " is-enabled [NAME...] Check whether unit files are enabled\n"
3809 " load [NAME...] Load one or more units\n"
3810 " list-jobs List jobs\n"
3811 " cancel [JOB...] Cancel all, one, or more jobs\n"
3812 " monitor Monitor unit/job changes\n"
3813 " dump Dump server status\n"
3814 " dot Dump dependency graph for dot(1)\n"
3815 " snapshot [NAME] Create a snapshot\n"
3816 " delete [NAME...] Remove one or more snapshots\n"
3817 " daemon-reload Reload systemd manager configuration\n"
3818 " daemon-reexec Reexecute systemd manager\n"
3819 " daemon-exit Ask the systemd manager to quit\n"
3820 " show-environment Dump environment\n"
3821 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3822 " unset-environment [NAME...] Unset one or more environment variables\n"
3823 " halt Shut down and halt the system\n"
3824 " poweroff Shut down and power-off the system\n"
3825 " reboot Shut down and reboot the system\n"
3826 " rescue Enter system rescue mode\n"
3827 " emergency Enter system emergency mode\n"
3828 " default Enter system default mode\n",
3829 program_invocation_short_name);
3834 static int halt_help(void) {
3836 printf("%s [OPTIONS...]\n\n"
3837 "%s the system.\n\n"
3838 " --help Show this help\n"
3839 " --halt Halt the machine\n"
3840 " -p --poweroff Switch off the machine\n"
3841 " --reboot Reboot the machine\n"
3842 " -f --force Force immediate halt/power-off/reboot\n"
3843 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3844 " -d --no-wtmp Don't write wtmp record\n"
3845 " -n --no-sync Don't sync before halt/power-off/reboot\n"
3846 " --no-wall Don't send wall message before halt/power-off/reboot\n",
3847 program_invocation_short_name,
3848 arg_action == ACTION_REBOOT ? "Reboot" :
3849 arg_action == ACTION_POWEROFF ? "Power off" :
3855 static int shutdown_help(void) {
3857 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3858 "Shut down the system.\n\n"
3859 " --help Show this help\n"
3860 " -H --halt Halt the machine\n"
3861 " -P --poweroff Power-off the machine\n"
3862 " -r --reboot Reboot the machine\n"
3863 " -h Equivalent to --poweroff, overriden by --halt\n"
3864 " -k Don't halt/power-off/reboot, just send warnings\n"
3865 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3866 " -c Cancel a pending shutdown\n",
3867 program_invocation_short_name);
3872 static int telinit_help(void) {
3874 printf("%s [OPTIONS...] {COMMAND}\n\n"
3875 "Send control commands to the init daemon.\n\n"
3876 " --help Show this help\n"
3877 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
3879 " 0 Power-off the machine\n"
3880 " 6 Reboot the machine\n"
3881 " 2, 3, 4, 5 Start runlevelX.target unit\n"
3882 " 1, s, S Enter rescue mode\n"
3883 " q, Q Reload init daemon configuration\n"
3884 " u, U Reexecute init daemon\n",
3885 program_invocation_short_name);
3890 static int runlevel_help(void) {
3892 printf("%s [OPTIONS...]\n\n"
3893 "Prints the previous and current runlevel of the init system.\n\n"
3894 " --help Show this help\n",
3895 program_invocation_short_name);
3900 static int systemctl_parse_argv(int argc, char *argv[]) {
3918 static const struct option options[] = {
3919 { "help", no_argument, NULL, 'h' },
3920 { "type", required_argument, NULL, 't' },
3921 { "property", required_argument, NULL, 'p' },
3922 { "all", no_argument, NULL, 'a' },
3923 { "full", no_argument, NULL, ARG_FULL },
3924 { "fail", no_argument, NULL, ARG_FAIL },
3925 { "session", no_argument, NULL, ARG_SESSION },
3926 { "system", no_argument, NULL, ARG_SYSTEM },
3927 { "global", no_argument, NULL, ARG_GLOBAL },
3928 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
3929 { "no-wall", no_argument, NULL, ARG_NO_WALL },
3930 { "quiet", no_argument, NULL, 'q' },
3931 { "order", no_argument, NULL, ARG_ORDER },
3932 { "require", no_argument, NULL, ARG_REQUIRE },
3933 { "force", no_argument, NULL, ARG_FORCE },
3934 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
3935 { "defaults", no_argument, NULL, ARG_DEFAULTS },
3936 { "sysv-compat", no_argument, NULL, ARG_SYSV_COMPAT },
3937 { NULL, 0, NULL, 0 }
3945 while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
3960 if (!(l = strv_append(arg_property, optarg)))
3963 strv_free(arg_property);
3966 /* If the user asked for a particular
3967 * property, show it to him, even if it is
3986 arg_session = false;
3990 arg_no_block = true;
3998 arg_dot = DOT_ORDER;
4002 arg_dot = DOT_REQUIRE;
4018 arg_no_reload = true;
4027 arg_defaults = true;
4030 case ARG_SYSV_COMPAT:
4031 arg_sysv_compat = true;
4038 log_error("Unknown option code %c", c);
4046 static int halt_parse_argv(int argc, char *argv[]) {
4055 static const struct option options[] = {
4056 { "help", no_argument, NULL, ARG_HELP },
4057 { "halt", no_argument, NULL, ARG_HALT },
4058 { "poweroff", no_argument, NULL, 'p' },
4059 { "reboot", no_argument, NULL, ARG_REBOOT },
4060 { "force", no_argument, NULL, 'f' },
4061 { "wtmp-only", no_argument, NULL, 'w' },
4062 { "no-wtmp", no_argument, NULL, 'd' },
4063 { "no-sync", no_argument, NULL, 'n' },
4064 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4065 { NULL, 0, NULL, 0 }
4073 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4074 if (runlevel == '0' || runlevel == '6')
4075 arg_immediate = true;
4077 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4085 arg_action = ACTION_HALT;
4089 if (arg_action != ACTION_REBOOT)
4090 arg_action = ACTION_POWEROFF;
4094 arg_action = ACTION_REBOOT;
4098 arg_immediate = true;
4119 /* Compatibility nops */
4126 log_error("Unknown option code %c", c);
4131 if (optind < argc) {
4132 log_error("Too many arguments.");
4139 static int parse_time_spec(const char *t, usec_t *_u) {
4143 if (streq(t, "now"))
4145 else if (t[0] == '+') {
4148 if (safe_atou64(t + 1, &u) < 0)
4151 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4160 hour = strtol(t, &e, 10);
4161 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4164 minute = strtol(e+1, &e, 10);
4165 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4168 n = now(CLOCK_REALTIME);
4169 s = (time_t) (n / USEC_PER_SEC);
4172 assert_se(localtime_r(&s, &tm));
4174 tm.tm_hour = (int) hour;
4175 tm.tm_min = (int) minute;
4178 assert_se(s = mktime(&tm));
4180 *_u = (usec_t) s * USEC_PER_SEC;
4183 *_u += USEC_PER_DAY;
4189 static int shutdown_parse_argv(int argc, char *argv[]) {
4196 static const struct option options[] = {
4197 { "help", no_argument, NULL, ARG_HELP },
4198 { "halt", no_argument, NULL, 'H' },
4199 { "poweroff", no_argument, NULL, 'P' },
4200 { "reboot", no_argument, NULL, 'r' },
4201 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4202 { NULL, 0, NULL, 0 }
4210 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4218 arg_action = ACTION_HALT;
4222 arg_action = ACTION_POWEROFF;
4226 arg_action = ACTION_REBOOT;
4230 if (arg_action != ACTION_HALT)
4231 arg_action = ACTION_POWEROFF;
4244 /* Compatibility nops */
4248 arg_action = ACTION_CANCEL_SHUTDOWN;
4255 log_error("Unknown option code %c", c);
4260 if (argc > optind) {
4261 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4262 log_error("Failed to parse time specification: %s", argv[optind]);
4266 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4268 /* We skip the time argument */
4269 if (argc > optind + 1)
4270 arg_wall = argv + optind + 1;
4277 static int telinit_parse_argv(int argc, char *argv[]) {
4284 static const struct option options[] = {
4285 { "help", no_argument, NULL, ARG_HELP },
4286 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4287 { NULL, 0, NULL, 0 }
4290 static const struct {
4294 { '0', ACTION_POWEROFF },
4295 { '6', ACTION_REBOOT },
4296 { '1', ACTION_RESCUE },
4297 { '2', ACTION_RUNLEVEL2 },
4298 { '3', ACTION_RUNLEVEL3 },
4299 { '4', ACTION_RUNLEVEL4 },
4300 { '5', ACTION_RUNLEVEL5 },
4301 { 's', ACTION_RESCUE },
4302 { 'S', ACTION_RESCUE },
4303 { 'q', ACTION_RELOAD },
4304 { 'Q', ACTION_RELOAD },
4305 { 'u', ACTION_REEXEC },
4306 { 'U', ACTION_REEXEC }
4315 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4330 log_error("Unknown option code %c", c);
4335 if (optind >= argc) {
4340 if (optind + 1 < argc) {
4341 log_error("Too many arguments.");
4345 if (strlen(argv[optind]) != 1) {
4346 log_error("Expected single character argument.");
4350 for (i = 0; i < ELEMENTSOF(table); i++)
4351 if (table[i].from == argv[optind][0])
4354 if (i >= ELEMENTSOF(table)) {
4355 log_error("Unknown command %s.", argv[optind]);
4359 arg_action = table[i].to;
4366 static int runlevel_parse_argv(int argc, char *argv[]) {
4372 static const struct option options[] = {
4373 { "help", no_argument, NULL, ARG_HELP },
4374 { NULL, 0, NULL, 0 }
4382 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4393 log_error("Unknown option code %c", c);
4398 if (optind < argc) {
4399 log_error("Too many arguments.");
4406 static int parse_argv(int argc, char *argv[]) {
4410 if (program_invocation_short_name) {
4412 if (strstr(program_invocation_short_name, "halt")) {
4413 arg_action = ACTION_HALT;
4414 return halt_parse_argv(argc, argv);
4415 } else if (strstr(program_invocation_short_name, "poweroff")) {
4416 arg_action = ACTION_POWEROFF;
4417 return halt_parse_argv(argc, argv);
4418 } else if (strstr(program_invocation_short_name, "reboot")) {
4419 arg_action = ACTION_REBOOT;
4420 return halt_parse_argv(argc, argv);
4421 } else if (strstr(program_invocation_short_name, "shutdown")) {
4422 arg_action = ACTION_POWEROFF;
4423 return shutdown_parse_argv(argc, argv);
4424 } else if (strstr(program_invocation_short_name, "init")) {
4426 if (sd_booted() > 0) {
4427 arg_action = ACTION_INVALID;
4428 return telinit_parse_argv(argc, argv);
4430 /* Hmm, so some other init system is
4431 * running, we need to forward this
4432 * request to it. For now we simply
4433 * guess that it is Upstart. */
4435 execv("/lib/upstart/telinit", argv);
4437 log_error("Couldn't find an alternative telinit implementation to spawn.");
4441 } else if (strstr(program_invocation_short_name, "runlevel")) {
4442 arg_action = ACTION_RUNLEVEL;
4443 return runlevel_parse_argv(argc, argv);
4447 arg_action = ACTION_SYSTEMCTL;
4448 return systemctl_parse_argv(argc, argv);
4451 static int action_to_runlevel(void) {
4453 static const char table[_ACTION_MAX] = {
4454 [ACTION_HALT] = '0',
4455 [ACTION_POWEROFF] = '0',
4456 [ACTION_REBOOT] = '6',
4457 [ACTION_RUNLEVEL2] = '2',
4458 [ACTION_RUNLEVEL3] = '3',
4459 [ACTION_RUNLEVEL4] = '4',
4460 [ACTION_RUNLEVEL5] = '5',
4461 [ACTION_RESCUE] = '1'
4464 assert(arg_action < _ACTION_MAX);
4466 return table[arg_action];
4469 static int talk_upstart(void) {
4470 DBusMessage *m = NULL, *reply = NULL;
4472 int previous, rl, r;
4474 env1_buf[] = "RUNLEVEL=X",
4475 env2_buf[] = "PREVLEVEL=X";
4476 char *env1 = env1_buf, *env2 = env2_buf;
4477 const char *emit = "runlevel";
4478 dbus_bool_t b_false = FALSE;
4479 DBusMessageIter iter, sub;
4480 DBusConnection *bus;
4482 dbus_error_init(&error);
4484 if (!(rl = action_to_runlevel()))
4487 if (utmp_get_runlevel(&previous, NULL) < 0)
4490 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4491 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4496 log_error("Failed to connect to Upstart bus: %s", error.message);
4501 if ((r = bus_check_peercred(bus)) < 0) {
4502 log_error("Failed to verify owner of bus.");
4506 if (!(m = dbus_message_new_method_call(
4507 "com.ubuntu.Upstart",
4508 "/com/ubuntu/Upstart",
4509 "com.ubuntu.Upstart0_6",
4512 log_error("Could not allocate message.");
4517 dbus_message_iter_init_append(m, &iter);
4519 env1_buf[sizeof(env1_buf)-2] = rl;
4520 env2_buf[sizeof(env2_buf)-2] = previous;
4522 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4523 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4524 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4525 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4526 !dbus_message_iter_close_container(&iter, &sub) ||
4527 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4528 log_error("Could not append arguments to message.");
4533 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4535 if (error_is_no_service(&error)) {
4540 log_error("Failed to issue method call: %s", error.message);
4549 dbus_message_unref(m);
4552 dbus_message_unref(reply);
4555 dbus_connection_close(bus);
4556 dbus_connection_unref(bus);
4559 dbus_error_free(&error);
4564 static int talk_initctl(void) {
4565 struct init_request request;
4569 if (!(rl = action_to_runlevel()))
4573 request.magic = INIT_MAGIC;
4574 request.sleeptime = 0;
4575 request.cmd = INIT_CMD_RUNLVL;
4576 request.runlevel = rl;
4578 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4580 if (errno == ENOENT)
4583 log_error("Failed to open "INIT_FIFO": %m");
4588 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4589 close_nointr_nofail(fd);
4592 log_error("Failed to write to "INIT_FIFO": %m");
4593 return errno ? -errno : -EIO;
4599 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4601 static const struct {
4609 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4611 { "list-units", LESS, 1, list_units },
4612 { "list-jobs", EQUAL, 1, list_jobs },
4613 { "clear-jobs", EQUAL, 1, daemon_reload },
4614 { "load", MORE, 2, load_unit },
4615 { "cancel", MORE, 2, cancel_job },
4616 { "start", MORE, 2, start_unit },
4617 { "stop", MORE, 2, start_unit },
4618 { "reload", MORE, 2, start_unit },
4619 { "restart", MORE, 2, start_unit },
4620 { "try-restart", MORE, 2, start_unit },
4621 { "reload-or-restart", MORE, 2, start_unit },
4622 { "reload-or-try-restart", MORE, 2, start_unit },
4623 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4624 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4625 { "isolate", EQUAL, 2, start_unit },
4626 { "is-active", MORE, 2, check_unit },
4627 { "check", MORE, 2, check_unit },
4628 { "show", MORE, 1, show },
4629 { "status", MORE, 2, show },
4630 { "monitor", EQUAL, 1, monitor },
4631 { "dump", EQUAL, 1, dump },
4632 { "dot", EQUAL, 1, dot },
4633 { "snapshot", LESS, 2, snapshot },
4634 { "delete", MORE, 2, delete_snapshot },
4635 { "daemon-reload", EQUAL, 1, daemon_reload },
4636 { "daemon-reexec", EQUAL, 1, daemon_reload },
4637 { "daemon-exit", EQUAL, 1, daemon_reload },
4638 { "show-environment", EQUAL, 1, show_enviroment },
4639 { "set-environment", MORE, 2, set_environment },
4640 { "unset-environment", MORE, 2, set_environment },
4641 { "halt", EQUAL, 1, start_special },
4642 { "poweroff", EQUAL, 1, start_special },
4643 { "reboot", EQUAL, 1, start_special },
4644 { "default", EQUAL, 1, start_special },
4645 { "rescue", EQUAL, 1, start_special },
4646 { "emergency", EQUAL, 1, start_special },
4647 { "reset-maintenance", MORE, 1, reset_maintenance },
4648 { "enable", MORE, 2, enable_unit },
4649 { "disable", MORE, 2, enable_unit },
4650 { "is-enabled", MORE, 2, enable_unit }
4660 left = argc - optind;
4663 /* Special rule: no arguments means "list-units" */
4666 if (streq(argv[optind], "help")) {
4671 for (i = 0; i < ELEMENTSOF(verbs); i++)
4672 if (streq(argv[optind], verbs[i].verb))
4675 if (i >= ELEMENTSOF(verbs)) {
4676 log_error("Unknown operation %s", argv[optind]);
4681 switch (verbs[i].argc_cmp) {
4684 if (left != verbs[i].argc) {
4685 log_error("Invalid number of arguments.");
4692 if (left < verbs[i].argc) {
4693 log_error("Too few arguments.");
4700 if (left > verbs[i].argc) {
4701 log_error("Too many arguments.");
4708 assert_not_reached("Unknown comparison operator.");
4711 /* Require a bus connection for all operations but
4713 if (!streq(verbs[i].verb, "enable") &&
4714 !streq(verbs[i].verb, "disable") &&
4716 log_error("Failed to get D-Bus connection: %s", error->message);
4720 return verbs[i].dispatch(bus, argv + optind, left);
4723 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
4725 struct msghdr msghdr;
4727 union sockaddr_union sockaddr;
4728 struct ucred *ucred;
4730 struct cmsghdr cmsghdr;
4731 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
4733 struct shutdownd_command c;
4741 strncpy(c.wall_message, message, sizeof(c.wall_message));
4743 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4747 sockaddr.sa.sa_family = AF_UNIX;
4748 sockaddr.un.sun_path[0] = 0;
4749 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
4752 iovec.iov_base = (char*) &c;
4753 iovec.iov_len = sizeof(c);
4756 control.cmsghdr.cmsg_level = SOL_SOCKET;
4757 control.cmsghdr.cmsg_type = SCM_CREDENTIALS;
4758 control.cmsghdr.cmsg_len = CMSG_LEN(sizeof(struct ucred));
4760 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
4761 ucred->pid = getpid();
4762 ucred->uid = getuid();
4763 ucred->gid = getgid();
4766 msghdr.msg_name = &sockaddr;
4767 msghdr.msg_namelen = sizeof(sa_family_t) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
4769 msghdr.msg_iov = &iovec;
4770 msghdr.msg_iovlen = 1;
4771 msghdr.msg_control = &control;
4772 msghdr.msg_controllen = control.cmsghdr.cmsg_len;
4774 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
4775 close_nointr_nofail(fd);
4779 close_nointr_nofail(fd);
4783 static int reload_with_fallback(DBusConnection *bus) {
4786 /* First, try systemd via D-Bus. */
4787 if (daemon_reload(bus, NULL, 0) > 0)
4791 /* Nothing else worked, so let's try signals */
4792 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
4794 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
4795 log_error("kill() failed: %m");
4802 static int start_with_fallback(DBusConnection *bus) {
4805 /* First, try systemd via D-Bus. */
4806 if (start_unit(bus, NULL, 0) > 0)
4810 /* Hmm, talking to systemd via D-Bus didn't work. Then
4811 * let's try to talk to Upstart via D-Bus. */
4812 if (talk_upstart() > 0)
4815 /* Nothing else worked, so let's try
4817 if (talk_initctl() > 0)
4820 log_error("Failed to talk to init daemon.");
4824 warn_wall(arg_action);
4828 static int halt_main(DBusConnection *bus) {
4831 if (geteuid() != 0) {
4832 log_error("Must to be root.");
4838 char date[FORMAT_TIMESTAMP_MAX];
4840 m = strv_join(arg_wall, " ");
4841 r = send_shutdownd(arg_when,
4842 arg_action == ACTION_HALT ? 'H' :
4843 arg_action == ACTION_POWEROFF ? 'P' :
4850 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
4852 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
4853 format_timestamp(date, sizeof(date), arg_when));
4858 if (!arg_dry && !arg_immediate)
4859 return start_with_fallback(bus);
4862 if (sd_booted() > 0)
4863 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
4864 else if ((r = utmp_put_shutdown(0)) < 0)
4865 log_warning("Failed to write utmp record: %s", strerror(-r));
4874 /* Make sure C-A-D is handled by the kernel from this
4876 reboot(RB_ENABLE_CAD);
4878 switch (arg_action) {
4881 log_info("Halting.");
4882 reboot(RB_HALT_SYSTEM);
4885 case ACTION_POWEROFF:
4886 log_info("Powering off.");
4887 reboot(RB_POWER_OFF);
4891 log_info("Rebooting.");
4892 reboot(RB_AUTOBOOT);
4896 assert_not_reached("Unknown halt action.");
4899 /* We should never reach this. */
4903 static int runlevel_main(void) {
4904 int r, runlevel, previous;
4906 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
4907 printf("unknown\n");
4912 previous <= 0 ? 'N' : previous,
4913 runlevel <= 0 ? 'N' : runlevel);
4918 int main(int argc, char*argv[]) {
4920 DBusConnection *bus = NULL;
4923 dbus_error_init(&error);
4925 log_parse_environment();
4928 if ((r = parse_argv(argc, argv)) < 0)
4935 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
4936 * let's shortcut this */
4937 if (arg_action == ACTION_RUNLEVEL) {
4938 retval = runlevel_main() < 0;
4942 bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
4944 switch (arg_action) {
4946 case ACTION_SYSTEMCTL: {
4947 retval = systemctl_main(bus, argc, argv, &error) < 0;
4952 case ACTION_POWEROFF:
4954 retval = halt_main(bus) < 0;
4957 case ACTION_RUNLEVEL2:
4958 case ACTION_RUNLEVEL3:
4959 case ACTION_RUNLEVEL4:
4960 case ACTION_RUNLEVEL5:
4962 case ACTION_EMERGENCY:
4963 case ACTION_DEFAULT:
4964 retval = start_with_fallback(bus) < 0;
4969 retval = reload_with_fallback(bus) < 0;
4972 case ACTION_CANCEL_SHUTDOWN:
4973 retval = send_shutdownd(0, 0, false, NULL) < 0;
4976 case ACTION_INVALID:
4977 case ACTION_RUNLEVEL:
4979 assert_not_reached("Unknown action");
4985 dbus_connection_close(bus);
4986 dbus_connection_unref(bus);
4989 dbus_error_free(&error);
4993 strv_free(arg_property);