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.DBus.Properties", "PropertiesChanged")) {
2395 const char *path, *interface, *property = "Id";
2396 DBusMessageIter iter, sub;
2398 path = dbus_message_get_path(message);
2400 if (!dbus_message_get_args(message, &error,
2401 DBUS_TYPE_STRING, &interface,
2402 DBUS_TYPE_INVALID)) {
2403 log_error("Failed to parse message: %s", error.message);
2407 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2408 !streq(interface, "org.freedesktop.systemd1.Unit"))
2411 if (!(m = dbus_message_new_method_call(
2412 "org.freedesktop.systemd1",
2414 "org.freedesktop.DBus.Properties",
2416 log_error("Could not allocate message.");
2420 if (!dbus_message_append_args(m,
2421 DBUS_TYPE_STRING, &interface,
2422 DBUS_TYPE_STRING, &property,
2423 DBUS_TYPE_INVALID)) {
2424 log_error("Could not append arguments to message.");
2428 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2429 log_error("Failed to issue method call: %s", error.message);
2433 if (!dbus_message_iter_init(reply, &iter) ||
2434 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2435 log_error("Failed to parse reply.");
2439 dbus_message_iter_recurse(&iter, &sub);
2441 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2444 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2445 log_error("Failed to parse reply.");
2449 dbus_message_iter_get_basic(&sub, &id);
2450 printf("Unit %s changed.\n", id);
2454 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2455 log_error("Failed to parse reply.");
2459 dbus_message_iter_get_basic(&sub, &id);
2460 printf("Job %u changed.\n", id);
2466 dbus_message_unref(m);
2469 dbus_message_unref(reply);
2471 dbus_error_free(&error);
2472 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2476 dbus_message_unref(m);
2479 dbus_message_unref(reply);
2481 dbus_error_free(&error);
2482 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2485 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2486 DBusMessage *m = NULL, *reply = NULL;
2490 dbus_error_init(&error);
2493 dbus_bus_add_match(bus,
2495 "sender='org.freedesktop.systemd1',"
2496 "interface='org.freedesktop.systemd1.Manager',"
2497 "path='/org/freedesktop/systemd1'",
2500 if (dbus_error_is_set(&error)) {
2501 log_error("Failed to add match: %s", error.message);
2506 dbus_bus_add_match(bus,
2508 "sender='org.freedesktop.systemd1',"
2509 "interface='org.freedesktop.DBus.Properties',"
2510 "member='PropertiesChanged'",
2513 if (dbus_error_is_set(&error)) {
2514 log_error("Failed to add match: %s", error.message);
2520 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2521 log_error("Failed to add filter.");
2526 if (!(m = dbus_message_new_method_call(
2527 "org.freedesktop.systemd1",
2528 "/org/freedesktop/systemd1",
2529 "org.freedesktop.systemd1.Manager",
2531 log_error("Could not allocate message.");
2536 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2537 log_error("Failed to issue method call: %s", error.message);
2542 while (dbus_connection_read_write_dispatch(bus, -1))
2549 /* This is slightly dirty, since we don't undo the filter or the matches. */
2552 dbus_message_unref(m);
2555 dbus_message_unref(reply);
2557 dbus_error_free(&error);
2562 static int dump(DBusConnection *bus, char **args, unsigned n) {
2563 DBusMessage *m = NULL, *reply = NULL;
2568 dbus_error_init(&error);
2570 if (!(m = dbus_message_new_method_call(
2571 "org.freedesktop.systemd1",
2572 "/org/freedesktop/systemd1",
2573 "org.freedesktop.systemd1.Manager",
2575 log_error("Could not allocate message.");
2579 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2580 log_error("Failed to issue method call: %s", error.message);
2585 if (!dbus_message_get_args(reply, &error,
2586 DBUS_TYPE_STRING, &text,
2587 DBUS_TYPE_INVALID)) {
2588 log_error("Failed to parse reply: %s", error.message);
2593 fputs(text, stdout);
2599 dbus_message_unref(m);
2602 dbus_message_unref(reply);
2604 dbus_error_free(&error);
2609 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2610 DBusMessage *m = NULL, *reply = NULL;
2613 const char *name = "", *path, *id;
2614 dbus_bool_t cleanup = FALSE;
2615 DBusMessageIter iter, sub;
2617 *interface = "org.freedesktop.systemd1.Unit",
2620 dbus_error_init(&error);
2622 if (!(m = dbus_message_new_method_call(
2623 "org.freedesktop.systemd1",
2624 "/org/freedesktop/systemd1",
2625 "org.freedesktop.systemd1.Manager",
2626 "CreateSnapshot"))) {
2627 log_error("Could not allocate message.");
2634 if (!dbus_message_append_args(m,
2635 DBUS_TYPE_STRING, &name,
2636 DBUS_TYPE_BOOLEAN, &cleanup,
2637 DBUS_TYPE_INVALID)) {
2638 log_error("Could not append arguments to message.");
2643 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2644 log_error("Failed to issue method call: %s", error.message);
2649 if (!dbus_message_get_args(reply, &error,
2650 DBUS_TYPE_OBJECT_PATH, &path,
2651 DBUS_TYPE_INVALID)) {
2652 log_error("Failed to parse reply: %s", error.message);
2657 dbus_message_unref(m);
2658 if (!(m = dbus_message_new_method_call(
2659 "org.freedesktop.systemd1",
2661 "org.freedesktop.DBus.Properties",
2663 log_error("Could not allocate message.");
2667 if (!dbus_message_append_args(m,
2668 DBUS_TYPE_STRING, &interface,
2669 DBUS_TYPE_STRING, &property,
2670 DBUS_TYPE_INVALID)) {
2671 log_error("Could not append arguments to message.");
2676 dbus_message_unref(reply);
2677 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2678 log_error("Failed to issue method call: %s", error.message);
2683 if (!dbus_message_iter_init(reply, &iter) ||
2684 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2685 log_error("Failed to parse reply.");
2690 dbus_message_iter_recurse(&iter, &sub);
2692 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2693 log_error("Failed to parse reply.");
2698 dbus_message_iter_get_basic(&sub, &id);
2706 dbus_message_unref(m);
2709 dbus_message_unref(reply);
2711 dbus_error_free(&error);
2716 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2717 DBusMessage *m = NULL, *reply = NULL;
2725 dbus_error_init(&error);
2727 for (i = 1; i < n; i++) {
2728 const char *path = NULL;
2730 if (!(m = dbus_message_new_method_call(
2731 "org.freedesktop.systemd1",
2732 "/org/freedesktop/systemd1",
2733 "org.freedesktop.systemd1.Manager",
2735 log_error("Could not allocate message.");
2740 if (!dbus_message_append_args(m,
2741 DBUS_TYPE_STRING, &args[i],
2742 DBUS_TYPE_INVALID)) {
2743 log_error("Could not append arguments to message.");
2748 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2749 log_error("Failed to issue method call: %s", error.message);
2754 if (!dbus_message_get_args(reply, &error,
2755 DBUS_TYPE_OBJECT_PATH, &path,
2756 DBUS_TYPE_INVALID)) {
2757 log_error("Failed to parse reply: %s", error.message);
2762 dbus_message_unref(m);
2763 if (!(m = dbus_message_new_method_call(
2764 "org.freedesktop.systemd1",
2766 "org.freedesktop.systemd1.Snapshot",
2768 log_error("Could not allocate message.");
2773 dbus_message_unref(reply);
2774 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2775 log_error("Failed to issue method call: %s", error.message);
2780 dbus_message_unref(m);
2781 dbus_message_unref(reply);
2789 dbus_message_unref(m);
2792 dbus_message_unref(reply);
2794 dbus_error_free(&error);
2799 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2800 DBusMessage *m = NULL, *reply = NULL;
2805 dbus_error_init(&error);
2807 if (arg_action == ACTION_RELOAD)
2809 else if (arg_action == ACTION_REEXEC)
2810 method = "Reexecute";
2812 assert(arg_action == ACTION_SYSTEMCTL);
2815 streq(args[0], "clear-jobs") ||
2816 streq(args[0], "cancel") ? "ClearJobs" :
2817 streq(args[0], "daemon-reexec") ? "Reexecute" :
2818 streq(args[0], "reset-maintenance") ? "ResetMaintenance" :
2819 streq(args[0], "daemon-exit") ? "Exit" :
2823 if (!(m = dbus_message_new_method_call(
2824 "org.freedesktop.systemd1",
2825 "/org/freedesktop/systemd1",
2826 "org.freedesktop.systemd1.Manager",
2828 log_error("Could not allocate message.");
2832 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2834 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
2835 /* There's always a fallback possible for
2836 * legacy actions. */
2841 log_error("Failed to issue method call: %s", error.message);
2850 dbus_message_unref(m);
2853 dbus_message_unref(reply);
2855 dbus_error_free(&error);
2860 static int reset_maintenance(DBusConnection *bus, char **args, unsigned n) {
2861 DBusMessage *m = NULL, *reply = NULL;
2867 dbus_error_init(&error);
2870 return daemon_reload(bus, args, n);
2872 for (i = 1; i < n; i++) {
2874 if (!(m = dbus_message_new_method_call(
2875 "org.freedesktop.systemd1",
2876 "/org/freedesktop/systemd1",
2877 "org.freedesktop.systemd1.Manager",
2878 "ResetMaintenanceUnit"))) {
2879 log_error("Could not allocate message.");
2884 if (!dbus_message_append_args(m,
2885 DBUS_TYPE_STRING, args + i,
2886 DBUS_TYPE_INVALID)) {
2887 log_error("Could not append arguments to message.");
2892 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2893 log_error("Failed to issue method call: %s", error.message);
2898 dbus_message_unref(m);
2899 dbus_message_unref(reply);
2907 dbus_message_unref(m);
2910 dbus_message_unref(reply);
2912 dbus_error_free(&error);
2917 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
2918 DBusMessage *m = NULL, *reply = NULL;
2920 DBusMessageIter iter, sub, sub2;
2923 *interface = "org.freedesktop.systemd1.Manager",
2924 *property = "Environment";
2926 dbus_error_init(&error);
2928 if (!(m = dbus_message_new_method_call(
2929 "org.freedesktop.systemd1",
2930 "/org/freedesktop/systemd1",
2931 "org.freedesktop.DBus.Properties",
2933 log_error("Could not allocate message.");
2937 if (!dbus_message_append_args(m,
2938 DBUS_TYPE_STRING, &interface,
2939 DBUS_TYPE_STRING, &property,
2940 DBUS_TYPE_INVALID)) {
2941 log_error("Could not append arguments to message.");
2946 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2947 log_error("Failed to issue method call: %s", error.message);
2952 if (!dbus_message_iter_init(reply, &iter) ||
2953 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2954 log_error("Failed to parse reply.");
2959 dbus_message_iter_recurse(&iter, &sub);
2961 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
2962 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
2963 log_error("Failed to parse reply.");
2968 dbus_message_iter_recurse(&sub, &sub2);
2970 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
2973 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
2974 log_error("Failed to parse reply.");
2979 dbus_message_iter_get_basic(&sub2, &text);
2980 printf("%s\n", text);
2982 dbus_message_iter_next(&sub2);
2989 dbus_message_unref(m);
2992 dbus_message_unref(reply);
2994 dbus_error_free(&error);
2999 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3000 DBusMessage *m = NULL, *reply = NULL;
3004 DBusMessageIter iter, sub;
3007 dbus_error_init(&error);
3009 method = streq(args[0], "set-environment")
3011 : "UnsetEnvironment";
3013 if (!(m = dbus_message_new_method_call(
3014 "org.freedesktop.systemd1",
3015 "/org/freedesktop/systemd1",
3016 "org.freedesktop.systemd1.Manager",
3019 log_error("Could not allocate message.");
3023 dbus_message_iter_init_append(m, &iter);
3025 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3026 log_error("Could not append arguments to message.");
3031 for (i = 1; i < n; i++)
3032 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3033 log_error("Could not append arguments to message.");
3038 if (!dbus_message_iter_close_container(&iter, &sub)) {
3039 log_error("Could not append arguments to message.");
3044 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3045 log_error("Failed to issue method call: %s", error.message);
3054 dbus_message_unref(m);
3057 dbus_message_unref(reply);
3059 dbus_error_free(&error);
3072 static Hashmap *will_install = NULL, *have_installed = NULL;
3073 static Set *remove_symlinks_to = NULL;
3075 static void install_info_free(InstallInfo *i) {
3080 strv_free(i->aliases);
3081 strv_free(i->wanted_by);
3085 static void install_info_hashmap_free(Hashmap *m) {
3088 while ((i = hashmap_steal_first(m)))
3089 install_info_free(i);
3094 static bool unit_name_valid(const char *name) {
3096 /* This is a minimal version of unit_name_valid() from
3102 if (ignore_file(name))
3108 static int install_info_add(const char *name) {
3112 assert(will_install);
3114 if (!unit_name_valid(name))
3117 if (hashmap_get(have_installed, name) ||
3118 hashmap_get(will_install, name))
3121 if (!(i = new0(InstallInfo, 1))) {
3126 if (!(i->name = strdup(name))) {
3131 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3138 install_info_free(i);
3143 static int config_parse_also(
3144 const char *filename,
3146 const char *section,
3160 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3164 if (!(n = strndup(w, l)))
3167 r = install_info_add(n);
3177 static int mark_symlink_for_removal(const char *p) {
3182 assert(path_is_absolute(p));
3184 if (!remove_symlinks_to)
3187 if (!(n = strdup(p)))
3190 path_kill_slashes(n);
3192 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3194 return r == -EEXIST ? 0 : r;
3200 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3209 if (!(d = fdopendir(fd))) {
3210 close_nointr_nofail(fd);
3216 while ((de = readdir(d))) {
3217 bool is_dir = false, is_link = false;
3219 if (ignore_file(de->d_name))
3222 if (de->d_type == DT_LNK)
3224 else if (de->d_type == DT_DIR)
3226 else if (de->d_type == DT_UNKNOWN) {
3229 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3230 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3237 is_link = S_ISLNK(st.st_mode);
3238 is_dir = S_ISDIR(st.st_mode);
3246 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3247 log_error("Failed to open %s/%s: %m", root, de->d_name);
3254 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3255 log_error("Failed to allocate directory string.");
3256 close_nointr_nofail(nfd);
3261 /* This will close nfd, regardless whether it succeeds or not */
3262 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3268 } else if (is_link) {
3272 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3273 log_error("Failed to allocate symlink string.");
3278 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3279 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3287 if ((c = canonicalize_file_name(dest))) {
3288 /* This might fail if the destination
3289 * is already removed */
3295 path_kill_slashes(dest);
3296 if (set_get(remove_symlinks_to, dest)) {
3299 log_info("rm '%s'", p);
3301 if (unlink(p) < 0) {
3302 log_error("Cannot unlink symlink %s: %m", p);
3307 rmdir_parents(p, config_path);
3308 path_kill_slashes(p);
3310 if (!set_get(remove_symlinks_to, p)) {
3312 if ((r = mark_symlink_for_removal(p)) < 0) {
3331 static int remove_marked_symlinks(const char *config_path) {
3335 assert(config_path);
3337 if (set_size(remove_symlinks_to) <= 0)
3340 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3347 if ((cfd = dup(fd)) < 0) {
3352 /* This takes possession of cfd and closes it */
3353 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3359 close_nointr_nofail(fd);
3364 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3371 if (streq(verb, "enable")) {
3374 mkdir_parents(new_path, 0755);
3376 if (symlink(old_path, new_path) >= 0) {
3379 log_info("ln -s '%s' '%s'", old_path, new_path);
3384 if (errno != EEXIST) {
3385 log_error("Cannot link %s to %s: %m", old_path, new_path);
3389 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3391 if (errno == EINVAL) {
3392 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3396 log_error("readlink() failed: %s", strerror(-r));
3400 if (streq(dest, old_path)) {
3406 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3415 log_info("ln -s '%s' '%s'", old_path, new_path);
3417 if (symlink(old_path, new_path) >= 0)
3420 log_error("Cannot link %s to %s: %m", old_path, new_path);
3423 } else if (streq(verb, "disable")) {
3426 if ((r = mark_symlink_for_removal(old_path)) < 0)
3429 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3430 if (errno == ENOENT)
3433 if (errno == EINVAL) {
3434 log_warning("File %s not a symlink, ignoring.", old_path);
3438 log_error("readlink() failed: %s", strerror(-r));
3442 if (!streq(dest, old_path)) {
3443 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3450 if ((r = mark_symlink_for_removal(new_path)) < 0)
3454 log_info("rm '%s'", new_path);
3456 if (unlink(new_path) >= 0)
3459 log_error("Cannot unlink %s: %m", new_path);
3462 } else if (streq(verb, "is-enabled")) {
3465 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3467 if (errno == ENOENT || errno == EINVAL)
3470 log_error("readlink() failed: %s", strerror(-r));
3474 if (streq(dest, old_path)) {
3482 assert_not_reached("Unknown action.");
3485 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3487 char *alias_path = NULL;
3492 assert(config_path);
3494 STRV_FOREACH(s, i->aliases) {
3496 if (!unit_name_valid(*s)) {
3497 log_error("Invalid name %s.", *s);
3503 if (!(alias_path = path_make_absolute(*s, config_path))) {
3504 log_error("Out of memory");
3509 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3512 if (streq(verb, "disable"))
3513 rmdir_parents(alias_path, config_path);
3524 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3526 char *alias_path = NULL;
3531 assert(config_path);
3533 STRV_FOREACH(s, i->wanted_by) {
3534 if (!unit_name_valid(*s)) {
3535 log_error("Invalid name %s.", *s);
3543 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3544 log_error("Out of memory");
3549 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3552 if (streq(verb, "disable"))
3553 rmdir_parents(alias_path, config_path);
3564 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3566 const ConfigItem items[] = {
3567 { "Alias", config_parse_strv, &i->aliases, "Install" },
3568 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3569 { "Also", config_parse_also, NULL, "Install" },
3571 { NULL, NULL, NULL, NULL }
3575 char *filename = NULL;
3582 STRV_FOREACH(p, paths->unit_path) {
3585 if (!(filename = path_make_absolute(i->name, *p))) {
3586 log_error("Out of memory");
3590 /* Ensure that we don't follow symlinks */
3591 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3592 if ((f = fdopen(fd, "re")))
3595 if (errno == ELOOP) {
3596 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3601 if (errno != ENOENT) {
3602 log_error("Failed to open %s: %m", filename);
3612 log_error("Couldn't find %s.", i->name);
3618 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3625 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3628 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3631 if ((r = mark_symlink_for_removal(filename)) < 0)
3634 if ((r = remove_marked_symlinks(config_path)) < 0)
3640 static char *get_config_path(void) {
3642 if (arg_session && arg_global)
3643 return strdup(SESSION_CONFIG_UNIT_PATH);
3648 if (session_config_home(&p) < 0)
3654 return strdup(SYSTEM_CONFIG_UNIT_PATH);
3657 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3661 char *config_path = NULL;
3664 const char *verb = args[0];
3666 dbus_error_init(&error);
3669 if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3670 log_error("Failed to determine lookup paths: %s", strerror(-r));
3674 if (!(config_path = get_config_path())) {
3675 log_error("Failed to determine config path");
3680 will_install = hashmap_new(string_hash_func, string_compare_func);
3681 have_installed = hashmap_new(string_hash_func, string_compare_func);
3683 if (!will_install || !have_installed) {
3684 log_error("Failed to allocate unit sets.");
3689 if (!arg_defaults && streq(verb, "disable"))
3690 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3691 log_error("Failed to allocate symlink sets.");
3696 for (j = 1; j < n; j++)
3697 if ((r = install_info_add(args[j])) < 0)
3700 while ((i = hashmap_first(will_install))) {
3703 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3705 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3713 /* In test mode and found something */
3719 if (streq(verb, "is-enabled"))
3720 r = r > 0 ? 0 : -ENOENT;
3722 /* Don't try to reload anything if the user asked us to not do this */
3724 /* Don't try to reload anything when updating a unit globally */
3726 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3727 (arg_session || sd_booted() > 0) &&
3728 /* Don't try to reload anything if we are running in a chroot environment */
3729 (arg_session || running_in_chroot() <= 0) ) {
3732 if ((q = daemon_reload(bus, args, n)) < 0)
3737 install_info_hashmap_free(will_install);
3738 install_info_hashmap_free(have_installed);
3740 set_free_free(remove_symlinks_to);
3742 lookup_paths_free(&paths);
3749 static int systemctl_help(void) {
3751 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3752 "Send control commands to or query the systemd manager.\n\n"
3753 " -h --help Show this help\n"
3754 " -t --type=TYPE List only units of a particular type\n"
3755 " -p --property=NAME Show only properties by this name\n"
3756 " -a --all Show all units/properties, including dead/empty ones\n"
3757 " --full Don't ellipsize unit names on output\n"
3758 " --fail When queueing a new job, fail if conflicting jobs are\n"
3760 " -q --quiet Suppress output\n"
3761 " --no-block Do not wait until operation finished\n"
3762 " --system Connect to system bus\n"
3763 " --session Connect to session bus\n"
3764 " --order When generating graph for dot, show only order\n"
3765 " --require When generating graph for dot, show only requirement\n"
3766 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3767 " --global Enable/disable unit files globally\n"
3768 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3770 " --force When enabling unit files, override existing symlinks\n"
3771 " --defaults When disabling unit files, remove default symlinks only\n\n"
3773 " list-units List units\n"
3774 " start [NAME...] Start (activate) one or more units\n"
3775 " stop [NAME...] Stop (deactivate) one or more units\n"
3776 " reload [NAME...] Reload one or more units\n"
3777 " restart [NAME...] Start or restart one or more units\n"
3778 " try-restart [NAME...] Restart one or more units if active\n"
3779 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3780 " otherwise start or restart\n"
3781 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3782 " otherwise restart if active\n"
3783 " isolate [NAME] Start one unit and stop all others\n"
3784 " is-active [NAME...] Check whether units are active\n"
3785 " status [NAME...|PID...] Show runtime status of one or more units\n"
3786 " show [NAME...|JOB...] Show properties of one or more\n"
3787 " units/jobs or the manager\n"
3788 " reset-maintenance [NAME...] Reset maintenance state for all, one,\n"
3790 " enable [NAME...] Enable one or more unit files\n"
3791 " disable [NAME...] Disable one or more unit files\n"
3792 " is-enabled [NAME...] Check whether unit files are enabled\n"
3793 " load [NAME...] Load one or more units\n"
3794 " list-jobs List jobs\n"
3795 " cancel [JOB...] Cancel all, one, or more jobs\n"
3796 " monitor Monitor unit/job changes\n"
3797 " dump Dump server status\n"
3798 " dot Dump dependency graph for dot(1)\n"
3799 " snapshot [NAME] Create a snapshot\n"
3800 " delete [NAME...] Remove one or more snapshots\n"
3801 " daemon-reload Reload systemd manager configuration\n"
3802 " daemon-reexec Reexecute systemd manager\n"
3803 " daemon-exit Ask the systemd manager to quit\n"
3804 " show-environment Dump environment\n"
3805 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3806 " unset-environment [NAME...] Unset one or more environment variables\n"
3807 " halt Shut down and halt the system\n"
3808 " poweroff Shut down and power-off the system\n"
3809 " reboot Shut down and reboot the system\n"
3810 " rescue Enter system rescue mode\n"
3811 " emergency Enter system emergency mode\n"
3812 " default Enter system default mode\n",
3813 program_invocation_short_name);
3818 static int halt_help(void) {
3820 printf("%s [OPTIONS...]\n\n"
3821 "%s the system.\n\n"
3822 " --help Show this help\n"
3823 " --halt Halt the machine\n"
3824 " -p --poweroff Switch off the machine\n"
3825 " --reboot Reboot the machine\n"
3826 " -f --force Force immediate halt/power-off/reboot\n"
3827 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3828 " -d --no-wtmp Don't write wtmp record\n"
3829 " -n --no-sync Don't sync before halt/power-off/reboot\n"
3830 " --no-wall Don't send wall message before halt/power-off/reboot\n",
3831 program_invocation_short_name,
3832 arg_action == ACTION_REBOOT ? "Reboot" :
3833 arg_action == ACTION_POWEROFF ? "Power off" :
3839 static int shutdown_help(void) {
3841 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3842 "Shut down the system.\n\n"
3843 " --help Show this help\n"
3844 " -H --halt Halt the machine\n"
3845 " -P --poweroff Power-off the machine\n"
3846 " -r --reboot Reboot the machine\n"
3847 " -h Equivalent to --poweroff, overriden by --halt\n"
3848 " -k Don't halt/power-off/reboot, just send warnings\n"
3849 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3850 " -c Cancel a pending shutdown\n",
3851 program_invocation_short_name);
3856 static int telinit_help(void) {
3858 printf("%s [OPTIONS...] {COMMAND}\n\n"
3859 "Send control commands to the init daemon.\n\n"
3860 " --help Show this help\n"
3861 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
3863 " 0 Power-off the machine\n"
3864 " 6 Reboot the machine\n"
3865 " 2, 3, 4, 5 Start runlevelX.target unit\n"
3866 " 1, s, S Enter rescue mode\n"
3867 " q, Q Reload init daemon configuration\n"
3868 " u, U Reexecute init daemon\n",
3869 program_invocation_short_name);
3874 static int runlevel_help(void) {
3876 printf("%s [OPTIONS...]\n\n"
3877 "Prints the previous and current runlevel of the init system.\n\n"
3878 " --help Show this help\n",
3879 program_invocation_short_name);
3884 static int systemctl_parse_argv(int argc, char *argv[]) {
3901 static const struct option options[] = {
3902 { "help", no_argument, NULL, 'h' },
3903 { "type", required_argument, NULL, 't' },
3904 { "property", required_argument, NULL, 'p' },
3905 { "all", no_argument, NULL, 'a' },
3906 { "full", no_argument, NULL, ARG_FULL },
3907 { "fail", no_argument, NULL, ARG_FAIL },
3908 { "session", no_argument, NULL, ARG_SESSION },
3909 { "system", no_argument, NULL, ARG_SYSTEM },
3910 { "global", no_argument, NULL, ARG_GLOBAL },
3911 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
3912 { "no-wall", no_argument, NULL, ARG_NO_WALL },
3913 { "quiet", no_argument, NULL, 'q' },
3914 { "order", no_argument, NULL, ARG_ORDER },
3915 { "require", no_argument, NULL, ARG_REQUIRE },
3916 { "force", no_argument, NULL, ARG_FORCE },
3917 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
3918 { "defaults", no_argument, NULL, ARG_DEFAULTS },
3919 { NULL, 0, NULL, 0 }
3927 while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
3942 if (!(l = strv_append(arg_property, optarg)))
3945 strv_free(arg_property);
3948 /* If the user asked for a particular
3949 * property, show it to him, even if it is
3968 arg_session = false;
3972 arg_no_block = true;
3980 arg_dot = DOT_ORDER;
3984 arg_dot = DOT_REQUIRE;
4000 arg_no_reload = true;
4009 arg_defaults = true;
4016 log_error("Unknown option code %c", c);
4024 static int halt_parse_argv(int argc, char *argv[]) {
4033 static const struct option options[] = {
4034 { "help", no_argument, NULL, ARG_HELP },
4035 { "halt", no_argument, NULL, ARG_HALT },
4036 { "poweroff", no_argument, NULL, 'p' },
4037 { "reboot", no_argument, NULL, ARG_REBOOT },
4038 { "force", no_argument, NULL, 'f' },
4039 { "wtmp-only", no_argument, NULL, 'w' },
4040 { "no-wtmp", no_argument, NULL, 'd' },
4041 { "no-sync", no_argument, NULL, 'n' },
4042 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4043 { NULL, 0, NULL, 0 }
4051 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4052 if (runlevel == '0' || runlevel == '6')
4053 arg_immediate = true;
4055 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4063 arg_action = ACTION_HALT;
4067 if (arg_action != ACTION_REBOOT)
4068 arg_action = ACTION_POWEROFF;
4072 arg_action = ACTION_REBOOT;
4076 arg_immediate = true;
4097 /* Compatibility nops */
4104 log_error("Unknown option code %c", c);
4109 if (optind < argc) {
4110 log_error("Too many arguments.");
4117 static int parse_time_spec(const char *t, usec_t *_u) {
4121 if (streq(t, "now"))
4123 else if (t[0] == '+') {
4126 if (safe_atou64(t + 1, &u) < 0)
4129 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4138 hour = strtol(t, &e, 10);
4139 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4142 minute = strtol(e+1, &e, 10);
4143 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4146 n = now(CLOCK_REALTIME);
4147 s = (time_t) (n / USEC_PER_SEC);
4150 assert_se(localtime_r(&s, &tm));
4152 tm.tm_hour = (int) hour;
4153 tm.tm_min = (int) minute;
4156 assert_se(s = mktime(&tm));
4158 *_u = (usec_t) s * USEC_PER_SEC;
4161 *_u += USEC_PER_DAY;
4167 static int shutdown_parse_argv(int argc, char *argv[]) {
4174 static const struct option options[] = {
4175 { "help", no_argument, NULL, ARG_HELP },
4176 { "halt", no_argument, NULL, 'H' },
4177 { "poweroff", no_argument, NULL, 'P' },
4178 { "reboot", no_argument, NULL, 'r' },
4179 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4180 { NULL, 0, NULL, 0 }
4188 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4196 arg_action = ACTION_HALT;
4200 arg_action = ACTION_POWEROFF;
4204 arg_action = ACTION_REBOOT;
4208 if (arg_action != ACTION_HALT)
4209 arg_action = ACTION_POWEROFF;
4222 /* Compatibility nops */
4226 arg_action = ACTION_CANCEL_SHUTDOWN;
4233 log_error("Unknown option code %c", c);
4238 if (argc > optind) {
4239 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4240 log_error("Failed to parse time specification: %s", argv[optind]);
4244 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4246 /* We skip the time argument */
4247 if (argc > optind + 1)
4248 arg_wall = argv + optind + 1;
4255 static int telinit_parse_argv(int argc, char *argv[]) {
4262 static const struct option options[] = {
4263 { "help", no_argument, NULL, ARG_HELP },
4264 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4265 { NULL, 0, NULL, 0 }
4268 static const struct {
4272 { '0', ACTION_POWEROFF },
4273 { '6', ACTION_REBOOT },
4274 { '1', ACTION_RESCUE },
4275 { '2', ACTION_RUNLEVEL2 },
4276 { '3', ACTION_RUNLEVEL3 },
4277 { '4', ACTION_RUNLEVEL4 },
4278 { '5', ACTION_RUNLEVEL5 },
4279 { 's', ACTION_RESCUE },
4280 { 'S', ACTION_RESCUE },
4281 { 'q', ACTION_RELOAD },
4282 { 'Q', ACTION_RELOAD },
4283 { 'u', ACTION_REEXEC },
4284 { 'U', ACTION_REEXEC }
4293 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4308 log_error("Unknown option code %c", c);
4313 if (optind >= argc) {
4318 if (optind + 1 < argc) {
4319 log_error("Too many arguments.");
4323 if (strlen(argv[optind]) != 1) {
4324 log_error("Expected single character argument.");
4328 for (i = 0; i < ELEMENTSOF(table); i++)
4329 if (table[i].from == argv[optind][0])
4332 if (i >= ELEMENTSOF(table)) {
4333 log_error("Unknown command %s.", argv[optind]);
4337 arg_action = table[i].to;
4344 static int runlevel_parse_argv(int argc, char *argv[]) {
4350 static const struct option options[] = {
4351 { "help", no_argument, NULL, ARG_HELP },
4352 { NULL, 0, NULL, 0 }
4360 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4371 log_error("Unknown option code %c", c);
4376 if (optind < argc) {
4377 log_error("Too many arguments.");
4384 static int parse_argv(int argc, char *argv[]) {
4388 if (program_invocation_short_name) {
4390 if (strstr(program_invocation_short_name, "halt")) {
4391 arg_action = ACTION_HALT;
4392 return halt_parse_argv(argc, argv);
4393 } else if (strstr(program_invocation_short_name, "poweroff")) {
4394 arg_action = ACTION_POWEROFF;
4395 return halt_parse_argv(argc, argv);
4396 } else if (strstr(program_invocation_short_name, "reboot")) {
4397 arg_action = ACTION_REBOOT;
4398 return halt_parse_argv(argc, argv);
4399 } else if (strstr(program_invocation_short_name, "shutdown")) {
4400 arg_action = ACTION_POWEROFF;
4401 return shutdown_parse_argv(argc, argv);
4402 } else if (strstr(program_invocation_short_name, "init")) {
4404 if (sd_booted() > 0) {
4405 arg_action = ACTION_INVALID;
4406 return telinit_parse_argv(argc, argv);
4408 /* Hmm, so some other init system is
4409 * running, we need to forward this
4410 * request to it. For now we simply
4411 * guess that it is Upstart. */
4413 execv("/lib/upstart/telinit", argv);
4415 log_error("Couldn't find an alternative telinit implementation to spawn.");
4419 } else if (strstr(program_invocation_short_name, "runlevel")) {
4420 arg_action = ACTION_RUNLEVEL;
4421 return runlevel_parse_argv(argc, argv);
4425 arg_action = ACTION_SYSTEMCTL;
4426 return systemctl_parse_argv(argc, argv);
4429 static int action_to_runlevel(void) {
4431 static const char table[_ACTION_MAX] = {
4432 [ACTION_HALT] = '0',
4433 [ACTION_POWEROFF] = '0',
4434 [ACTION_REBOOT] = '6',
4435 [ACTION_RUNLEVEL2] = '2',
4436 [ACTION_RUNLEVEL3] = '3',
4437 [ACTION_RUNLEVEL4] = '4',
4438 [ACTION_RUNLEVEL5] = '5',
4439 [ACTION_RESCUE] = '1'
4442 assert(arg_action < _ACTION_MAX);
4444 return table[arg_action];
4447 static int talk_upstart(void) {
4448 DBusMessage *m = NULL, *reply = NULL;
4450 int previous, rl, r;
4452 env1_buf[] = "RUNLEVEL=X",
4453 env2_buf[] = "PREVLEVEL=X";
4454 char *env1 = env1_buf, *env2 = env2_buf;
4455 const char *emit = "runlevel";
4456 dbus_bool_t b_false = FALSE;
4457 DBusMessageIter iter, sub;
4458 DBusConnection *bus;
4460 dbus_error_init(&error);
4462 if (!(rl = action_to_runlevel()))
4465 if (utmp_get_runlevel(&previous, NULL) < 0)
4468 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4469 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4474 log_error("Failed to connect to Upstart bus: %s", error.message);
4479 if ((r = bus_check_peercred(bus)) < 0) {
4480 log_error("Failed to verify owner of bus.");
4484 if (!(m = dbus_message_new_method_call(
4485 "com.ubuntu.Upstart",
4486 "/com/ubuntu/Upstart",
4487 "com.ubuntu.Upstart0_6",
4490 log_error("Could not allocate message.");
4495 dbus_message_iter_init_append(m, &iter);
4497 env1_buf[sizeof(env1_buf)-2] = rl;
4498 env2_buf[sizeof(env2_buf)-2] = previous;
4500 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4501 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4502 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4503 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4504 !dbus_message_iter_close_container(&iter, &sub) ||
4505 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4506 log_error("Could not append arguments to message.");
4511 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4513 if (error_is_no_service(&error)) {
4518 log_error("Failed to issue method call: %s", error.message);
4527 dbus_message_unref(m);
4530 dbus_message_unref(reply);
4533 dbus_connection_close(bus);
4534 dbus_connection_unref(bus);
4537 dbus_error_free(&error);
4542 static int talk_initctl(void) {
4543 struct init_request request;
4547 if (!(rl = action_to_runlevel()))
4551 request.magic = INIT_MAGIC;
4552 request.sleeptime = 0;
4553 request.cmd = INIT_CMD_RUNLVL;
4554 request.runlevel = rl;
4556 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4558 if (errno == ENOENT)
4561 log_error("Failed to open "INIT_FIFO": %m");
4566 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4567 close_nointr_nofail(fd);
4570 log_error("Failed to write to "INIT_FIFO": %m");
4571 return errno ? -errno : -EIO;
4577 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4579 static const struct {
4587 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4589 { "list-units", LESS, 1, list_units },
4590 { "list-jobs", EQUAL, 1, list_jobs },
4591 { "clear-jobs", EQUAL, 1, daemon_reload },
4592 { "load", MORE, 2, load_unit },
4593 { "cancel", MORE, 2, cancel_job },
4594 { "start", MORE, 2, start_unit },
4595 { "stop", MORE, 2, start_unit },
4596 { "reload", MORE, 2, start_unit },
4597 { "restart", MORE, 2, start_unit },
4598 { "try-restart", MORE, 2, start_unit },
4599 { "reload-or-restart", MORE, 2, start_unit },
4600 { "reload-or-try-restart", MORE, 2, start_unit },
4601 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4602 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4603 { "isolate", EQUAL, 2, start_unit },
4604 { "is-active", MORE, 2, check_unit },
4605 { "check", MORE, 2, check_unit },
4606 { "show", MORE, 1, show },
4607 { "status", MORE, 2, show },
4608 { "monitor", EQUAL, 1, monitor },
4609 { "dump", EQUAL, 1, dump },
4610 { "dot", EQUAL, 1, dot },
4611 { "snapshot", LESS, 2, snapshot },
4612 { "delete", MORE, 2, delete_snapshot },
4613 { "daemon-reload", EQUAL, 1, daemon_reload },
4614 { "daemon-reexec", EQUAL, 1, daemon_reload },
4615 { "daemon-exit", EQUAL, 1, daemon_reload },
4616 { "show-environment", EQUAL, 1, show_enviroment },
4617 { "set-environment", MORE, 2, set_environment },
4618 { "unset-environment", MORE, 2, set_environment },
4619 { "halt", EQUAL, 1, start_special },
4620 { "poweroff", EQUAL, 1, start_special },
4621 { "reboot", EQUAL, 1, start_special },
4622 { "default", EQUAL, 1, start_special },
4623 { "rescue", EQUAL, 1, start_special },
4624 { "emergency", EQUAL, 1, start_special },
4625 { "reset-maintenance", MORE, 1, reset_maintenance },
4626 { "enable", MORE, 2, enable_unit },
4627 { "disable", MORE, 2, enable_unit },
4628 { "is-enabled", MORE, 2, enable_unit }
4638 left = argc - optind;
4641 /* Special rule: no arguments means "list-units" */
4644 if (streq(argv[optind], "help")) {
4649 for (i = 0; i < ELEMENTSOF(verbs); i++)
4650 if (streq(argv[optind], verbs[i].verb))
4653 if (i >= ELEMENTSOF(verbs)) {
4654 log_error("Unknown operation %s", argv[optind]);
4659 switch (verbs[i].argc_cmp) {
4662 if (left != verbs[i].argc) {
4663 log_error("Invalid number of arguments.");
4670 if (left < verbs[i].argc) {
4671 log_error("Too few arguments.");
4678 if (left > verbs[i].argc) {
4679 log_error("Too many arguments.");
4686 assert_not_reached("Unknown comparison operator.");
4689 /* Require a bus connection for all operations but
4691 if (!streq(verbs[i].verb, "enable") &&
4692 !streq(verbs[i].verb, "disable") &&
4694 log_error("Failed to get D-Bus connection: %s", error->message);
4698 return verbs[i].dispatch(bus, argv + optind, left);
4701 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
4703 struct msghdr msghdr;
4705 union sockaddr_union sockaddr;
4706 struct ucred *ucred;
4708 struct cmsghdr cmsghdr;
4709 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
4711 struct shutdownd_command c;
4719 strncpy(c.wall_message, message, sizeof(c.wall_message));
4721 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4725 sockaddr.sa.sa_family = AF_UNIX;
4726 sockaddr.un.sun_path[0] = 0;
4727 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
4730 iovec.iov_base = (char*) &c;
4731 iovec.iov_len = sizeof(c);
4734 control.cmsghdr.cmsg_level = SOL_SOCKET;
4735 control.cmsghdr.cmsg_type = SCM_CREDENTIALS;
4736 control.cmsghdr.cmsg_len = CMSG_LEN(sizeof(struct ucred));
4738 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
4739 ucred->pid = getpid();
4740 ucred->uid = getuid();
4741 ucred->gid = getgid();
4744 msghdr.msg_name = &sockaddr;
4745 msghdr.msg_namelen = sizeof(sa_family_t) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
4747 msghdr.msg_iov = &iovec;
4748 msghdr.msg_iovlen = 1;
4749 msghdr.msg_control = &control;
4750 msghdr.msg_controllen = control.cmsghdr.cmsg_len;
4752 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
4753 close_nointr_nofail(fd);
4757 close_nointr_nofail(fd);
4761 static int reload_with_fallback(DBusConnection *bus) {
4764 /* First, try systemd via D-Bus. */
4765 if (daemon_reload(bus, NULL, 0) > 0)
4769 /* Nothing else worked, so let's try signals */
4770 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
4772 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
4773 log_error("kill() failed: %m");
4780 static int start_with_fallback(DBusConnection *bus) {
4783 /* First, try systemd via D-Bus. */
4784 if (start_unit(bus, NULL, 0) > 0)
4788 /* Hmm, talking to systemd via D-Bus didn't work. Then
4789 * let's try to talk to Upstart via D-Bus. */
4790 if (talk_upstart() > 0)
4793 /* Nothing else worked, so let's try
4795 if (talk_initctl() > 0)
4798 log_error("Failed to talk to init daemon.");
4802 warn_wall(arg_action);
4806 static int halt_main(DBusConnection *bus) {
4809 if (geteuid() != 0) {
4810 log_error("Must to be root.");
4816 char date[FORMAT_TIMESTAMP_MAX];
4818 m = strv_join(arg_wall, " ");
4819 r = send_shutdownd(arg_when,
4820 arg_action == ACTION_HALT ? 'H' :
4821 arg_action == ACTION_POWEROFF ? 'P' :
4828 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
4830 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
4831 format_timestamp(date, sizeof(date), arg_when));
4836 if (!arg_dry && !arg_immediate)
4837 return start_with_fallback(bus);
4840 if (sd_booted() > 0)
4841 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
4842 else if ((r = utmp_put_shutdown(0)) < 0)
4843 log_warning("Failed to write utmp record: %s", strerror(-r));
4852 /* Make sure C-A-D is handled by the kernel from this
4854 reboot(RB_ENABLE_CAD);
4856 switch (arg_action) {
4859 log_info("Halting.");
4860 reboot(RB_HALT_SYSTEM);
4863 case ACTION_POWEROFF:
4864 log_info("Powering off.");
4865 reboot(RB_POWER_OFF);
4869 log_info("Rebooting.");
4870 reboot(RB_AUTOBOOT);
4874 assert_not_reached("Unknown halt action.");
4877 /* We should never reach this. */
4881 static int runlevel_main(void) {
4882 int r, runlevel, previous;
4884 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
4885 printf("unknown\n");
4890 previous <= 0 ? 'N' : previous,
4891 runlevel <= 0 ? 'N' : runlevel);
4896 int main(int argc, char*argv[]) {
4898 DBusConnection *bus = NULL;
4901 dbus_error_init(&error);
4903 log_parse_environment();
4906 if ((r = parse_argv(argc, argv)) < 0)
4913 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
4914 * let's shortcut this */
4915 if (arg_action == ACTION_RUNLEVEL) {
4916 retval = runlevel_main() < 0;
4920 bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
4922 switch (arg_action) {
4924 case ACTION_SYSTEMCTL: {
4925 retval = systemctl_main(bus, argc, argv, &error) < 0;
4930 case ACTION_POWEROFF:
4932 retval = halt_main(bus) < 0;
4935 case ACTION_RUNLEVEL2:
4936 case ACTION_RUNLEVEL3:
4937 case ACTION_RUNLEVEL4:
4938 case ACTION_RUNLEVEL5:
4940 case ACTION_EMERGENCY:
4941 case ACTION_DEFAULT:
4942 retval = start_with_fallback(bus) < 0;
4947 retval = reload_with_fallback(bus) < 0;
4950 case ACTION_CANCEL_SHUTDOWN:
4951 retval = send_shutdownd(0, 0, false, NULL) < 0;
4954 case ACTION_INVALID:
4955 case ACTION_RUNLEVEL:
4957 assert_not_reached("Unknown action");
4963 dbus_connection_close(bus);
4964 dbus_connection_unref(bus);
4967 dbus_error_free(&error);
4971 strv_free(arg_property);