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 char **arg_wall = NULL;
73 static usec_t arg_when = 0;
90 ACTION_CANCEL_SHUTDOWN,
92 } arg_action = ACTION_SYSTEMCTL;
99 static bool private_bus = false;
101 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
103 static bool on_tty(void) {
106 if (_unlikely_(t < 0))
107 t = isatty(STDOUT_FILENO) > 0;
112 static const char *ansi_highlight(bool b) {
117 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
120 static const char *ansi_highlight_green(bool b) {
125 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
128 static bool error_is_no_service(DBusError *error) {
132 if (!dbus_error_is_set(error))
135 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
138 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
141 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
144 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
149 if (dbus_message_iter_get_arg_type(iter) != type)
152 dbus_message_iter_get_basic(iter, data);
154 if (!dbus_message_iter_next(iter) != !next)
160 static void warn_wall(enum action action) {
161 static const char *table[_ACTION_MAX] = {
162 [ACTION_HALT] = "The system is going down for system halt NOW!",
163 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
164 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
165 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
166 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
175 if (!(p = strv_join(arg_wall, " "))) {
176 log_error("Failed to join strings.");
192 utmp_wall(table[action]);
197 const char *description;
198 const char *load_state;
199 const char *active_state;
200 const char *sub_state;
201 const char *following;
202 const char *unit_path;
204 const char *job_type;
205 const char *job_path;
208 static int compare_unit_info(const void *a, const void *b) {
210 const struct unit_info *u = a, *v = b;
212 d1 = strrchr(u->id, '.');
213 d2 = strrchr(v->id, '.');
218 if ((r = strcasecmp(d1, d2)) != 0)
222 return strcasecmp(u->id, v->id);
225 static int list_units(DBusConnection *bus, char **args, unsigned n) {
226 DBusMessage *m = NULL, *reply = NULL;
229 DBusMessageIter iter, sub, sub2;
230 unsigned c = 0, k, n_units = 0;
231 struct unit_info *unit_infos = NULL;
233 dbus_error_init(&error);
237 if (!(m = dbus_message_new_method_call(
238 "org.freedesktop.systemd1",
239 "/org/freedesktop/systemd1",
240 "org.freedesktop.systemd1.Manager",
242 log_error("Could not allocate message.");
246 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
247 log_error("Failed to issue method call: %s", error.message);
252 if (!dbus_message_iter_init(reply, &iter) ||
253 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
254 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
255 log_error("Failed to parse reply.");
260 dbus_message_iter_recurse(&iter, &sub);
262 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
265 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
266 log_error("Failed to parse reply.");
274 n_units = MAX(2*c, 16);
275 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
278 log_error("Failed to allocate unit array.");
288 dbus_message_iter_recurse(&sub, &sub2);
290 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
291 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
292 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
293 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
294 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
295 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
296 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
297 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
298 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
299 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
300 log_error("Failed to parse reply.");
305 dbus_message_iter_next(&sub);
309 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
311 if (isatty(STDOUT_FILENO))
312 printf("%-45s %-6s %-12s %-12s %-15s %s\n", "UNIT", "LOAD", "ACTIVE", "SUB", "JOB", "DESCRIPTION");
314 for (k = 0; k < c; k++) {
316 struct unit_info *u = unit_infos+k;
318 if ((!arg_type || ((dot = strrchr(u->id, '.')) &&
319 streq(dot+1, arg_type))) &&
320 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0)) {
323 const char *on, *off;
325 if (streq(u->active_state, "maintenance")) {
326 on = ansi_highlight(true);
327 off = ansi_highlight(false);
331 e = arg_full ? NULL : ellipsize(u->id, 45, 33);
332 printf("%-45s %-6s %s%-12s %-12s%s%n", e ? e : u->id, u->load_state, on, u->active_state, u->sub_state, off, &a);
335 a -= strlen(on) + strlen(off);
338 printf(" => %-12s%n", u->job_type, &b);
342 if (a + b + 2 < columns()) {
346 printf(" %.*s", columns() - a - b - 2, u->description);
353 if (isatty(STDOUT_FILENO)) {
355 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
356 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
357 "SUB = The low-level unit activation state, values depend on unit type.\n"
358 "JOB = Pending job for the unit.\n");
361 printf("\n%u units listed.\n", c);
363 printf("\n%u units listed. Pass --all to see inactive units, too.\n", c);
370 dbus_message_unref(m);
373 dbus_message_unref(reply);
377 dbus_error_free(&error);
382 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
383 static const char * const colors[] = {
384 "Requires", "[color=\"black\"]",
385 "RequiresOverridable", "[color=\"black\"]",
386 "Requisite", "[color=\"darkblue\"]",
387 "RequisiteOverridable", "[color=\"darkblue\"]",
388 "Wants", "[color=\"darkgrey\"]",
389 "Conflicts", "[color=\"red\"]",
390 "ConflictedBy", "[color=\"red\"]",
391 "After", "[color=\"green\"]"
394 const char *c = NULL;
401 for (i = 0; i < ELEMENTSOF(colors); i += 2)
402 if (streq(colors[i], prop)) {
410 if (arg_dot != DOT_ALL)
411 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
414 switch (dbus_message_iter_get_arg_type(iter)) {
416 case DBUS_TYPE_ARRAY:
418 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
421 dbus_message_iter_recurse(iter, &sub);
423 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
426 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
427 dbus_message_iter_get_basic(&sub, &s);
428 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
430 dbus_message_iter_next(&sub);
440 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
441 DBusMessage *m = NULL, *reply = NULL;
442 const char *interface = "org.freedesktop.systemd1.Unit";
445 DBusMessageIter iter, sub, sub2, sub3;
450 dbus_error_init(&error);
452 if (!(m = dbus_message_new_method_call(
453 "org.freedesktop.systemd1",
455 "org.freedesktop.DBus.Properties",
457 log_error("Could not allocate message.");
462 if (!dbus_message_append_args(m,
463 DBUS_TYPE_STRING, &interface,
464 DBUS_TYPE_INVALID)) {
465 log_error("Could not append arguments to message.");
470 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
471 log_error("Failed to issue method call: %s", error.message);
476 if (!dbus_message_iter_init(reply, &iter) ||
477 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
478 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
479 log_error("Failed to parse reply.");
484 dbus_message_iter_recurse(&iter, &sub);
486 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
489 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
490 log_error("Failed to parse reply.");
495 dbus_message_iter_recurse(&sub, &sub2);
497 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
498 log_error("Failed to parse reply.");
503 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
504 log_error("Failed to parse reply.");
509 dbus_message_iter_recurse(&sub2, &sub3);
511 if (dot_one_property(name, prop, &sub3)) {
512 log_error("Failed to parse reply.");
517 dbus_message_iter_next(&sub);
524 dbus_message_unref(m);
527 dbus_message_unref(reply);
529 dbus_error_free(&error);
534 static int dot(DBusConnection *bus, char **args, unsigned n) {
535 DBusMessage *m = NULL, *reply = NULL;
538 DBusMessageIter iter, sub, sub2;
540 dbus_error_init(&error);
544 if (!(m = dbus_message_new_method_call(
545 "org.freedesktop.systemd1",
546 "/org/freedesktop/systemd1",
547 "org.freedesktop.systemd1.Manager",
549 log_error("Could not allocate message.");
553 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
554 log_error("Failed to issue method call: %s", error.message);
559 if (!dbus_message_iter_init(reply, &iter) ||
560 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
561 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
562 log_error("Failed to parse reply.");
567 printf("digraph systemd {\n");
569 dbus_message_iter_recurse(&iter, &sub);
570 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
571 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
573 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
574 log_error("Failed to parse reply.");
579 dbus_message_iter_recurse(&sub, &sub2);
581 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
582 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
583 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
584 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
585 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
586 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
587 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
588 log_error("Failed to parse reply.");
593 if ((r = dot_one(bus, id, unit_path)) < 0)
596 /* printf("\t\"%s\";\n", id); */
597 dbus_message_iter_next(&sub);
602 log_info(" Color legend: black = Requires\n"
603 " dark blue = Requisite\n"
604 " dark grey = Wants\n"
608 if (isatty(fileno(stdout)))
609 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
610 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
616 dbus_message_unref(m);
619 dbus_message_unref(reply);
621 dbus_error_free(&error);
626 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
627 DBusMessage *m = NULL, *reply = NULL;
630 DBusMessageIter iter, sub, sub2;
633 dbus_error_init(&error);
637 if (!(m = dbus_message_new_method_call(
638 "org.freedesktop.systemd1",
639 "/org/freedesktop/systemd1",
640 "org.freedesktop.systemd1.Manager",
642 log_error("Could not allocate message.");
646 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
647 log_error("Failed to issue method call: %s", error.message);
652 if (!dbus_message_iter_init(reply, &iter) ||
653 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
654 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
655 log_error("Failed to parse reply.");
660 dbus_message_iter_recurse(&iter, &sub);
662 printf("%4s %-45s %-17s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
664 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
665 const char *name, *type, *state, *job_path, *unit_path;
669 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
670 log_error("Failed to parse reply.");
675 dbus_message_iter_recurse(&sub, &sub2);
677 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
678 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
679 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
680 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
681 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
682 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
683 log_error("Failed to parse reply.");
688 e = arg_full ? NULL : ellipsize(name, 45, 33);
689 printf("%4u %-45s %-17s %-7s\n", id, e ? e : name, type, state);
694 dbus_message_iter_next(&sub);
697 printf("\n%u jobs listed.\n", k);
702 dbus_message_unref(m);
705 dbus_message_unref(reply);
707 dbus_error_free(&error);
712 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
713 DBusMessage *m = NULL, *reply = NULL;
718 dbus_error_init(&error);
723 for (i = 1; i < n; i++) {
725 if (!(m = dbus_message_new_method_call(
726 "org.freedesktop.systemd1",
727 "/org/freedesktop/systemd1",
728 "org.freedesktop.systemd1.Manager",
730 log_error("Could not allocate message.");
735 if (!dbus_message_append_args(m,
736 DBUS_TYPE_STRING, &args[i],
737 DBUS_TYPE_INVALID)) {
738 log_error("Could not append arguments to message.");
743 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
744 log_error("Failed to issue method call: %s", error.message);
749 dbus_message_unref(m);
750 dbus_message_unref(reply);
759 dbus_message_unref(m);
762 dbus_message_unref(reply);
764 dbus_error_free(&error);
769 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
770 DBusMessage *m = NULL, *reply = NULL;
775 dbus_error_init(&error);
781 return daemon_reload(bus, args, n);
783 for (i = 1; i < n; i++) {
787 if (!(m = dbus_message_new_method_call(
788 "org.freedesktop.systemd1",
789 "/org/freedesktop/systemd1",
790 "org.freedesktop.systemd1.Manager",
792 log_error("Could not allocate message.");
797 if ((r = safe_atou(args[i], &id)) < 0) {
798 log_error("Failed to parse job id: %s", strerror(-r));
802 assert_cc(sizeof(uint32_t) == sizeof(id));
803 if (!dbus_message_append_args(m,
804 DBUS_TYPE_UINT32, &id,
805 DBUS_TYPE_INVALID)) {
806 log_error("Could not append arguments to message.");
811 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
812 log_error("Failed to issue method call: %s", error.message);
817 if (!dbus_message_get_args(reply, &error,
818 DBUS_TYPE_OBJECT_PATH, &path,
819 DBUS_TYPE_INVALID)) {
820 log_error("Failed to parse reply: %s", error.message);
825 dbus_message_unref(m);
826 if (!(m = dbus_message_new_method_call(
827 "org.freedesktop.systemd1",
829 "org.freedesktop.systemd1.Job",
831 log_error("Could not allocate message.");
836 dbus_message_unref(reply);
837 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
838 log_error("Failed to issue method call: %s", error.message);
843 dbus_message_unref(m);
844 dbus_message_unref(reply);
852 dbus_message_unref(m);
855 dbus_message_unref(reply);
857 dbus_error_free(&error);
862 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
863 DBusMessage *m = NULL, *reply = NULL;
864 dbus_bool_t b = FALSE;
865 DBusMessageIter iter, sub;
867 *interface = "org.freedesktop.systemd1.Unit",
868 *property = "NeedDaemonReload",
871 /* We ignore all errors here, since this is used to show a warning only */
873 if (!(m = dbus_message_new_method_call(
874 "org.freedesktop.systemd1",
875 "/org/freedesktop/systemd1",
876 "org.freedesktop.systemd1.Manager",
880 if (!dbus_message_append_args(m,
881 DBUS_TYPE_STRING, &unit,
885 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
888 if (!dbus_message_get_args(reply, NULL,
889 DBUS_TYPE_OBJECT_PATH, &path,
893 dbus_message_unref(m);
894 if (!(m = dbus_message_new_method_call(
895 "org.freedesktop.systemd1",
897 "org.freedesktop.DBus.Properties",
901 if (!dbus_message_append_args(m,
902 DBUS_TYPE_STRING, &interface,
903 DBUS_TYPE_STRING, &property,
904 DBUS_TYPE_INVALID)) {
908 dbus_message_unref(reply);
909 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
912 if (!dbus_message_iter_init(reply, &iter) ||
913 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
916 dbus_message_iter_recurse(&iter, &sub);
918 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
921 dbus_message_iter_get_basic(&sub, &b);
925 dbus_message_unref(m);
928 dbus_message_unref(reply);
933 typedef struct WaitData {
938 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
946 dbus_error_init(&error);
948 log_debug("Got D-Bus request: %s.%s() on %s",
949 dbus_message_get_interface(message),
950 dbus_message_get_member(message),
951 dbus_message_get_path(message));
953 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
954 log_error("Warning! D-Bus connection terminated.");
955 dbus_connection_close(connection);
957 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
960 dbus_bool_t success = true;
962 if (!dbus_message_get_args(message, &error,
963 DBUS_TYPE_UINT32, &id,
964 DBUS_TYPE_OBJECT_PATH, &path,
965 DBUS_TYPE_BOOLEAN, &success,
967 log_error("Failed to parse message: %s", error.message);
971 if ((p = set_remove(d->set, (char*) path)))
979 dbus_error_free(&error);
980 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
983 static int enable_wait_for_jobs(DBusConnection *bus) {
991 dbus_error_init(&error);
992 dbus_bus_add_match(bus,
994 "sender='org.freedesktop.systemd1',"
995 "interface='org.freedesktop.systemd1.Manager',"
996 "member='JobRemoved',"
997 "path='/org/freedesktop/systemd1'",
1000 if (dbus_error_is_set(&error)) {
1001 log_error("Failed to add match: %s", error.message);
1002 dbus_error_free(&error);
1006 /* This is slightly dirty, since we don't undo the match registrations. */
1010 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1021 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1022 log_error("Failed to add filter.");
1027 while (!set_isempty(s) &&
1028 dbus_connection_read_write_dispatch(bus, -1))
1031 if (!arg_quiet && d.failed)
1032 log_error("Job failed, see logs for details.");
1034 r = d.failed ? -EIO : 0;
1037 /* This is slightly dirty, since we don't undo the filter registration. */
1042 static int start_unit_one(
1043 DBusConnection *bus,
1049 DBusMessage *m = NULL, *reply = NULL;
1058 assert(arg_no_block || s);
1060 dbus_error_init(&error);
1062 if (!(m = dbus_message_new_method_call(
1063 "org.freedesktop.systemd1",
1064 "/org/freedesktop/systemd1",
1065 "org.freedesktop.systemd1.Manager",
1067 log_error("Could not allocate message.");
1072 if (!dbus_message_append_args(m,
1073 DBUS_TYPE_STRING, &name,
1074 DBUS_TYPE_STRING, &mode,
1075 DBUS_TYPE_INVALID)) {
1076 log_error("Could not append arguments to message.");
1081 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1083 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
1084 /* There's always a fallback possible for
1085 * legacy actions. */
1090 log_error("Failed to issue method call: %s", error.message);
1095 if (!dbus_message_get_args(reply, &error,
1096 DBUS_TYPE_OBJECT_PATH, &path,
1097 DBUS_TYPE_INVALID)) {
1098 log_error("Failed to parse reply: %s", error.message);
1103 if (need_daemon_reload(bus, name))
1104 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1105 arg_session ? "--session" : "--system");
1107 if (!arg_no_block) {
1110 if (!(p = strdup(path))) {
1111 log_error("Failed to duplicate path.");
1116 if ((r = set_put(s, p)) < 0) {
1118 log_error("Failed to add path to set.");
1127 dbus_message_unref(m);
1130 dbus_message_unref(reply);
1132 dbus_error_free(&error);
1137 static enum action verb_to_action(const char *verb) {
1138 if (streq(verb, "halt"))
1140 else if (streq(verb, "poweroff"))
1141 return ACTION_POWEROFF;
1142 else if (streq(verb, "reboot"))
1143 return ACTION_REBOOT;
1144 else if (streq(verb, "rescue"))
1145 return ACTION_RESCUE;
1146 else if (streq(verb, "emergency"))
1147 return ACTION_EMERGENCY;
1148 else if (streq(verb, "default"))
1149 return ACTION_DEFAULT;
1151 return ACTION_INVALID;
1154 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1156 static const char * const table[_ACTION_MAX] = {
1157 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1158 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1159 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1160 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1161 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1162 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1163 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1164 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1165 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1166 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET
1171 const char *method, *mode, *one_name;
1176 if (arg_action == ACTION_SYSTEMCTL) {
1178 streq(args[0], "stop") ? "StopUnit" :
1179 streq(args[0], "reload") ? "ReloadUnit" :
1180 streq(args[0], "restart") ? "RestartUnit" :
1181 streq(args[0], "try-restart") ? "TryRestartUnit" :
1182 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1183 streq(args[0], "reload-or-try-restart") ||
1184 streq(args[0], "force-reload") ||
1185 streq(args[0], "condrestart") ? "ReloadOrTryRestartUnit" :
1189 (streq(args[0], "isolate") ||
1190 streq(args[0], "rescue") ||
1191 streq(args[0], "emergency")) ? "isolate" :
1195 one_name = table[verb_to_action(args[0])];
1198 assert(arg_action < ELEMENTSOF(table));
1199 assert(table[arg_action]);
1201 method = "StartUnit";
1203 mode = (arg_action == ACTION_EMERGENCY ||
1204 arg_action == ACTION_RESCUE) ? "isolate" : "replace";
1206 one_name = table[arg_action];
1209 if (!arg_no_block) {
1210 if ((r = enable_wait_for_jobs(bus)) < 0) {
1211 log_error("Could not watch jobs: %s", strerror(-r));
1215 if (!(s = set_new(string_hash_func, string_compare_func))) {
1216 log_error("Failed to allocate set.");
1225 if ((r = start_unit_one(bus, method, one_name, mode, s)) <= 0)
1228 for (i = 1; i < n; i++)
1229 if ((r = start_unit_one(bus, method, args[i], mode, s)) < 0)
1234 if ((r = wait_for_jobs(bus, s)) < 0)
1246 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1252 r = start_unit(bus, args, n);
1255 warn_wall(verb_to_action(args[0]));
1260 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1261 DBusMessage *m = NULL, *reply = NULL;
1263 *interface = "org.freedesktop.systemd1.Unit",
1264 *property = "ActiveState";
1265 int r = -EADDRNOTAVAIL;
1272 dbus_error_init(&error);
1274 for (i = 1; i < n; i++) {
1275 const char *path = NULL;
1277 DBusMessageIter iter, sub;
1279 if (!(m = dbus_message_new_method_call(
1280 "org.freedesktop.systemd1",
1281 "/org/freedesktop/systemd1",
1282 "org.freedesktop.systemd1.Manager",
1284 log_error("Could not allocate message.");
1289 if (!dbus_message_append_args(m,
1290 DBUS_TYPE_STRING, &args[i],
1291 DBUS_TYPE_INVALID)) {
1292 log_error("Could not append arguments to message.");
1297 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1299 /* Hmm, cannot figure out anything about this unit... */
1303 dbus_error_free(&error);
1307 if (!dbus_message_get_args(reply, &error,
1308 DBUS_TYPE_OBJECT_PATH, &path,
1309 DBUS_TYPE_INVALID)) {
1310 log_error("Failed to parse reply: %s", error.message);
1315 dbus_message_unref(m);
1316 if (!(m = dbus_message_new_method_call(
1317 "org.freedesktop.systemd1",
1319 "org.freedesktop.DBus.Properties",
1321 log_error("Could not allocate message.");
1326 if (!dbus_message_append_args(m,
1327 DBUS_TYPE_STRING, &interface,
1328 DBUS_TYPE_STRING, &property,
1329 DBUS_TYPE_INVALID)) {
1330 log_error("Could not append arguments to message.");
1335 dbus_message_unref(reply);
1336 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1337 log_error("Failed to issue method call: %s", error.message);
1342 if (!dbus_message_iter_init(reply, &iter) ||
1343 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1344 log_error("Failed to parse reply.");
1349 dbus_message_iter_recurse(&iter, &sub);
1351 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1352 log_error("Failed to parse reply.");
1357 dbus_message_iter_get_basic(&sub, &state);
1362 if (streq(state, "active") || startswith(state, "reloading"))
1365 dbus_message_unref(m);
1366 dbus_message_unref(reply);
1372 dbus_message_unref(m);
1375 dbus_message_unref(reply);
1377 dbus_error_free(&error);
1382 typedef struct ExecStatusInfo {
1388 usec_t start_timestamp;
1389 usec_t exit_timestamp;
1394 LIST_FIELDS(struct ExecStatusInfo, exec);
1397 static void exec_status_info_free(ExecStatusInfo *i) {
1405 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1406 uint64_t start_timestamp, exit_timestamp;
1407 DBusMessageIter sub2, sub3;
1411 int32_t code, status;
1417 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1420 dbus_message_iter_recurse(sub, &sub2);
1422 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1425 if (!(i->path = strdup(path)))
1428 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1429 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1433 dbus_message_iter_recurse(&sub2, &sub3);
1434 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1435 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1436 dbus_message_iter_next(&sub3);
1441 if (!(i->argv = new0(char*, n+1)))
1445 dbus_message_iter_recurse(&sub2, &sub3);
1446 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1449 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1450 dbus_message_iter_get_basic(&sub3, &s);
1451 dbus_message_iter_next(&sub3);
1453 if (!(i->argv[n++] = strdup(s)))
1457 if (!dbus_message_iter_next(&sub2) ||
1458 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1459 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1460 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1461 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1462 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1463 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1467 i->start_timestamp = (usec_t) start_timestamp;
1468 i->exit_timestamp = (usec_t) exit_timestamp;
1469 i->pid = (pid_t) pid;
1476 typedef struct UnitStatusInfo {
1478 const char *load_state;
1479 const char *active_state;
1480 const char *sub_state;
1482 const char *description;
1485 const char *default_control_group;
1487 bool need_daemon_reload;
1492 const char *status_text;
1496 usec_t start_timestamp;
1497 usec_t exit_timestamp;
1499 int exit_code, exit_status;
1502 unsigned n_accepted;
1503 unsigned n_connections;
1507 const char *sysfs_path;
1509 /* Mount, Automount */
1515 LIST_HEAD(ExecStatusInfo, exec);
1518 static void print_status_info(UnitStatusInfo *i) {
1520 const char *on, *off, *ss;
1524 /* This shows pretty information about a unit. See
1525 * print_property() for a low-level property printer */
1527 printf("%s", strna(i->id));
1529 if (i->description && !streq_ptr(i->id, i->description))
1530 printf(" - %s", i->description);
1534 if (streq_ptr(i->load_state, "failed")) {
1535 on = ansi_highlight(true);
1536 off = ansi_highlight(false);
1541 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1543 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1545 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1547 if (streq_ptr(i->active_state, "maintenance")) {
1548 on = ansi_highlight(true);
1549 off = ansi_highlight(false);
1550 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1551 on = ansi_highlight_green(true);
1552 off = ansi_highlight_green(false);
1557 printf("\t Active: %s%s (%s)%s\n",
1559 strna(i->active_state),
1563 printf("\t Active: %s%s%s\n",
1565 strna(i->active_state),
1569 printf("\t Device: %s\n", i->sysfs_path);
1571 printf("\t Where: %s\n", i->where);
1573 printf("\t What: %s\n", i->what);
1576 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1578 LIST_FOREACH(exec, p, i->exec) {
1581 /* Only show exited processes here */
1585 t = strv_join(p->argv, " ");
1586 printf("\t Exited: %u (%s, code=%s, ", p->pid, strna(t), sigchld_code_to_string(p->code));
1589 if (p->code == CLD_EXITED) {
1592 printf("status=%i", p->status);
1594 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1598 printf("signal=%s", signal_to_string(p->status));
1601 if (i->main_pid == p->pid &&
1602 i->start_timestamp == p->start_timestamp &&
1603 i->exit_timestamp == p->start_timestamp)
1604 /* Let's not show this twice */
1607 if (p->pid == i->control_pid)
1611 if (i->main_pid > 0 || i->control_pid > 0) {
1614 if (i->main_pid > 0) {
1615 printf(" Main: %u", (unsigned) i->main_pid);
1619 get_process_name(i->main_pid, &t);
1624 } else if (i->exit_code > 0) {
1625 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1627 if (i->exit_code == CLD_EXITED) {
1630 printf("status=%i", i->exit_status);
1632 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1636 printf("signal=%s", signal_to_string(i->exit_status));
1641 if (i->main_pid > 0 && i->control_pid > 0)
1644 if (i->control_pid > 0) {
1647 printf(" Control: %u", (unsigned) i->control_pid);
1649 get_process_name(i->control_pid, &t);
1660 printf("\t Status: \"%s\"\n", i->status_text);
1662 if (i->default_control_group) {
1665 printf("\t CGroup: %s\n", i->default_control_group);
1667 if ((c = columns()) > 18)
1672 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
1675 if (i->need_daemon_reload)
1676 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1677 ansi_highlight(true),
1678 ansi_highlight(false),
1679 arg_session ? "--session" : "--system");
1682 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1684 switch (dbus_message_iter_get_arg_type(iter)) {
1686 case DBUS_TYPE_STRING: {
1689 dbus_message_iter_get_basic(iter, &s);
1692 if (streq(name, "Id"))
1694 else if (streq(name, "LoadState"))
1696 else if (streq(name, "ActiveState"))
1697 i->active_state = s;
1698 else if (streq(name, "SubState"))
1700 else if (streq(name, "Description"))
1702 else if (streq(name, "FragmentPath"))
1704 else if (streq(name, "SysVPath")) {
1707 } else if (streq(name, "DefaultControlGroup"))
1708 i->default_control_group = s;
1709 else if (streq(name, "StatusText"))
1711 else if (streq(name, "SysFSPath"))
1713 else if (streq(name, "Where"))
1715 else if (streq(name, "What"))
1722 case DBUS_TYPE_BOOLEAN: {
1725 dbus_message_iter_get_basic(iter, &b);
1727 if (streq(name, "Accept"))
1729 else if (streq(name, "NeedDaemonReload"))
1730 i->need_daemon_reload = b;
1735 case DBUS_TYPE_UINT32: {
1738 dbus_message_iter_get_basic(iter, &u);
1740 if (streq(name, "MainPID")) {
1742 i->main_pid = (pid_t) u;
1745 } else if (streq(name, "ControlPID"))
1746 i->control_pid = (pid_t) u;
1747 else if (streq(name, "ExecMainPID")) {
1749 i->main_pid = (pid_t) u;
1750 } else if (streq(name, "NAccepted"))
1752 else if (streq(name, "NConnections"))
1753 i->n_connections = u;
1758 case DBUS_TYPE_INT32: {
1761 dbus_message_iter_get_basic(iter, &j);
1763 if (streq(name, "ExecMainCode"))
1764 i->exit_code = (int) j;
1765 else if (streq(name, "ExecMainStatus"))
1766 i->exit_status = (int) j;
1771 case DBUS_TYPE_UINT64: {
1774 dbus_message_iter_get_basic(iter, &u);
1776 if (streq(name, "ExecMainStartTimestamp"))
1777 i->start_timestamp = (usec_t) u;
1778 else if (streq(name, "ExecMainExitTimestamp"))
1779 i->exit_timestamp = (usec_t) u;
1784 case DBUS_TYPE_ARRAY: {
1786 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
1787 startswith(name, "Exec")) {
1788 DBusMessageIter sub;
1790 dbus_message_iter_recurse(iter, &sub);
1791 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1792 ExecStatusInfo *info;
1795 if (!(info = new0(ExecStatusInfo, 1)))
1798 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
1803 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
1805 dbus_message_iter_next(&sub);
1816 static int print_property(const char *name, DBusMessageIter *iter) {
1820 /* This is a low-level property printer, see
1821 * print_status_info() for the nicer output */
1823 if (arg_property && !strv_find(arg_property, name))
1826 switch (dbus_message_iter_get_arg_type(iter)) {
1828 case DBUS_TYPE_STRING: {
1830 dbus_message_iter_get_basic(iter, &s);
1832 if (arg_all || s[0])
1833 printf("%s=%s\n", name, s);
1838 case DBUS_TYPE_BOOLEAN: {
1840 dbus_message_iter_get_basic(iter, &b);
1841 printf("%s=%s\n", name, yes_no(b));
1846 case DBUS_TYPE_UINT64: {
1848 dbus_message_iter_get_basic(iter, &u);
1850 /* Yes, heuristics! But we can change this check
1851 * should it turn out to not be sufficient */
1853 if (strstr(name, "Timestamp")) {
1854 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
1856 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
1857 printf("%s=%s\n", name, strempty(t));
1858 } else if (strstr(name, "USec")) {
1859 char timespan[FORMAT_TIMESPAN_MAX];
1861 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
1863 printf("%s=%llu\n", name, (unsigned long long) u);
1868 case DBUS_TYPE_UINT32: {
1870 dbus_message_iter_get_basic(iter, &u);
1872 if (strstr(name, "UMask") || strstr(name, "Mode"))
1873 printf("%s=%04o\n", name, u);
1875 printf("%s=%u\n", name, (unsigned) u);
1880 case DBUS_TYPE_INT32: {
1882 dbus_message_iter_get_basic(iter, &i);
1884 printf("%s=%i\n", name, (int) i);
1888 case DBUS_TYPE_STRUCT: {
1889 DBusMessageIter sub;
1890 dbus_message_iter_recurse(iter, &sub);
1892 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
1895 dbus_message_iter_get_basic(&sub, &u);
1898 printf("%s=%u\n", name, (unsigned) u);
1900 printf("%s=\n", name);
1903 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
1906 dbus_message_iter_get_basic(&sub, &s);
1908 if (arg_all || s[0])
1909 printf("%s=%s\n", name, s);
1917 case DBUS_TYPE_ARRAY:
1919 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
1920 DBusMessageIter sub;
1923 dbus_message_iter_recurse(iter, &sub);
1925 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1926 printf("%s=", name);
1928 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1931 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
1932 dbus_message_iter_get_basic(&sub, &s);
1933 printf("%s%s", space ? " " : "", s);
1936 dbus_message_iter_next(&sub);
1944 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
1945 DBusMessageIter sub;
1947 dbus_message_iter_recurse(iter, &sub);
1949 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1950 printf("%s=", name);
1952 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1955 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
1956 dbus_message_iter_get_basic(&sub, &u);
1959 dbus_message_iter_next(&sub);
1967 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
1968 DBusMessageIter sub, sub2;
1970 dbus_message_iter_recurse(iter, &sub);
1971 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1972 const char *type, *path;
1974 dbus_message_iter_recurse(&sub, &sub2);
1976 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
1977 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
1978 printf("%s=%s\n", type, path);
1980 dbus_message_iter_next(&sub);
1985 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
1986 DBusMessageIter sub, sub2;
1988 dbus_message_iter_recurse(iter, &sub);
1989 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1991 uint64_t value, next_elapse;
1993 dbus_message_iter_recurse(&sub, &sub2);
1995 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
1996 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
1997 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
1998 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2000 printf("%s={ value=%s ; next_elapse=%s }\n",
2002 format_timespan(timespan1, sizeof(timespan1), value),
2003 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2006 dbus_message_iter_next(&sub);
2011 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2012 DBusMessageIter sub;
2014 dbus_message_iter_recurse(iter, &sub);
2015 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2016 ExecStatusInfo info;
2019 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2020 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2023 t = strv_join(info.argv, " ");
2025 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2029 yes_no(info.ignore),
2030 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2031 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2032 (unsigned) info. pid,
2033 sigchld_code_to_string(info.code),
2035 info.code == CLD_EXITED ? "" : "/",
2036 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2042 strv_free(info.argv);
2044 dbus_message_iter_next(&sub);
2054 printf("%s=[unprintable]\n", name);
2059 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2060 DBusMessage *m = NULL, *reply = NULL;
2061 const char *interface = "";
2064 DBusMessageIter iter, sub, sub2, sub3;
2065 UnitStatusInfo info;
2073 dbus_error_init(&error);
2075 if (!(m = dbus_message_new_method_call(
2076 "org.freedesktop.systemd1",
2078 "org.freedesktop.DBus.Properties",
2080 log_error("Could not allocate message.");
2085 if (!dbus_message_append_args(m,
2086 DBUS_TYPE_STRING, &interface,
2087 DBUS_TYPE_INVALID)) {
2088 log_error("Could not append arguments to message.");
2093 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2094 log_error("Failed to issue method call: %s", error.message);
2099 if (!dbus_message_iter_init(reply, &iter) ||
2100 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2101 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2102 log_error("Failed to parse reply.");
2107 dbus_message_iter_recurse(&iter, &sub);
2114 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2117 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2118 log_error("Failed to parse reply.");
2123 dbus_message_iter_recurse(&sub, &sub2);
2125 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2126 log_error("Failed to parse reply.");
2131 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2132 log_error("Failed to parse reply.");
2137 dbus_message_iter_recurse(&sub2, &sub3);
2139 if (show_properties)
2140 r = print_property(name, &sub3);
2142 r = status_property(name, &sub3, &info);
2145 log_error("Failed to parse reply.");
2150 dbus_message_iter_next(&sub);
2153 if (!show_properties)
2154 print_status_info(&info);
2156 while ((p = info.exec)) {
2157 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2158 exec_status_info_free(p);
2165 dbus_message_unref(m);
2168 dbus_message_unref(reply);
2170 dbus_error_free(&error);
2175 static int show(DBusConnection *bus, char **args, unsigned n) {
2176 DBusMessage *m = NULL, *reply = NULL;
2180 bool show_properties, new_line = false;
2185 dbus_error_init(&error);
2187 show_properties = !streq(args[0], "status");
2189 if (show_properties && n <= 1) {
2190 /* If not argument is specified inspect the manager
2193 r = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2197 for (i = 1; i < n; i++) {
2198 const char *path = NULL;
2201 if (safe_atou32(args[i], &id) < 0) {
2203 /* Interpret as unit name */
2205 if (!(m = dbus_message_new_method_call(
2206 "org.freedesktop.systemd1",
2207 "/org/freedesktop/systemd1",
2208 "org.freedesktop.systemd1.Manager",
2210 log_error("Could not allocate message.");
2215 if (!dbus_message_append_args(m,
2216 DBUS_TYPE_STRING, &args[i],
2217 DBUS_TYPE_INVALID)) {
2218 log_error("Could not append arguments to message.");
2223 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2225 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2226 log_error("Failed to issue method call: %s", error.message);
2231 dbus_error_free(&error);
2233 dbus_message_unref(m);
2234 if (!(m = dbus_message_new_method_call(
2235 "org.freedesktop.systemd1",
2236 "/org/freedesktop/systemd1",
2237 "org.freedesktop.systemd1.Manager",
2239 log_error("Could not allocate message.");
2244 if (!dbus_message_append_args(m,
2245 DBUS_TYPE_STRING, &args[i],
2246 DBUS_TYPE_INVALID)) {
2247 log_error("Could not append arguments to message.");
2252 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2253 log_error("Failed to issue method call: %s", error.message);
2259 } else if (show_properties) {
2261 /* Interpret as job id */
2263 if (!(m = dbus_message_new_method_call(
2264 "org.freedesktop.systemd1",
2265 "/org/freedesktop/systemd1",
2266 "org.freedesktop.systemd1.Manager",
2268 log_error("Could not allocate message.");
2273 if (!dbus_message_append_args(m,
2274 DBUS_TYPE_UINT32, &id,
2275 DBUS_TYPE_INVALID)) {
2276 log_error("Could not append arguments to message.");
2281 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2282 log_error("Failed to issue method call: %s", error.message);
2288 /* Interpret as PID */
2290 if (!(m = dbus_message_new_method_call(
2291 "org.freedesktop.systemd1",
2292 "/org/freedesktop/systemd1",
2293 "org.freedesktop.systemd1.Manager",
2295 log_error("Could not allocate message.");
2300 if (!dbus_message_append_args(m,
2301 DBUS_TYPE_UINT32, &id,
2302 DBUS_TYPE_INVALID)) {
2303 log_error("Could not append arguments to message.");
2308 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2309 log_error("Failed to issue method call: %s", error.message);
2315 if (!dbus_message_get_args(reply, &error,
2316 DBUS_TYPE_OBJECT_PATH, &path,
2317 DBUS_TYPE_INVALID)) {
2318 log_error("Failed to parse reply: %s", error.message);
2323 if ((r = show_one(bus, path, show_properties, &new_line)) < 0)
2326 dbus_message_unref(m);
2327 dbus_message_unref(reply);
2335 dbus_message_unref(m);
2338 dbus_message_unref(reply);
2340 dbus_error_free(&error);
2345 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2347 DBusMessage *m = NULL, *reply = NULL;
2352 dbus_error_init(&error);
2354 log_debug("Got D-Bus request: %s.%s() on %s",
2355 dbus_message_get_interface(message),
2356 dbus_message_get_member(message),
2357 dbus_message_get_path(message));
2359 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2360 log_error("Warning! D-Bus connection terminated.");
2361 dbus_connection_close(connection);
2363 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2364 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2365 const char *id, *path;
2367 if (!dbus_message_get_args(message, &error,
2368 DBUS_TYPE_STRING, &id,
2369 DBUS_TYPE_OBJECT_PATH, &path,
2371 log_error("Failed to parse message: %s", error.message);
2372 else if (streq(dbus_message_get_member(message), "UnitNew"))
2373 printf("Unit %s added.\n", id);
2375 printf("Unit %s removed.\n", id);
2377 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2378 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2382 if (!dbus_message_get_args(message, &error,
2383 DBUS_TYPE_UINT32, &id,
2384 DBUS_TYPE_OBJECT_PATH, &path,
2386 log_error("Failed to parse message: %s", error.message);
2387 else if (streq(dbus_message_get_member(message), "JobNew"))
2388 printf("Job %u added.\n", id);
2390 printf("Job %u removed.\n", id);
2393 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Unit", "Changed") ||
2394 dbus_message_is_signal(message, "org.freedesktop.systemd1.Job", "Changed")) {
2396 const char *path, *interface, *property = "Id";
2397 DBusMessageIter iter, sub;
2399 path = dbus_message_get_path(message);
2400 interface = dbus_message_get_interface(message);
2402 if (!(m = dbus_message_new_method_call(
2403 "org.freedesktop.systemd1",
2405 "org.freedesktop.DBus.Properties",
2407 log_error("Could not allocate message.");
2411 if (!dbus_message_append_args(m,
2412 DBUS_TYPE_STRING, &interface,
2413 DBUS_TYPE_STRING, &property,
2414 DBUS_TYPE_INVALID)) {
2415 log_error("Could not append arguments to message.");
2419 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2420 log_error("Failed to issue method call: %s", error.message);
2424 if (!dbus_message_iter_init(reply, &iter) ||
2425 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2426 log_error("Failed to parse reply.");
2430 dbus_message_iter_recurse(&iter, &sub);
2432 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2435 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2436 log_error("Failed to parse reply.");
2440 dbus_message_iter_get_basic(&sub, &id);
2441 printf("Unit %s changed.\n", id);
2445 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2446 log_error("Failed to parse reply.");
2450 dbus_message_iter_get_basic(&sub, &id);
2451 printf("Job %u changed.\n", id);
2457 dbus_message_unref(m);
2460 dbus_message_unref(reply);
2462 dbus_error_free(&error);
2463 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2467 dbus_message_unref(m);
2470 dbus_message_unref(reply);
2472 dbus_error_free(&error);
2473 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2476 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2477 DBusMessage *m = NULL, *reply = NULL;
2481 dbus_error_init(&error);
2484 dbus_bus_add_match(bus,
2486 "sender='org.freedesktop.systemd1',"
2487 "interface='org.freedesktop.systemd1.Manager',"
2488 "path='/org/freedesktop/systemd1'",
2491 if (dbus_error_is_set(&error)) {
2492 log_error("Failed to add match: %s", error.message);
2497 dbus_bus_add_match(bus,
2499 "sender='org.freedesktop.systemd1',"
2500 "interface='org.freedesktop.systemd1.Unit',"
2504 if (dbus_error_is_set(&error)) {
2505 log_error("Failed to add match: %s", error.message);
2510 dbus_bus_add_match(bus,
2512 "sender='org.freedesktop.systemd1',"
2513 "interface='org.freedesktop.systemd1.Job',"
2517 if (dbus_error_is_set(&error)) {
2518 log_error("Failed to add match: %s", error.message);
2524 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2525 log_error("Failed to add filter.");
2530 if (!(m = dbus_message_new_method_call(
2531 "org.freedesktop.systemd1",
2532 "/org/freedesktop/systemd1",
2533 "org.freedesktop.systemd1.Manager",
2535 log_error("Could not allocate message.");
2540 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2541 log_error("Failed to issue method call: %s", error.message);
2546 while (dbus_connection_read_write_dispatch(bus, -1))
2553 /* This is slightly dirty, since we don't undo the filter or the matches. */
2556 dbus_message_unref(m);
2559 dbus_message_unref(reply);
2561 dbus_error_free(&error);
2566 static int dump(DBusConnection *bus, char **args, unsigned n) {
2567 DBusMessage *m = NULL, *reply = NULL;
2572 dbus_error_init(&error);
2574 if (!(m = dbus_message_new_method_call(
2575 "org.freedesktop.systemd1",
2576 "/org/freedesktop/systemd1",
2577 "org.freedesktop.systemd1.Manager",
2579 log_error("Could not allocate message.");
2583 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2584 log_error("Failed to issue method call: %s", error.message);
2589 if (!dbus_message_get_args(reply, &error,
2590 DBUS_TYPE_STRING, &text,
2591 DBUS_TYPE_INVALID)) {
2592 log_error("Failed to parse reply: %s", error.message);
2597 fputs(text, stdout);
2603 dbus_message_unref(m);
2606 dbus_message_unref(reply);
2608 dbus_error_free(&error);
2613 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2614 DBusMessage *m = NULL, *reply = NULL;
2617 const char *name = "", *path, *id;
2618 dbus_bool_t cleanup = FALSE;
2619 DBusMessageIter iter, sub;
2621 *interface = "org.freedesktop.systemd1.Unit",
2624 dbus_error_init(&error);
2626 if (!(m = dbus_message_new_method_call(
2627 "org.freedesktop.systemd1",
2628 "/org/freedesktop/systemd1",
2629 "org.freedesktop.systemd1.Manager",
2630 "CreateSnapshot"))) {
2631 log_error("Could not allocate message.");
2638 if (!dbus_message_append_args(m,
2639 DBUS_TYPE_STRING, &name,
2640 DBUS_TYPE_BOOLEAN, &cleanup,
2641 DBUS_TYPE_INVALID)) {
2642 log_error("Could not append arguments to message.");
2647 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2648 log_error("Failed to issue method call: %s", error.message);
2653 if (!dbus_message_get_args(reply, &error,
2654 DBUS_TYPE_OBJECT_PATH, &path,
2655 DBUS_TYPE_INVALID)) {
2656 log_error("Failed to parse reply: %s", error.message);
2661 dbus_message_unref(m);
2662 if (!(m = dbus_message_new_method_call(
2663 "org.freedesktop.systemd1",
2665 "org.freedesktop.DBus.Properties",
2667 log_error("Could not allocate message.");
2671 if (!dbus_message_append_args(m,
2672 DBUS_TYPE_STRING, &interface,
2673 DBUS_TYPE_STRING, &property,
2674 DBUS_TYPE_INVALID)) {
2675 log_error("Could not append arguments to message.");
2680 dbus_message_unref(reply);
2681 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2682 log_error("Failed to issue method call: %s", error.message);
2687 if (!dbus_message_iter_init(reply, &iter) ||
2688 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2689 log_error("Failed to parse reply.");
2694 dbus_message_iter_recurse(&iter, &sub);
2696 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2697 log_error("Failed to parse reply.");
2702 dbus_message_iter_get_basic(&sub, &id);
2710 dbus_message_unref(m);
2713 dbus_message_unref(reply);
2715 dbus_error_free(&error);
2720 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2721 DBusMessage *m = NULL, *reply = NULL;
2729 dbus_error_init(&error);
2731 for (i = 1; i < n; i++) {
2732 const char *path = NULL;
2734 if (!(m = dbus_message_new_method_call(
2735 "org.freedesktop.systemd1",
2736 "/org/freedesktop/systemd1",
2737 "org.freedesktop.systemd1.Manager",
2739 log_error("Could not allocate message.");
2744 if (!dbus_message_append_args(m,
2745 DBUS_TYPE_STRING, &args[i],
2746 DBUS_TYPE_INVALID)) {
2747 log_error("Could not append arguments to message.");
2752 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2753 log_error("Failed to issue method call: %s", error.message);
2758 if (!dbus_message_get_args(reply, &error,
2759 DBUS_TYPE_OBJECT_PATH, &path,
2760 DBUS_TYPE_INVALID)) {
2761 log_error("Failed to parse reply: %s", error.message);
2766 dbus_message_unref(m);
2767 if (!(m = dbus_message_new_method_call(
2768 "org.freedesktop.systemd1",
2770 "org.freedesktop.systemd1.Snapshot",
2772 log_error("Could not allocate message.");
2777 dbus_message_unref(reply);
2778 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2779 log_error("Failed to issue method call: %s", error.message);
2784 dbus_message_unref(m);
2785 dbus_message_unref(reply);
2793 dbus_message_unref(m);
2796 dbus_message_unref(reply);
2798 dbus_error_free(&error);
2803 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2804 DBusMessage *m = NULL, *reply = NULL;
2809 dbus_error_init(&error);
2811 if (arg_action == ACTION_RELOAD)
2813 else if (arg_action == ACTION_REEXEC)
2814 method = "Reexecute";
2816 assert(arg_action == ACTION_SYSTEMCTL);
2819 streq(args[0], "clear-jobs") ||
2820 streq(args[0], "cancel") ? "ClearJobs" :
2821 streq(args[0], "daemon-reexec") ? "Reexecute" :
2822 streq(args[0], "reset-maintenance") ? "ResetMaintenance" :
2823 streq(args[0], "daemon-exit") ? "Exit" :
2827 if (!(m = dbus_message_new_method_call(
2828 "org.freedesktop.systemd1",
2829 "/org/freedesktop/systemd1",
2830 "org.freedesktop.systemd1.Manager",
2832 log_error("Could not allocate message.");
2836 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2838 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
2839 /* There's always a fallback possible for
2840 * legacy actions. */
2845 log_error("Failed to issue method call: %s", error.message);
2854 dbus_message_unref(m);
2857 dbus_message_unref(reply);
2859 dbus_error_free(&error);
2864 static int reset_maintenance(DBusConnection *bus, char **args, unsigned n) {
2865 DBusMessage *m = NULL, *reply = NULL;
2871 dbus_error_init(&error);
2874 return daemon_reload(bus, args, n);
2876 for (i = 1; i < n; i++) {
2878 if (!(m = dbus_message_new_method_call(
2879 "org.freedesktop.systemd1",
2880 "/org/freedesktop/systemd1",
2881 "org.freedesktop.systemd1.Manager",
2882 "ResetMaintenanceUnit"))) {
2883 log_error("Could not allocate message.");
2888 if (!dbus_message_append_args(m,
2889 DBUS_TYPE_STRING, args + i,
2890 DBUS_TYPE_INVALID)) {
2891 log_error("Could not append arguments to message.");
2896 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2897 log_error("Failed to issue method call: %s", error.message);
2902 dbus_message_unref(m);
2903 dbus_message_unref(reply);
2911 dbus_message_unref(m);
2914 dbus_message_unref(reply);
2916 dbus_error_free(&error);
2921 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
2922 DBusMessage *m = NULL, *reply = NULL;
2924 DBusMessageIter iter, sub, sub2;
2927 *interface = "org.freedesktop.systemd1.Manager",
2928 *property = "Environment";
2930 dbus_error_init(&error);
2932 if (!(m = dbus_message_new_method_call(
2933 "org.freedesktop.systemd1",
2934 "/org/freedesktop/systemd1",
2935 "org.freedesktop.DBus.Properties",
2937 log_error("Could not allocate message.");
2941 if (!dbus_message_append_args(m,
2942 DBUS_TYPE_STRING, &interface,
2943 DBUS_TYPE_STRING, &property,
2944 DBUS_TYPE_INVALID)) {
2945 log_error("Could not append arguments to message.");
2950 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2951 log_error("Failed to issue method call: %s", error.message);
2956 if (!dbus_message_iter_init(reply, &iter) ||
2957 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2958 log_error("Failed to parse reply.");
2963 dbus_message_iter_recurse(&iter, &sub);
2965 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
2966 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
2967 log_error("Failed to parse reply.");
2972 dbus_message_iter_recurse(&sub, &sub2);
2974 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
2977 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
2978 log_error("Failed to parse reply.");
2983 dbus_message_iter_get_basic(&sub2, &text);
2984 printf("%s\n", text);
2986 dbus_message_iter_next(&sub2);
2993 dbus_message_unref(m);
2996 dbus_message_unref(reply);
2998 dbus_error_free(&error);
3003 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3004 DBusMessage *m = NULL, *reply = NULL;
3008 DBusMessageIter iter, sub;
3011 dbus_error_init(&error);
3013 method = streq(args[0], "set-environment")
3015 : "UnsetEnvironment";
3017 if (!(m = dbus_message_new_method_call(
3018 "org.freedesktop.systemd1",
3019 "/org/freedesktop/systemd1",
3020 "org.freedesktop.systemd1.Manager",
3023 log_error("Could not allocate message.");
3027 dbus_message_iter_init_append(m, &iter);
3029 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3030 log_error("Could not append arguments to message.");
3035 for (i = 1; i < n; i++)
3036 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3037 log_error("Could not append arguments to message.");
3042 if (!dbus_message_iter_close_container(&iter, &sub)) {
3043 log_error("Could not append arguments to message.");
3048 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3049 log_error("Failed to issue method call: %s", error.message);
3058 dbus_message_unref(m);
3061 dbus_message_unref(reply);
3063 dbus_error_free(&error);
3076 static Hashmap *will_install = NULL, *have_installed = NULL;
3077 static Set *remove_symlinks_to = NULL;
3079 static void install_info_free(InstallInfo *i) {
3084 strv_free(i->aliases);
3085 strv_free(i->wanted_by);
3089 static void install_info_hashmap_free(Hashmap *m) {
3092 while ((i = hashmap_steal_first(m)))
3093 install_info_free(i);
3098 static bool unit_name_valid(const char *name) {
3100 /* This is a minimal version of unit_name_valid() from
3106 if (ignore_file(name))
3112 static int install_info_add(const char *name) {
3116 assert(will_install);
3118 if (!unit_name_valid(name))
3121 if (hashmap_get(have_installed, name) ||
3122 hashmap_get(will_install, name))
3125 if (!(i = new0(InstallInfo, 1))) {
3130 if (!(i->name = strdup(name))) {
3135 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3142 install_info_free(i);
3147 static int config_parse_also(
3148 const char *filename,
3150 const char *section,
3164 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3168 if (!(n = strndup(w, l)))
3171 r = install_info_add(n);
3181 static int mark_symlink_for_removal(const char *p) {
3186 assert(path_is_absolute(p));
3188 if (!remove_symlinks_to)
3191 if (!(n = strdup(p)))
3194 path_kill_slashes(n);
3196 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3198 return r == -EEXIST ? 0 : r;
3204 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3213 if (!(d = fdopendir(fd))) {
3214 close_nointr_nofail(fd);
3220 while ((de = readdir(d))) {
3221 bool is_dir = false, is_link = false;
3223 if (ignore_file(de->d_name))
3226 if (de->d_type == DT_LNK)
3228 else if (de->d_type == DT_DIR)
3230 else if (de->d_type == DT_UNKNOWN) {
3233 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3234 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3241 is_link = S_ISLNK(st.st_mode);
3242 is_dir = S_ISDIR(st.st_mode);
3250 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3251 log_error("Failed to open %s/%s: %m", root, de->d_name);
3258 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3259 log_error("Failed to allocate directory string.");
3260 close_nointr_nofail(nfd);
3265 /* This will close nfd, regardless whether it succeeds or not */
3266 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3272 } else if (is_link) {
3276 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3277 log_error("Failed to allocate symlink string.");
3282 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3283 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3291 if ((c = canonicalize_file_name(dest))) {
3292 /* This might fail if the destination
3293 * is already removed */
3299 path_kill_slashes(dest);
3300 if (set_get(remove_symlinks_to, dest)) {
3303 log_info("rm '%s'", p);
3305 if (unlink(p) < 0) {
3306 log_error("Cannot unlink symlink %s: %m", p);
3311 rmdir_parents(p, config_path);
3312 path_kill_slashes(p);
3314 if (!set_get(remove_symlinks_to, p)) {
3316 if ((r = mark_symlink_for_removal(p)) < 0) {
3335 static int remove_marked_symlinks(const char *config_path) {
3339 assert(config_path);
3341 if (set_size(remove_symlinks_to) <= 0)
3344 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3351 if ((cfd = dup(fd)) < 0) {
3356 /* This takes possession of cfd and closes it */
3357 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3363 close_nointr_nofail(fd);
3368 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3375 if (streq(verb, "enable")) {
3378 mkdir_parents(new_path, 0755);
3380 if (symlink(old_path, new_path) >= 0) {
3383 log_info("ln -s '%s' '%s'", old_path, new_path);
3388 if (errno != EEXIST) {
3389 log_error("Cannot link %s to %s: %m", old_path, new_path);
3393 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3395 if (errno == EINVAL) {
3396 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3400 log_error("readlink() failed: %s", strerror(-r));
3404 if (streq(dest, old_path)) {
3410 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3419 log_info("ln -s '%s' '%s'", old_path, new_path);
3421 if (symlink(old_path, new_path) >= 0)
3424 log_error("Cannot link %s to %s: %m", old_path, new_path);
3427 } else if (streq(verb, "disable")) {
3430 if ((r = mark_symlink_for_removal(old_path)) < 0)
3433 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3434 if (errno == ENOENT)
3437 if (errno == EINVAL) {
3438 log_warning("File %s not a symlink, ignoring.", old_path);
3442 log_error("readlink() failed: %s", strerror(-r));
3446 if (!streq(dest, old_path)) {
3447 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3454 if ((r = mark_symlink_for_removal(new_path)) < 0)
3458 log_info("rm '%s'", new_path);
3460 if (unlink(new_path) >= 0)
3463 log_error("Cannot unlink %s: %m", new_path);
3466 } else if (streq(verb, "is-enabled")) {
3469 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3471 if (errno == ENOENT || errno == EINVAL)
3474 log_error("readlink() failed: %s", strerror(-r));
3478 if (streq(dest, old_path)) {
3486 assert_not_reached("Unknown action.");
3489 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3491 char *alias_path = NULL;
3496 assert(config_path);
3498 STRV_FOREACH(s, i->aliases) {
3500 if (!unit_name_valid(*s)) {
3501 log_error("Invalid name %s.", *s);
3507 if (!(alias_path = path_make_absolute(*s, config_path))) {
3508 log_error("Out of memory");
3513 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3516 if (streq(verb, "disable"))
3517 rmdir_parents(alias_path, config_path);
3528 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3530 char *alias_path = NULL;
3535 assert(config_path);
3537 STRV_FOREACH(s, i->wanted_by) {
3538 if (!unit_name_valid(*s)) {
3539 log_error("Invalid name %s.", *s);
3547 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3548 log_error("Out of memory");
3553 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3556 if (streq(verb, "disable"))
3557 rmdir_parents(alias_path, config_path);
3568 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3570 const ConfigItem items[] = {
3571 { "Alias", config_parse_strv, &i->aliases, "Install" },
3572 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3573 { "Also", config_parse_also, NULL, "Install" },
3575 { NULL, NULL, NULL, NULL }
3579 char *filename = NULL;
3586 STRV_FOREACH(p, paths->unit_path) {
3589 if (!(filename = path_make_absolute(i->name, *p))) {
3590 log_error("Out of memory");
3594 /* Ensure that we don't follow symlinks */
3595 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3596 if ((f = fdopen(fd, "re")))
3599 if (errno == ELOOP) {
3600 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3605 if (errno != ENOENT) {
3606 log_error("Failed to open %s: %m", filename);
3616 log_error("Couldn't find %s.", i->name);
3622 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3629 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3632 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3635 if ((r = mark_symlink_for_removal(filename)) < 0)
3638 if ((r = remove_marked_symlinks(config_path)) < 0)
3644 static char *get_config_path(void) {
3646 if (arg_session && arg_global)
3647 return strdup(SESSION_CONFIG_UNIT_PATH);
3652 if (session_config_home(&p) < 0)
3658 return strdup(SYSTEM_CONFIG_UNIT_PATH);
3661 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3665 char *config_path = NULL;
3668 const char *verb = args[0];
3670 dbus_error_init(&error);
3673 if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3674 log_error("Failed to determine lookup paths: %s", strerror(-r));
3678 if (!(config_path = get_config_path())) {
3679 log_error("Failed to determine config path");
3684 will_install = hashmap_new(string_hash_func, string_compare_func);
3685 have_installed = hashmap_new(string_hash_func, string_compare_func);
3687 if (!will_install || !have_installed) {
3688 log_error("Failed to allocate unit sets.");
3693 if (!arg_defaults && streq(verb, "disable"))
3694 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3695 log_error("Failed to allocate symlink sets.");
3700 for (j = 1; j < n; j++)
3701 if ((r = install_info_add(args[j])) < 0)
3704 while ((i = hashmap_first(will_install))) {
3707 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3709 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3717 /* In test mode and found something */
3723 if (streq(verb, "is-enabled"))
3724 r = r > 0 ? 0 : -ENOENT;
3726 /* Don't try to reload anything if the user asked us to not do this */
3728 /* Don't try to reload anything when updating a unit globally */
3730 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3731 (arg_session || sd_booted() > 0) &&
3732 /* Don't try to reload anything if we are running in a chroot environment */
3733 (arg_session || running_in_chroot() <= 0) ) {
3736 if ((q = daemon_reload(bus, args, n)) < 0)
3741 install_info_hashmap_free(will_install);
3742 install_info_hashmap_free(have_installed);
3744 set_free_free(remove_symlinks_to);
3746 lookup_paths_free(&paths);
3753 static int systemctl_help(void) {
3755 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3756 "Send control commands to or query the systemd manager.\n\n"
3757 " -h --help Show this help\n"
3758 " -t --type=TYPE List only units of a particular type\n"
3759 " -p --property=NAME Show only properties by this name\n"
3760 " -a --all Show all units/properties, including dead/empty ones\n"
3761 " --full Don't ellipsize unit names on output\n"
3762 " --fail When queueing a new job, fail if conflicting jobs are\n"
3764 " -q --quiet Suppress output\n"
3765 " --no-block Do not wait until operation finished\n"
3766 " --system Connect to system bus\n"
3767 " --session Connect to session bus\n"
3768 " --order When generating graph for dot, show only order\n"
3769 " --require When generating graph for dot, show only requirement\n"
3770 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3771 " --global Enable/disable unit files globally\n"
3772 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3774 " --force When enabling unit files, override existing symlinks\n"
3775 " --defaults When disabling unit files, remove default symlinks only\n\n"
3777 " list-units List units\n"
3778 " start [NAME...] Start (activate) one or more units\n"
3779 " stop [NAME...] Stop (deactivate) one or more units\n"
3780 " reload [NAME...] Reload one or more units\n"
3781 " restart [NAME...] Start or restart one or more units\n"
3782 " try-restart [NAME...] Restart one or more units if active\n"
3783 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3784 " otherwise start or restart\n"
3785 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3786 " otherwise restart if active\n"
3787 " isolate [NAME] Start one unit and stop all others\n"
3788 " is-active [NAME...] Check whether units are active\n"
3789 " status [NAME...|PID...] Show runtime status of one or more units\n"
3790 " show [NAME...|JOB...] Show properties of one or more\n"
3791 " units/jobs or the manager\n"
3792 " reset-maintenance [NAME...] Reset maintenance state for all, one,\n"
3794 " enable [NAME...] Enable one or more unit files\n"
3795 " disable [NAME...] Disable one or more unit files\n"
3796 " is-enabled [NAME...] Check whether unit files are enabled\n"
3797 " load [NAME...] Load one or more units\n"
3798 " list-jobs List jobs\n"
3799 " cancel [JOB...] Cancel all, one, or more jobs\n"
3800 " monitor Monitor unit/job changes\n"
3801 " dump Dump server status\n"
3802 " dot Dump dependency graph for dot(1)\n"
3803 " snapshot [NAME] Create a snapshot\n"
3804 " delete [NAME...] Remove one or more snapshots\n"
3805 " daemon-reload Reload systemd manager configuration\n"
3806 " daemon-reexec Reexecute systemd manager\n"
3807 " daemon-exit Ask the systemd manager to quit\n"
3808 " show-environment Dump environment\n"
3809 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3810 " unset-environment [NAME...] Unset one or more environment variables\n"
3811 " halt Shut down and halt the system\n"
3812 " poweroff Shut down and power-off the system\n"
3813 " reboot Shut down and reboot the system\n"
3814 " rescue Enter system rescue mode\n"
3815 " emergency Enter system emergency mode\n"
3816 " default Enter system default mode\n",
3817 program_invocation_short_name);
3822 static int halt_help(void) {
3824 printf("%s [OPTIONS...]\n\n"
3825 "%s the system.\n\n"
3826 " --help Show this help\n"
3827 " --halt Halt the machine\n"
3828 " -p --poweroff Switch off the machine\n"
3829 " --reboot Reboot the machine\n"
3830 " -f --force Force immediate halt/power-off/reboot\n"
3831 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3832 " -d --no-wtmp Don't write wtmp record\n"
3833 " -n --no-sync Don't sync before halt/power-off/reboot\n"
3834 " --no-wall Don't send wall message before halt/power-off/reboot\n",
3835 program_invocation_short_name,
3836 arg_action == ACTION_REBOOT ? "Reboot" :
3837 arg_action == ACTION_POWEROFF ? "Power off" :
3843 static int shutdown_help(void) {
3845 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3846 "Shut down the system.\n\n"
3847 " --help Show this help\n"
3848 " -H --halt Halt the machine\n"
3849 " -P --poweroff Power-off the machine\n"
3850 " -r --reboot Reboot the machine\n"
3851 " -h Equivalent to --poweroff, overriden by --halt\n"
3852 " -k Don't halt/power-off/reboot, just send warnings\n"
3853 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3854 " -c Cancel a pending shutdown\n",
3855 program_invocation_short_name);
3860 static int telinit_help(void) {
3862 printf("%s [OPTIONS...] {COMMAND}\n\n"
3863 "Send control commands to the init daemon.\n\n"
3864 " --help Show this help\n"
3865 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
3867 " 0 Power-off the machine\n"
3868 " 6 Reboot the machine\n"
3869 " 2, 3, 4, 5 Start runlevelX.target unit\n"
3870 " 1, s, S Enter rescue mode\n"
3871 " q, Q Reload init daemon configuration\n"
3872 " u, U Reexecute init daemon\n",
3873 program_invocation_short_name);
3878 static int runlevel_help(void) {
3880 printf("%s [OPTIONS...]\n\n"
3881 "Prints the previous and current runlevel of the init system.\n\n"
3882 " --help Show this help\n",
3883 program_invocation_short_name);
3888 static int systemctl_parse_argv(int argc, char *argv[]) {
3905 static const struct option options[] = {
3906 { "help", no_argument, NULL, 'h' },
3907 { "type", required_argument, NULL, 't' },
3908 { "property", required_argument, NULL, 'p' },
3909 { "all", no_argument, NULL, 'a' },
3910 { "full", no_argument, NULL, ARG_FULL },
3911 { "fail", no_argument, NULL, ARG_FAIL },
3912 { "session", no_argument, NULL, ARG_SESSION },
3913 { "system", no_argument, NULL, ARG_SYSTEM },
3914 { "global", no_argument, NULL, ARG_GLOBAL },
3915 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
3916 { "no-wall", no_argument, NULL, ARG_NO_WALL },
3917 { "quiet", no_argument, NULL, 'q' },
3918 { "order", no_argument, NULL, ARG_ORDER },
3919 { "require", no_argument, NULL, ARG_REQUIRE },
3920 { "force", no_argument, NULL, ARG_FORCE },
3921 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
3922 { "defaults", no_argument, NULL, ARG_DEFAULTS },
3923 { NULL, 0, NULL, 0 }
3931 while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
3946 if (!(l = strv_append(arg_property, optarg)))
3949 strv_free(arg_property);
3952 /* If the user asked for a particular
3953 * property, show it to him, even if it is
3972 arg_session = false;
3976 arg_no_block = true;
3984 arg_dot = DOT_ORDER;
3988 arg_dot = DOT_REQUIRE;
4004 arg_no_reload = true;
4013 arg_defaults = true;
4020 log_error("Unknown option code %c", c);
4028 static int halt_parse_argv(int argc, char *argv[]) {
4037 static const struct option options[] = {
4038 { "help", no_argument, NULL, ARG_HELP },
4039 { "halt", no_argument, NULL, ARG_HALT },
4040 { "poweroff", no_argument, NULL, 'p' },
4041 { "reboot", no_argument, NULL, ARG_REBOOT },
4042 { "force", no_argument, NULL, 'f' },
4043 { "wtmp-only", no_argument, NULL, 'w' },
4044 { "no-wtmp", no_argument, NULL, 'd' },
4045 { "no-sync", no_argument, NULL, 'n' },
4046 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4047 { NULL, 0, NULL, 0 }
4055 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4056 if (runlevel == '0' || runlevel == '6')
4057 arg_immediate = true;
4059 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4067 arg_action = ACTION_HALT;
4071 if (arg_action != ACTION_REBOOT)
4072 arg_action = ACTION_POWEROFF;
4076 arg_action = ACTION_REBOOT;
4080 arg_immediate = true;
4101 /* Compatibility nops */
4108 log_error("Unknown option code %c", c);
4113 if (optind < argc) {
4114 log_error("Too many arguments.");
4121 static int parse_time_spec(const char *t, usec_t *_u) {
4125 if (streq(t, "now"))
4127 else if (t[0] == '+') {
4130 if (safe_atou64(t + 1, &u) < 0)
4133 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4142 hour = strtol(t, &e, 10);
4143 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4146 minute = strtol(e+1, &e, 10);
4147 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4150 n = now(CLOCK_REALTIME);
4151 s = (time_t) (n / USEC_PER_SEC);
4154 assert_se(localtime_r(&s, &tm));
4156 tm.tm_hour = (int) hour;
4157 tm.tm_min = (int) minute;
4160 assert_se(s = mktime(&tm));
4162 *_u = (usec_t) s * USEC_PER_SEC;
4165 *_u += USEC_PER_DAY;
4171 static int shutdown_parse_argv(int argc, char *argv[]) {
4178 static const struct option options[] = {
4179 { "help", no_argument, NULL, ARG_HELP },
4180 { "halt", no_argument, NULL, 'H' },
4181 { "poweroff", no_argument, NULL, 'P' },
4182 { "reboot", no_argument, NULL, 'r' },
4183 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4184 { NULL, 0, NULL, 0 }
4192 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4200 arg_action = ACTION_HALT;
4204 arg_action = ACTION_POWEROFF;
4208 arg_action = ACTION_REBOOT;
4212 if (arg_action != ACTION_HALT)
4213 arg_action = ACTION_POWEROFF;
4226 /* Compatibility nops */
4230 arg_action = ACTION_CANCEL_SHUTDOWN;
4237 log_error("Unknown option code %c", c);
4242 if (argc > optind) {
4243 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4244 log_error("Failed to parse time specification: %s", argv[optind]);
4248 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4250 /* We skip the time argument */
4251 if (argc > optind + 1)
4252 arg_wall = argv + optind + 1;
4259 static int telinit_parse_argv(int argc, char *argv[]) {
4266 static const struct option options[] = {
4267 { "help", no_argument, NULL, ARG_HELP },
4268 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4269 { NULL, 0, NULL, 0 }
4272 static const struct {
4276 { '0', ACTION_POWEROFF },
4277 { '6', ACTION_REBOOT },
4278 { '1', ACTION_RESCUE },
4279 { '2', ACTION_RUNLEVEL2 },
4280 { '3', ACTION_RUNLEVEL3 },
4281 { '4', ACTION_RUNLEVEL4 },
4282 { '5', ACTION_RUNLEVEL5 },
4283 { 's', ACTION_RESCUE },
4284 { 'S', ACTION_RESCUE },
4285 { 'q', ACTION_RELOAD },
4286 { 'Q', ACTION_RELOAD },
4287 { 'u', ACTION_REEXEC },
4288 { 'U', ACTION_REEXEC }
4297 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4312 log_error("Unknown option code %c", c);
4317 if (optind >= argc) {
4322 if (optind + 1 < argc) {
4323 log_error("Too many arguments.");
4327 if (strlen(argv[optind]) != 1) {
4328 log_error("Expected single character argument.");
4332 for (i = 0; i < ELEMENTSOF(table); i++)
4333 if (table[i].from == argv[optind][0])
4336 if (i >= ELEMENTSOF(table)) {
4337 log_error("Unknown command %s.", argv[optind]);
4341 arg_action = table[i].to;
4348 static int runlevel_parse_argv(int argc, char *argv[]) {
4354 static const struct option options[] = {
4355 { "help", no_argument, NULL, ARG_HELP },
4356 { NULL, 0, NULL, 0 }
4364 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4375 log_error("Unknown option code %c", c);
4380 if (optind < argc) {
4381 log_error("Too many arguments.");
4388 static int parse_argv(int argc, char *argv[]) {
4392 if (program_invocation_short_name) {
4394 if (strstr(program_invocation_short_name, "halt")) {
4395 arg_action = ACTION_HALT;
4396 return halt_parse_argv(argc, argv);
4397 } else if (strstr(program_invocation_short_name, "poweroff")) {
4398 arg_action = ACTION_POWEROFF;
4399 return halt_parse_argv(argc, argv);
4400 } else if (strstr(program_invocation_short_name, "reboot")) {
4401 arg_action = ACTION_REBOOT;
4402 return halt_parse_argv(argc, argv);
4403 } else if (strstr(program_invocation_short_name, "shutdown")) {
4404 arg_action = ACTION_POWEROFF;
4405 return shutdown_parse_argv(argc, argv);
4406 } else if (strstr(program_invocation_short_name, "init")) {
4408 if (sd_booted() > 0) {
4409 arg_action = ACTION_INVALID;
4410 return telinit_parse_argv(argc, argv);
4412 /* Hmm, so some other init system is
4413 * running, we need to forward this
4414 * request to it. For now we simply
4415 * guess that it is Upstart. */
4417 execv("/lib/upstart/telinit", argv);
4419 log_error("Couldn't find an alternative telinit implementation to spawn.");
4423 } else if (strstr(program_invocation_short_name, "runlevel")) {
4424 arg_action = ACTION_RUNLEVEL;
4425 return runlevel_parse_argv(argc, argv);
4429 arg_action = ACTION_SYSTEMCTL;
4430 return systemctl_parse_argv(argc, argv);
4433 static int action_to_runlevel(void) {
4435 static const char table[_ACTION_MAX] = {
4436 [ACTION_HALT] = '0',
4437 [ACTION_POWEROFF] = '0',
4438 [ACTION_REBOOT] = '6',
4439 [ACTION_RUNLEVEL2] = '2',
4440 [ACTION_RUNLEVEL3] = '3',
4441 [ACTION_RUNLEVEL4] = '4',
4442 [ACTION_RUNLEVEL5] = '5',
4443 [ACTION_RESCUE] = '1'
4446 assert(arg_action < _ACTION_MAX);
4448 return table[arg_action];
4451 static int talk_upstart(void) {
4452 DBusMessage *m = NULL, *reply = NULL;
4454 int previous, rl, r;
4456 env1_buf[] = "RUNLEVEL=X",
4457 env2_buf[] = "PREVLEVEL=X";
4458 char *env1 = env1_buf, *env2 = env2_buf;
4459 const char *emit = "runlevel";
4460 dbus_bool_t b_false = FALSE;
4461 DBusMessageIter iter, sub;
4462 DBusConnection *bus;
4464 dbus_error_init(&error);
4466 if (!(rl = action_to_runlevel()))
4469 if (utmp_get_runlevel(&previous, NULL) < 0)
4472 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4473 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4478 log_error("Failed to connect to Upstart bus: %s", error.message);
4483 if ((r = bus_check_peercred(bus)) < 0) {
4484 log_error("Failed to verify owner of bus.");
4488 if (!(m = dbus_message_new_method_call(
4489 "com.ubuntu.Upstart",
4490 "/com/ubuntu/Upstart",
4491 "com.ubuntu.Upstart0_6",
4494 log_error("Could not allocate message.");
4499 dbus_message_iter_init_append(m, &iter);
4501 env1_buf[sizeof(env1_buf)-2] = rl;
4502 env2_buf[sizeof(env2_buf)-2] = previous;
4504 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4505 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4506 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4507 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4508 !dbus_message_iter_close_container(&iter, &sub) ||
4509 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4510 log_error("Could not append arguments to message.");
4515 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4517 if (error_is_no_service(&error)) {
4522 log_error("Failed to issue method call: %s", error.message);
4531 dbus_message_unref(m);
4534 dbus_message_unref(reply);
4537 dbus_connection_close(bus);
4538 dbus_connection_unref(bus);
4541 dbus_error_free(&error);
4546 static int talk_initctl(void) {
4547 struct init_request request;
4551 if (!(rl = action_to_runlevel()))
4555 request.magic = INIT_MAGIC;
4556 request.sleeptime = 0;
4557 request.cmd = INIT_CMD_RUNLVL;
4558 request.runlevel = rl;
4560 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4562 if (errno == ENOENT)
4565 log_error("Failed to open "INIT_FIFO": %m");
4570 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4571 close_nointr_nofail(fd);
4574 log_error("Failed to write to "INIT_FIFO": %m");
4575 return errno ? -errno : -EIO;
4581 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4583 static const struct {
4591 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4593 { "list-units", LESS, 1, list_units },
4594 { "list-jobs", EQUAL, 1, list_jobs },
4595 { "clear-jobs", EQUAL, 1, daemon_reload },
4596 { "load", MORE, 2, load_unit },
4597 { "cancel", MORE, 2, cancel_job },
4598 { "start", MORE, 2, start_unit },
4599 { "stop", MORE, 2, start_unit },
4600 { "reload", MORE, 2, start_unit },
4601 { "restart", MORE, 2, start_unit },
4602 { "try-restart", MORE, 2, start_unit },
4603 { "reload-or-restart", MORE, 2, start_unit },
4604 { "reload-or-try-restart", MORE, 2, start_unit },
4605 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4606 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4607 { "isolate", EQUAL, 2, start_unit },
4608 { "is-active", MORE, 2, check_unit },
4609 { "check", MORE, 2, check_unit },
4610 { "show", MORE, 1, show },
4611 { "status", MORE, 2, show },
4612 { "monitor", EQUAL, 1, monitor },
4613 { "dump", EQUAL, 1, dump },
4614 { "dot", EQUAL, 1, dot },
4615 { "snapshot", LESS, 2, snapshot },
4616 { "delete", MORE, 2, delete_snapshot },
4617 { "daemon-reload", EQUAL, 1, daemon_reload },
4618 { "daemon-reexec", EQUAL, 1, daemon_reload },
4619 { "daemon-exit", EQUAL, 1, daemon_reload },
4620 { "show-environment", EQUAL, 1, show_enviroment },
4621 { "set-environment", MORE, 2, set_environment },
4622 { "unset-environment", MORE, 2, set_environment },
4623 { "halt", EQUAL, 1, start_special },
4624 { "poweroff", EQUAL, 1, start_special },
4625 { "reboot", EQUAL, 1, start_special },
4626 { "default", EQUAL, 1, start_special },
4627 { "rescue", EQUAL, 1, start_special },
4628 { "emergency", EQUAL, 1, start_special },
4629 { "reset-maintenance", MORE, 1, reset_maintenance },
4630 { "enable", MORE, 2, enable_unit },
4631 { "disable", MORE, 2, enable_unit },
4632 { "is-enabled", MORE, 2, enable_unit }
4642 left = argc - optind;
4645 /* Special rule: no arguments means "list-units" */
4648 if (streq(argv[optind], "help")) {
4653 for (i = 0; i < ELEMENTSOF(verbs); i++)
4654 if (streq(argv[optind], verbs[i].verb))
4657 if (i >= ELEMENTSOF(verbs)) {
4658 log_error("Unknown operation %s", argv[optind]);
4663 switch (verbs[i].argc_cmp) {
4666 if (left != verbs[i].argc) {
4667 log_error("Invalid number of arguments.");
4674 if (left < verbs[i].argc) {
4675 log_error("Too few arguments.");
4682 if (left > verbs[i].argc) {
4683 log_error("Too many arguments.");
4690 assert_not_reached("Unknown comparison operator.");
4693 /* Require a bus connection for all operations but
4695 if (!streq(verbs[i].verb, "enable") &&
4696 !streq(verbs[i].verb, "disable") &&
4698 log_error("Failed to get D-Bus connection: %s", error->message);
4702 return verbs[i].dispatch(bus, argv + optind, left);
4705 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
4707 struct msghdr msghdr;
4709 union sockaddr_union sockaddr;
4710 struct ucred *ucred;
4712 struct cmsghdr cmsghdr;
4713 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
4715 struct shutdownd_command c;
4723 strncpy(c.wall_message, message, sizeof(c.wall_message));
4725 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4729 sockaddr.sa.sa_family = AF_UNIX;
4730 sockaddr.un.sun_path[0] = 0;
4731 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
4734 iovec.iov_base = (char*) &c;
4735 iovec.iov_len = sizeof(c);
4738 control.cmsghdr.cmsg_level = SOL_SOCKET;
4739 control.cmsghdr.cmsg_type = SCM_CREDENTIALS;
4740 control.cmsghdr.cmsg_len = CMSG_LEN(sizeof(struct ucred));
4742 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
4743 ucred->pid = getpid();
4744 ucred->uid = getuid();
4745 ucred->gid = getgid();
4748 msghdr.msg_name = &sockaddr;
4749 msghdr.msg_namelen = sizeof(sa_family_t) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
4751 msghdr.msg_iov = &iovec;
4752 msghdr.msg_iovlen = 1;
4753 msghdr.msg_control = &control;
4754 msghdr.msg_controllen = control.cmsghdr.cmsg_len;
4756 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
4757 close_nointr_nofail(fd);
4761 close_nointr_nofail(fd);
4765 static int reload_with_fallback(DBusConnection *bus) {
4768 /* First, try systemd via D-Bus. */
4769 if (daemon_reload(bus, NULL, 0) > 0)
4773 /* Nothing else worked, so let's try signals */
4774 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
4776 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
4777 log_error("kill() failed: %m");
4784 static int start_with_fallback(DBusConnection *bus) {
4787 /* First, try systemd via D-Bus. */
4788 if (start_unit(bus, NULL, 0) > 0)
4792 /* Hmm, talking to systemd via D-Bus didn't work. Then
4793 * let's try to talk to Upstart via D-Bus. */
4794 if (talk_upstart() > 0)
4797 /* Nothing else worked, so let's try
4799 if (talk_initctl() > 0)
4802 log_error("Failed to talk to init daemon.");
4806 warn_wall(arg_action);
4810 static int halt_main(DBusConnection *bus) {
4813 if (geteuid() != 0) {
4814 log_error("Must to be root.");
4820 char date[FORMAT_TIMESTAMP_MAX];
4822 m = strv_join(arg_wall, " ");
4823 r = send_shutdownd(arg_when,
4824 arg_action == ACTION_HALT ? 'H' :
4825 arg_action == ACTION_POWEROFF ? 'P' :
4832 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
4834 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
4835 format_timestamp(date, sizeof(date), arg_when));
4840 if (!arg_dry && !arg_immediate)
4841 return start_with_fallback(bus);
4844 if (sd_booted() > 0)
4845 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
4846 else if ((r = utmp_put_shutdown(0)) < 0)
4847 log_warning("Failed to write utmp record: %s", strerror(-r));
4856 /* Make sure C-A-D is handled by the kernel from this
4858 reboot(RB_ENABLE_CAD);
4860 switch (arg_action) {
4863 log_info("Halting.");
4864 reboot(RB_HALT_SYSTEM);
4867 case ACTION_POWEROFF:
4868 log_info("Powering off.");
4869 reboot(RB_POWER_OFF);
4873 log_info("Rebooting.");
4874 reboot(RB_AUTOBOOT);
4878 assert_not_reached("Unknown halt action.");
4881 /* We should never reach this. */
4885 static int runlevel_main(void) {
4886 int r, runlevel, previous;
4888 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
4889 printf("unknown\n");
4894 previous <= 0 ? 'N' : previous,
4895 runlevel <= 0 ? 'N' : runlevel);
4900 int main(int argc, char*argv[]) {
4902 DBusConnection *bus = NULL;
4905 dbus_error_init(&error);
4907 log_parse_environment();
4910 if ((r = parse_argv(argc, argv)) < 0)
4917 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
4918 * let's shortcut this */
4919 if (arg_action == ACTION_RUNLEVEL) {
4920 retval = runlevel_main() < 0;
4924 bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
4926 switch (arg_action) {
4928 case ACTION_SYSTEMCTL: {
4929 retval = systemctl_main(bus, argc, argv, &error) < 0;
4934 case ACTION_POWEROFF:
4936 retval = halt_main(bus) < 0;
4939 case ACTION_RUNLEVEL2:
4940 case ACTION_RUNLEVEL3:
4941 case ACTION_RUNLEVEL4:
4942 case ACTION_RUNLEVEL5:
4944 case ACTION_EMERGENCY:
4945 case ACTION_DEFAULT:
4946 retval = start_with_fallback(bus) < 0;
4951 retval = reload_with_fallback(bus) < 0;
4954 case ACTION_CANCEL_SHUTDOWN:
4955 retval = send_shutdownd(0, 0, false, NULL) < 0;
4958 case ACTION_INVALID:
4959 case ACTION_RUNLEVEL:
4961 assert_not_reached("Unknown action");
4967 dbus_connection_close(bus);
4968 dbus_connection_unref(bus);
4971 dbus_error_free(&error);
4975 strv_free(arg_property);