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"
54 static const char *arg_type = NULL;
55 static char **arg_property = NULL;
56 static bool arg_all = false;
57 static bool arg_fail = false;
58 static bool arg_session = false;
59 static bool arg_global = false;
60 static bool arg_immediate = false;
61 static bool arg_no_block = false;
62 static bool arg_no_wtmp = false;
63 static bool arg_no_sync = false;
64 static bool arg_no_wall = false;
65 static bool arg_no_reload = false;
66 static bool arg_dry = false;
67 static bool arg_quiet = false;
68 static bool arg_full = false;
69 static bool arg_force = false;
70 static bool arg_defaults = false;
71 static char **arg_wall = NULL;
72 static usec_t arg_when = 0;
89 ACTION_CANCEL_SHUTDOWN,
91 } arg_action = ACTION_SYSTEMCTL;
98 static bool private_bus = false;
100 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
102 static bool on_tty(void) {
105 if (_unlikely_(t < 0))
106 t = isatty(STDOUT_FILENO) > 0;
111 static const char *ansi_highlight(bool b) {
116 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
119 static const char *ansi_highlight_green(bool b) {
124 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
127 static bool error_is_no_service(DBusError *error) {
131 if (!dbus_error_is_set(error))
134 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
137 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
140 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
143 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
148 if (dbus_message_iter_get_arg_type(iter) != type)
151 dbus_message_iter_get_basic(iter, data);
153 if (!dbus_message_iter_next(iter) != !next)
159 static void warn_wall(enum action action) {
160 static const char *table[_ACTION_MAX] = {
161 [ACTION_HALT] = "The system is going down for system halt NOW!",
162 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
163 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
164 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
165 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
174 if (!(p = strv_join(arg_wall, " "))) {
175 log_error("Failed to join strings.");
191 utmp_wall(table[action]);
196 const char *description;
197 const char *load_state;
198 const char *active_state;
199 const char *sub_state;
200 const char *following;
201 const char *unit_path;
203 const char *job_type;
204 const char *job_path;
207 static int compare_unit_info(const void *a, const void *b) {
209 const struct unit_info *u = a, *v = b;
211 d1 = strrchr(u->id, '.');
212 d2 = strrchr(v->id, '.');
217 if ((r = strcasecmp(d1, d2)) != 0)
221 return strcasecmp(u->id, v->id);
224 static int list_units(DBusConnection *bus, char **args, unsigned n) {
225 DBusMessage *m = NULL, *reply = NULL;
228 DBusMessageIter iter, sub, sub2;
229 unsigned c = 0, k, n_units = 0;
230 struct unit_info *unit_infos = NULL;
232 dbus_error_init(&error);
236 if (!(m = dbus_message_new_method_call(
237 "org.freedesktop.systemd1",
238 "/org/freedesktop/systemd1",
239 "org.freedesktop.systemd1.Manager",
241 log_error("Could not allocate message.");
245 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
246 log_error("Failed to issue method call: %s", error.message);
251 if (!dbus_message_iter_init(reply, &iter) ||
252 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
253 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
254 log_error("Failed to parse reply.");
259 dbus_message_iter_recurse(&iter, &sub);
261 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
264 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
265 log_error("Failed to parse reply.");
273 n_units = MAX(2*c, 16);
274 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
277 log_error("Failed to allocate unit array.");
287 dbus_message_iter_recurse(&sub, &sub2);
289 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
290 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
291 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
292 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
293 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
294 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
295 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
296 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
297 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
298 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
299 log_error("Failed to parse reply.");
304 dbus_message_iter_next(&sub);
308 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
310 if (isatty(STDOUT_FILENO))
311 printf("%-45s %-6s %-12s %-12s %-15s %s\n", "UNIT", "LOAD", "ACTIVE", "SUB", "JOB", "DESCRIPTION");
313 for (k = 0; k < c; k++) {
315 struct unit_info *u = unit_infos+k;
317 if ((!arg_type || ((dot = strrchr(u->id, '.')) &&
318 streq(dot+1, arg_type))) &&
319 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0)) {
322 const char *on, *off;
324 if (streq(u->active_state, "maintenance")) {
325 on = ansi_highlight(true);
326 off = ansi_highlight(false);
330 e = arg_full ? NULL : ellipsize(u->id, 45, 33);
331 printf("%-45s %-6s %s%-12s %-12s%s%n", e ? e : u->id, u->load_state, on, u->active_state, u->sub_state, off, &a);
334 a -= strlen(on) + strlen(off);
337 printf(" => %-12s%n", u->job_type, &b);
341 if (a + b + 2 < columns()) {
345 printf(" %.*s", columns() - a - b - 2, u->description);
352 if (isatty(STDOUT_FILENO)) {
354 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
355 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
356 "SUB = The low-level unit activation state, values depend on unit type.\n"
357 "JOB = Pending job for the unit.\n");
360 printf("\n%u units listed.\n", c);
362 printf("\n%u units listed. Pass --all to see inactive units, too.\n", c);
369 dbus_message_unref(m);
372 dbus_message_unref(reply);
376 dbus_error_free(&error);
381 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
382 static const char * const colors[] = {
383 "Requires", "[color=\"black\"]",
384 "RequiresOverridable", "[color=\"black\"]",
385 "Requisite", "[color=\"darkblue\"]",
386 "RequisiteOverridable", "[color=\"darkblue\"]",
387 "Wants", "[color=\"darkgrey\"]",
388 "Conflicts", "[color=\"red\"]",
389 "ConflictedBy", "[color=\"red\"]",
390 "After", "[color=\"green\"]"
393 const char *c = NULL;
400 for (i = 0; i < ELEMENTSOF(colors); i += 2)
401 if (streq(colors[i], prop)) {
409 if (arg_dot != DOT_ALL)
410 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
413 switch (dbus_message_iter_get_arg_type(iter)) {
415 case DBUS_TYPE_ARRAY:
417 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
420 dbus_message_iter_recurse(iter, &sub);
422 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
425 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
426 dbus_message_iter_get_basic(&sub, &s);
427 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
429 dbus_message_iter_next(&sub);
439 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
440 DBusMessage *m = NULL, *reply = NULL;
441 const char *interface = "org.freedesktop.systemd1.Unit";
444 DBusMessageIter iter, sub, sub2, sub3;
449 dbus_error_init(&error);
451 if (!(m = dbus_message_new_method_call(
452 "org.freedesktop.systemd1",
454 "org.freedesktop.DBus.Properties",
456 log_error("Could not allocate message.");
461 if (!dbus_message_append_args(m,
462 DBUS_TYPE_STRING, &interface,
463 DBUS_TYPE_INVALID)) {
464 log_error("Could not append arguments to message.");
469 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
470 log_error("Failed to issue method call: %s", error.message);
475 if (!dbus_message_iter_init(reply, &iter) ||
476 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
477 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
478 log_error("Failed to parse reply.");
483 dbus_message_iter_recurse(&iter, &sub);
485 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
488 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
489 log_error("Failed to parse reply.");
494 dbus_message_iter_recurse(&sub, &sub2);
496 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
497 log_error("Failed to parse reply.");
502 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
503 log_error("Failed to parse reply.");
508 dbus_message_iter_recurse(&sub2, &sub3);
510 if (dot_one_property(name, prop, &sub3)) {
511 log_error("Failed to parse reply.");
516 dbus_message_iter_next(&sub);
523 dbus_message_unref(m);
526 dbus_message_unref(reply);
528 dbus_error_free(&error);
533 static int dot(DBusConnection *bus, char **args, unsigned n) {
534 DBusMessage *m = NULL, *reply = NULL;
537 DBusMessageIter iter, sub, sub2;
539 dbus_error_init(&error);
543 if (!(m = dbus_message_new_method_call(
544 "org.freedesktop.systemd1",
545 "/org/freedesktop/systemd1",
546 "org.freedesktop.systemd1.Manager",
548 log_error("Could not allocate message.");
552 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
553 log_error("Failed to issue method call: %s", error.message);
558 if (!dbus_message_iter_init(reply, &iter) ||
559 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
560 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
561 log_error("Failed to parse reply.");
566 printf("digraph systemd {\n");
568 dbus_message_iter_recurse(&iter, &sub);
569 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
570 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
572 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
573 log_error("Failed to parse reply.");
578 dbus_message_iter_recurse(&sub, &sub2);
580 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
581 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
582 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
583 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
584 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
585 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
586 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
587 log_error("Failed to parse reply.");
592 if ((r = dot_one(bus, id, unit_path)) < 0)
595 /* printf("\t\"%s\";\n", id); */
596 dbus_message_iter_next(&sub);
601 log_info(" Color legend: black = Requires\n"
602 " dark blue = Requisite\n"
603 " dark grey = Wants\n"
607 if (isatty(fileno(stdout)))
608 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
609 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
615 dbus_message_unref(m);
618 dbus_message_unref(reply);
620 dbus_error_free(&error);
625 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
626 DBusMessage *m = NULL, *reply = NULL;
629 DBusMessageIter iter, sub, sub2;
632 dbus_error_init(&error);
636 if (!(m = dbus_message_new_method_call(
637 "org.freedesktop.systemd1",
638 "/org/freedesktop/systemd1",
639 "org.freedesktop.systemd1.Manager",
641 log_error("Could not allocate message.");
645 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
646 log_error("Failed to issue method call: %s", error.message);
651 if (!dbus_message_iter_init(reply, &iter) ||
652 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
653 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
654 log_error("Failed to parse reply.");
659 dbus_message_iter_recurse(&iter, &sub);
661 printf("%4s %-45s %-17s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
663 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
664 const char *name, *type, *state, *job_path, *unit_path;
668 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
669 log_error("Failed to parse reply.");
674 dbus_message_iter_recurse(&sub, &sub2);
676 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
677 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
678 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
679 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
680 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
681 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
682 log_error("Failed to parse reply.");
687 e = arg_full ? NULL : ellipsize(name, 45, 33);
688 printf("%4u %-45s %-17s %-7s\n", id, e ? e : name, type, state);
693 dbus_message_iter_next(&sub);
696 printf("\n%u jobs listed.\n", k);
701 dbus_message_unref(m);
704 dbus_message_unref(reply);
706 dbus_error_free(&error);
711 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
712 DBusMessage *m = NULL, *reply = NULL;
717 dbus_error_init(&error);
722 for (i = 1; i < n; i++) {
724 if (!(m = dbus_message_new_method_call(
725 "org.freedesktop.systemd1",
726 "/org/freedesktop/systemd1",
727 "org.freedesktop.systemd1.Manager",
729 log_error("Could not allocate message.");
734 if (!dbus_message_append_args(m,
735 DBUS_TYPE_STRING, &args[i],
736 DBUS_TYPE_INVALID)) {
737 log_error("Could not append arguments to message.");
742 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
743 log_error("Failed to issue method call: %s", error.message);
748 dbus_message_unref(m);
749 dbus_message_unref(reply);
758 dbus_message_unref(m);
761 dbus_message_unref(reply);
763 dbus_error_free(&error);
768 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
769 DBusMessage *m = NULL, *reply = NULL;
774 dbus_error_init(&error);
780 return daemon_reload(bus, args, n);
782 for (i = 1; i < n; i++) {
786 if (!(m = dbus_message_new_method_call(
787 "org.freedesktop.systemd1",
788 "/org/freedesktop/systemd1",
789 "org.freedesktop.systemd1.Manager",
791 log_error("Could not allocate message.");
796 if ((r = safe_atou(args[i], &id)) < 0) {
797 log_error("Failed to parse job id: %s", strerror(-r));
801 assert_cc(sizeof(uint32_t) == sizeof(id));
802 if (!dbus_message_append_args(m,
803 DBUS_TYPE_UINT32, &id,
804 DBUS_TYPE_INVALID)) {
805 log_error("Could not append arguments to message.");
810 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
811 log_error("Failed to issue method call: %s", error.message);
816 if (!dbus_message_get_args(reply, &error,
817 DBUS_TYPE_OBJECT_PATH, &path,
818 DBUS_TYPE_INVALID)) {
819 log_error("Failed to parse reply: %s", error.message);
824 dbus_message_unref(m);
825 if (!(m = dbus_message_new_method_call(
826 "org.freedesktop.systemd1",
828 "org.freedesktop.systemd1.Job",
830 log_error("Could not allocate message.");
835 dbus_message_unref(reply);
836 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
837 log_error("Failed to issue method call: %s", error.message);
842 dbus_message_unref(m);
843 dbus_message_unref(reply);
851 dbus_message_unref(m);
854 dbus_message_unref(reply);
856 dbus_error_free(&error);
861 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
862 DBusMessage *m = NULL, *reply = NULL;
863 dbus_bool_t b = FALSE;
864 DBusMessageIter iter, sub;
866 *interface = "org.freedesktop.systemd1.Unit",
867 *property = "NeedDaemonReload",
870 /* We ignore all errors here, since this is used to show a warning only */
872 if (!(m = dbus_message_new_method_call(
873 "org.freedesktop.systemd1",
874 "/org/freedesktop/systemd1",
875 "org.freedesktop.systemd1.Manager",
879 if (!dbus_message_append_args(m,
880 DBUS_TYPE_STRING, &unit,
884 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
887 if (!dbus_message_get_args(reply, NULL,
888 DBUS_TYPE_OBJECT_PATH, &path,
892 dbus_message_unref(m);
893 if (!(m = dbus_message_new_method_call(
894 "org.freedesktop.systemd1",
896 "org.freedesktop.DBus.Properties",
900 if (!dbus_message_append_args(m,
901 DBUS_TYPE_STRING, &interface,
902 DBUS_TYPE_STRING, &property,
903 DBUS_TYPE_INVALID)) {
907 dbus_message_unref(reply);
908 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
911 if (!dbus_message_iter_init(reply, &iter) ||
912 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
915 dbus_message_iter_recurse(&iter, &sub);
917 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
920 dbus_message_iter_get_basic(&sub, &b);
924 dbus_message_unref(m);
927 dbus_message_unref(reply);
932 typedef struct WaitData {
937 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
945 dbus_error_init(&error);
947 log_debug("Got D-Bus request: %s.%s() on %s",
948 dbus_message_get_interface(message),
949 dbus_message_get_member(message),
950 dbus_message_get_path(message));
952 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
953 log_error("Warning! D-Bus connection terminated.");
954 dbus_connection_close(connection);
956 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
959 dbus_bool_t success = true;
961 if (!dbus_message_get_args(message, &error,
962 DBUS_TYPE_UINT32, &id,
963 DBUS_TYPE_OBJECT_PATH, &path,
964 DBUS_TYPE_BOOLEAN, &success,
966 log_error("Failed to parse message: %s", error.message);
970 if ((p = set_remove(d->set, (char*) path)))
978 dbus_error_free(&error);
979 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
982 static int enable_wait_for_jobs(DBusConnection *bus) {
990 dbus_error_init(&error);
991 dbus_bus_add_match(bus,
993 "sender='org.freedesktop.systemd1',"
994 "interface='org.freedesktop.systemd1.Manager',"
995 "member='JobRemoved',"
996 "path='/org/freedesktop/systemd1'",
999 if (dbus_error_is_set(&error)) {
1000 log_error("Failed to add match: %s", error.message);
1001 dbus_error_free(&error);
1005 /* This is slightly dirty, since we don't undo the match registrations. */
1009 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1020 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1021 log_error("Failed to add filter.");
1026 while (!set_isempty(s) &&
1027 dbus_connection_read_write_dispatch(bus, -1))
1030 if (!arg_quiet && d.failed)
1031 log_error("Job failed, see logs for details.");
1033 r = d.failed ? -EIO : 0;
1036 /* This is slightly dirty, since we don't undo the filter registration. */
1041 static int start_unit_one(
1042 DBusConnection *bus,
1048 DBusMessage *m = NULL, *reply = NULL;
1057 assert(arg_no_block || s);
1059 dbus_error_init(&error);
1061 if (!(m = dbus_message_new_method_call(
1062 "org.freedesktop.systemd1",
1063 "/org/freedesktop/systemd1",
1064 "org.freedesktop.systemd1.Manager",
1066 log_error("Could not allocate message.");
1071 if (!dbus_message_append_args(m,
1072 DBUS_TYPE_STRING, &name,
1073 DBUS_TYPE_STRING, &mode,
1074 DBUS_TYPE_INVALID)) {
1075 log_error("Could not append arguments to message.");
1080 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1082 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
1083 /* There's always a fallback possible for
1084 * legacy actions. */
1089 log_error("Failed to issue method call: %s", error.message);
1094 if (!dbus_message_get_args(reply, &error,
1095 DBUS_TYPE_OBJECT_PATH, &path,
1096 DBUS_TYPE_INVALID)) {
1097 log_error("Failed to parse reply: %s", error.message);
1102 if (need_daemon_reload(bus, name))
1103 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1104 arg_session ? "--session" : "--system");
1106 if (!arg_no_block) {
1109 if (!(p = strdup(path))) {
1110 log_error("Failed to duplicate path.");
1115 if ((r = set_put(s, p)) < 0) {
1117 log_error("Failed to add path to set.");
1126 dbus_message_unref(m);
1129 dbus_message_unref(reply);
1131 dbus_error_free(&error);
1136 static enum action verb_to_action(const char *verb) {
1137 if (streq(verb, "halt"))
1139 else if (streq(verb, "poweroff"))
1140 return ACTION_POWEROFF;
1141 else if (streq(verb, "reboot"))
1142 return ACTION_REBOOT;
1143 else if (streq(verb, "rescue"))
1144 return ACTION_RESCUE;
1145 else if (streq(verb, "emergency"))
1146 return ACTION_EMERGENCY;
1147 else if (streq(verb, "default"))
1148 return ACTION_DEFAULT;
1150 return ACTION_INVALID;
1153 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1155 static const char * const table[_ACTION_MAX] = {
1156 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1157 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1158 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1159 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1160 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1161 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1162 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1163 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1164 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1165 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET
1170 const char *method, *mode, *one_name;
1175 if (arg_action == ACTION_SYSTEMCTL) {
1177 streq(args[0], "stop") ? "StopUnit" :
1178 streq(args[0], "reload") ? "ReloadUnit" :
1179 streq(args[0], "restart") ? "RestartUnit" :
1180 streq(args[0], "try-restart") ? "TryRestartUnit" :
1181 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1182 streq(args[0], "reload-or-try-restart") ||
1183 streq(args[0], "force-reload") ||
1184 streq(args[0], "condrestart") ? "ReloadOrTryRestartUnit" :
1188 (streq(args[0], "isolate") ||
1189 streq(args[0], "rescue") ||
1190 streq(args[0], "emergency")) ? "isolate" :
1194 one_name = table[verb_to_action(args[0])];
1197 assert(arg_action < ELEMENTSOF(table));
1198 assert(table[arg_action]);
1200 method = "StartUnit";
1202 mode = (arg_action == ACTION_EMERGENCY ||
1203 arg_action == ACTION_RESCUE) ? "isolate" : "replace";
1205 one_name = table[arg_action];
1208 if (!arg_no_block) {
1209 if ((r = enable_wait_for_jobs(bus)) < 0) {
1210 log_error("Could not watch jobs: %s", strerror(-r));
1214 if (!(s = set_new(string_hash_func, string_compare_func))) {
1215 log_error("Failed to allocate set.");
1224 if ((r = start_unit_one(bus, method, one_name, mode, s)) <= 0)
1227 for (i = 1; i < n; i++)
1228 if ((r = start_unit_one(bus, method, args[i], mode, s)) < 0)
1233 if ((r = wait_for_jobs(bus, s)) < 0)
1245 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1251 r = start_unit(bus, args, n);
1254 warn_wall(verb_to_action(args[0]));
1259 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1260 DBusMessage *m = NULL, *reply = NULL;
1262 *interface = "org.freedesktop.systemd1.Unit",
1263 *property = "ActiveState";
1264 int r = -EADDRNOTAVAIL;
1271 dbus_error_init(&error);
1273 for (i = 1; i < n; i++) {
1274 const char *path = NULL;
1276 DBusMessageIter iter, sub;
1278 if (!(m = dbus_message_new_method_call(
1279 "org.freedesktop.systemd1",
1280 "/org/freedesktop/systemd1",
1281 "org.freedesktop.systemd1.Manager",
1283 log_error("Could not allocate message.");
1288 if (!dbus_message_append_args(m,
1289 DBUS_TYPE_STRING, &args[i],
1290 DBUS_TYPE_INVALID)) {
1291 log_error("Could not append arguments to message.");
1296 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1298 /* Hmm, cannot figure out anything about this unit... */
1302 dbus_error_free(&error);
1306 if (!dbus_message_get_args(reply, &error,
1307 DBUS_TYPE_OBJECT_PATH, &path,
1308 DBUS_TYPE_INVALID)) {
1309 log_error("Failed to parse reply: %s", error.message);
1314 dbus_message_unref(m);
1315 if (!(m = dbus_message_new_method_call(
1316 "org.freedesktop.systemd1",
1318 "org.freedesktop.DBus.Properties",
1320 log_error("Could not allocate message.");
1325 if (!dbus_message_append_args(m,
1326 DBUS_TYPE_STRING, &interface,
1327 DBUS_TYPE_STRING, &property,
1328 DBUS_TYPE_INVALID)) {
1329 log_error("Could not append arguments to message.");
1334 dbus_message_unref(reply);
1335 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1336 log_error("Failed to issue method call: %s", error.message);
1341 if (!dbus_message_iter_init(reply, &iter) ||
1342 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1343 log_error("Failed to parse reply.");
1348 dbus_message_iter_recurse(&iter, &sub);
1350 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1351 log_error("Failed to parse reply.");
1356 dbus_message_iter_get_basic(&sub, &state);
1361 if (streq(state, "active") || startswith(state, "reloading"))
1364 dbus_message_unref(m);
1365 dbus_message_unref(reply);
1371 dbus_message_unref(m);
1374 dbus_message_unref(reply);
1376 dbus_error_free(&error);
1381 typedef struct ExecStatusInfo {
1387 usec_t start_timestamp;
1388 usec_t exit_timestamp;
1393 LIST_FIELDS(struct ExecStatusInfo, exec);
1396 static void exec_status_info_free(ExecStatusInfo *i) {
1404 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1405 uint64_t start_timestamp, exit_timestamp;
1406 DBusMessageIter sub2, sub3;
1410 int32_t code, status;
1416 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1419 dbus_message_iter_recurse(sub, &sub2);
1421 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1424 if (!(i->path = strdup(path)))
1427 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1428 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1432 dbus_message_iter_recurse(&sub2, &sub3);
1433 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1434 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1435 dbus_message_iter_next(&sub3);
1440 if (!(i->argv = new0(char*, n+1)))
1444 dbus_message_iter_recurse(&sub2, &sub3);
1445 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1448 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1449 dbus_message_iter_get_basic(&sub3, &s);
1450 dbus_message_iter_next(&sub3);
1452 if (!(i->argv[n++] = strdup(s)))
1456 if (!dbus_message_iter_next(&sub2) ||
1457 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1458 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1459 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1460 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1461 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1462 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1466 i->start_timestamp = (usec_t) start_timestamp;
1467 i->exit_timestamp = (usec_t) exit_timestamp;
1468 i->pid = (pid_t) pid;
1475 typedef struct UnitStatusInfo {
1477 const char *load_state;
1478 const char *active_state;
1479 const char *sub_state;
1481 const char *description;
1484 const char *default_control_group;
1486 bool need_daemon_reload;
1491 const char *status_text;
1494 usec_t start_timestamp;
1495 usec_t exit_timestamp;
1497 int exit_code, exit_status;
1500 unsigned n_accepted;
1501 unsigned n_connections;
1505 const char *sysfs_path;
1507 /* Mount, Automount */
1513 LIST_HEAD(ExecStatusInfo, exec);
1516 static void print_status_info(UnitStatusInfo *i) {
1518 const char *on, *off, *ss;
1522 /* This shows pretty information about a unit. See
1523 * print_property() for a low-level property printer */
1525 printf("%s", strna(i->id));
1527 if (i->description && !streq_ptr(i->id, i->description))
1528 printf(" - %s", i->description);
1532 if (streq_ptr(i->load_state, "failed")) {
1533 on = ansi_highlight(true);
1534 off = ansi_highlight(false);
1539 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1541 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1543 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1545 if (streq_ptr(i->active_state, "maintenance")) {
1546 on = ansi_highlight(true);
1547 off = ansi_highlight(false);
1548 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1549 on = ansi_highlight_green(true);
1550 off = ansi_highlight_green(false);
1555 printf("\t Active: %s%s (%s)%s\n",
1557 strna(i->active_state),
1561 printf("\t Active: %s%s%s\n",
1563 strna(i->active_state),
1567 printf("\t Device: %s\n", i->sysfs_path);
1569 printf("\t Where: %s\n", i->where);
1571 printf("\t What: %s\n", i->what);
1574 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1576 LIST_FOREACH(exec, p, i->exec) {
1579 /* Only show exited processes here */
1583 t = strv_join(p->argv, " ");
1584 printf("\t Exited: %u (%s, code=%s, ", p->pid, strna(t), sigchld_code_to_string(p->code));
1587 if (p->code == CLD_EXITED)
1588 printf("status=%i", p->status);
1590 printf("signal=%s", signal_to_string(p->status));
1593 if (i->main_pid == p->pid &&
1594 i->start_timestamp == p->start_timestamp &&
1595 i->exit_timestamp == p->start_timestamp)
1596 /* Let's not show this twice */
1599 if (p->pid == i->control_pid)
1603 if (i->main_pid > 0 || i->control_pid > 0) {
1606 if (i->main_pid > 0) {
1607 printf(" Main: %u", (unsigned) i->main_pid);
1611 get_process_name(i->main_pid, &t);
1616 } else if (i->exit_code > 0) {
1617 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1619 if (i->exit_code == CLD_EXITED)
1620 printf("status=%i", i->exit_status);
1622 printf("signal=%s", signal_to_string(i->exit_status));
1627 if (i->main_pid > 0 && i->control_pid > 0)
1630 if (i->control_pid > 0) {
1633 printf(" Control: %u", (unsigned) i->control_pid);
1635 get_process_name(i->control_pid, &t);
1646 printf("\t Status: \"%s\"\n", i->status_text);
1648 if (i->default_control_group) {
1651 printf("\t CGroup: %s\n", i->default_control_group);
1653 if ((c = columns()) > 18)
1658 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
1661 if (i->need_daemon_reload)
1662 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1663 ansi_highlight(true),
1664 ansi_highlight(false),
1665 arg_session ? "--session" : "--system");
1668 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1670 switch (dbus_message_iter_get_arg_type(iter)) {
1672 case DBUS_TYPE_STRING: {
1675 dbus_message_iter_get_basic(iter, &s);
1678 if (streq(name, "Id"))
1680 else if (streq(name, "LoadState"))
1682 else if (streq(name, "ActiveState"))
1683 i->active_state = s;
1684 else if (streq(name, "SubState"))
1686 else if (streq(name, "Description"))
1688 else if (streq(name, "FragmentPath"))
1690 else if (streq(name, "SysVPath"))
1692 else if (streq(name, "DefaultControlGroup"))
1693 i->default_control_group = s;
1694 else if (streq(name, "StatusText"))
1696 else if (streq(name, "SysFSPath"))
1698 else if (streq(name, "Where"))
1700 else if (streq(name, "What"))
1707 case DBUS_TYPE_BOOLEAN: {
1710 dbus_message_iter_get_basic(iter, &b);
1712 if (streq(name, "Accept"))
1714 else if (streq(name, "NeedDaemonReload"))
1715 i->need_daemon_reload = b;
1720 case DBUS_TYPE_UINT32: {
1723 dbus_message_iter_get_basic(iter, &u);
1725 if (streq(name, "MainPID")) {
1727 i->main_pid = (pid_t) u;
1730 } else if (streq(name, "ControlPID"))
1731 i->control_pid = (pid_t) u;
1732 else if (streq(name, "ExecMainPID")) {
1734 i->main_pid = (pid_t) u;
1735 } else if (streq(name, "NAccepted"))
1737 else if (streq(name, "NConnections"))
1738 i->n_connections = u;
1743 case DBUS_TYPE_INT32: {
1746 dbus_message_iter_get_basic(iter, &j);
1748 if (streq(name, "ExecMainCode"))
1749 i->exit_code = (int) j;
1750 else if (streq(name, "ExecMainStatus"))
1751 i->exit_status = (int) j;
1756 case DBUS_TYPE_UINT64: {
1759 dbus_message_iter_get_basic(iter, &u);
1761 if (streq(name, "ExecMainStartTimestamp"))
1762 i->start_timestamp = (usec_t) u;
1763 else if (streq(name, "ExecMainExitTimestamp"))
1764 i->exit_timestamp = (usec_t) u;
1769 case DBUS_TYPE_ARRAY: {
1771 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
1772 startswith(name, "Exec")) {
1773 DBusMessageIter sub;
1775 dbus_message_iter_recurse(iter, &sub);
1776 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1777 ExecStatusInfo *info;
1780 if (!(info = new0(ExecStatusInfo, 1)))
1783 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
1788 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
1790 dbus_message_iter_next(&sub);
1801 static int print_property(const char *name, DBusMessageIter *iter) {
1805 /* This is a low-level property printer, see
1806 * print_status_info() for the nicer output */
1808 if (arg_property && !strv_find(arg_property, name))
1811 switch (dbus_message_iter_get_arg_type(iter)) {
1813 case DBUS_TYPE_STRING: {
1815 dbus_message_iter_get_basic(iter, &s);
1817 if (arg_all || s[0])
1818 printf("%s=%s\n", name, s);
1823 case DBUS_TYPE_BOOLEAN: {
1825 dbus_message_iter_get_basic(iter, &b);
1826 printf("%s=%s\n", name, yes_no(b));
1831 case DBUS_TYPE_UINT64: {
1833 dbus_message_iter_get_basic(iter, &u);
1835 /* Yes, heuristics! But we can change this check
1836 * should it turn out to not be sufficient */
1838 if (strstr(name, "Timestamp")) {
1839 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
1841 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
1842 printf("%s=%s\n", name, strempty(t));
1843 } else if (strstr(name, "USec")) {
1844 char timespan[FORMAT_TIMESPAN_MAX];
1846 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
1848 printf("%s=%llu\n", name, (unsigned long long) u);
1853 case DBUS_TYPE_UINT32: {
1855 dbus_message_iter_get_basic(iter, &u);
1857 if (strstr(name, "UMask") || strstr(name, "Mode"))
1858 printf("%s=%04o\n", name, u);
1860 printf("%s=%u\n", name, (unsigned) u);
1865 case DBUS_TYPE_INT32: {
1867 dbus_message_iter_get_basic(iter, &i);
1869 printf("%s=%i\n", name, (int) i);
1873 case DBUS_TYPE_STRUCT: {
1874 DBusMessageIter sub;
1875 dbus_message_iter_recurse(iter, &sub);
1877 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
1880 dbus_message_iter_get_basic(&sub, &u);
1883 printf("%s=%u\n", name, (unsigned) u);
1885 printf("%s=\n", name);
1888 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
1891 dbus_message_iter_get_basic(&sub, &s);
1893 if (arg_all || s[0])
1894 printf("%s=%s\n", name, s);
1902 case DBUS_TYPE_ARRAY:
1904 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
1905 DBusMessageIter sub;
1908 dbus_message_iter_recurse(iter, &sub);
1910 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1911 printf("%s=", name);
1913 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1916 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
1917 dbus_message_iter_get_basic(&sub, &s);
1918 printf("%s%s", space ? " " : "", s);
1921 dbus_message_iter_next(&sub);
1929 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
1930 DBusMessageIter sub;
1932 dbus_message_iter_recurse(iter, &sub);
1934 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1935 printf("%s=", name);
1937 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1940 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
1941 dbus_message_iter_get_basic(&sub, &u);
1944 dbus_message_iter_next(&sub);
1952 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
1953 DBusMessageIter sub, sub2;
1955 dbus_message_iter_recurse(iter, &sub);
1956 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1957 const char *type, *path;
1959 dbus_message_iter_recurse(&sub, &sub2);
1961 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
1962 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
1963 printf("%s=%s\n", type, path);
1965 dbus_message_iter_next(&sub);
1970 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
1971 DBusMessageIter sub, sub2;
1973 dbus_message_iter_recurse(iter, &sub);
1974 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1976 uint64_t value, next_elapse;
1978 dbus_message_iter_recurse(&sub, &sub2);
1980 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
1981 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
1982 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
1983 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
1985 printf("%s={ value=%s ; next_elapse=%s }\n",
1987 format_timespan(timespan1, sizeof(timespan1), value),
1988 format_timespan(timespan2, sizeof(timespan2), next_elapse));
1991 dbus_message_iter_next(&sub);
1996 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
1997 DBusMessageIter sub;
1999 dbus_message_iter_recurse(iter, &sub);
2000 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2001 ExecStatusInfo info;
2004 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2005 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2008 t = strv_join(info.argv, " ");
2010 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2014 yes_no(info.ignore),
2015 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2016 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2017 (unsigned) info. pid,
2018 sigchld_code_to_string(info.code),
2020 info.code == CLD_EXITED ? "" : "/",
2021 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2027 strv_free(info.argv);
2029 dbus_message_iter_next(&sub);
2039 printf("%s=[unprintable]\n", name);
2044 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2045 DBusMessage *m = NULL, *reply = NULL;
2046 const char *interface = "";
2049 DBusMessageIter iter, sub, sub2, sub3;
2050 UnitStatusInfo info;
2058 dbus_error_init(&error);
2060 if (!(m = dbus_message_new_method_call(
2061 "org.freedesktop.systemd1",
2063 "org.freedesktop.DBus.Properties",
2065 log_error("Could not allocate message.");
2070 if (!dbus_message_append_args(m,
2071 DBUS_TYPE_STRING, &interface,
2072 DBUS_TYPE_INVALID)) {
2073 log_error("Could not append arguments to message.");
2078 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2079 log_error("Failed to issue method call: %s", error.message);
2084 if (!dbus_message_iter_init(reply, &iter) ||
2085 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2086 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2087 log_error("Failed to parse reply.");
2092 dbus_message_iter_recurse(&iter, &sub);
2099 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2102 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2103 log_error("Failed to parse reply.");
2108 dbus_message_iter_recurse(&sub, &sub2);
2110 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2111 log_error("Failed to parse reply.");
2116 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2117 log_error("Failed to parse reply.");
2122 dbus_message_iter_recurse(&sub2, &sub3);
2124 if (show_properties)
2125 r = print_property(name, &sub3);
2127 r = status_property(name, &sub3, &info);
2130 log_error("Failed to parse reply.");
2135 dbus_message_iter_next(&sub);
2138 if (!show_properties)
2139 print_status_info(&info);
2141 while ((p = info.exec)) {
2142 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2143 exec_status_info_free(p);
2150 dbus_message_unref(m);
2153 dbus_message_unref(reply);
2155 dbus_error_free(&error);
2160 static int show(DBusConnection *bus, char **args, unsigned n) {
2161 DBusMessage *m = NULL, *reply = NULL;
2165 bool show_properties, new_line = false;
2170 dbus_error_init(&error);
2172 show_properties = !streq(args[0], "status");
2174 if (show_properties && n <= 1) {
2175 /* If not argument is specified inspect the manager
2178 r = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2182 for (i = 1; i < n; i++) {
2183 const char *path = NULL;
2186 if (safe_atou32(args[i], &id) < 0) {
2188 /* Interpret as unit name */
2190 if (!(m = dbus_message_new_method_call(
2191 "org.freedesktop.systemd1",
2192 "/org/freedesktop/systemd1",
2193 "org.freedesktop.systemd1.Manager",
2195 log_error("Could not allocate message.");
2200 if (!dbus_message_append_args(m,
2201 DBUS_TYPE_STRING, &args[i],
2202 DBUS_TYPE_INVALID)) {
2203 log_error("Could not append arguments to message.");
2208 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2210 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2211 log_error("Failed to issue method call: %s", error.message);
2216 dbus_error_free(&error);
2218 dbus_message_unref(m);
2219 if (!(m = dbus_message_new_method_call(
2220 "org.freedesktop.systemd1",
2221 "/org/freedesktop/systemd1",
2222 "org.freedesktop.systemd1.Manager",
2224 log_error("Could not allocate message.");
2229 if (!dbus_message_append_args(m,
2230 DBUS_TYPE_STRING, &args[i],
2231 DBUS_TYPE_INVALID)) {
2232 log_error("Could not append arguments to message.");
2237 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2238 log_error("Failed to issue method call: %s", error.message);
2244 } else if (show_properties) {
2246 /* Interpret as job id */
2248 if (!(m = dbus_message_new_method_call(
2249 "org.freedesktop.systemd1",
2250 "/org/freedesktop/systemd1",
2251 "org.freedesktop.systemd1.Manager",
2253 log_error("Could not allocate message.");
2258 if (!dbus_message_append_args(m,
2259 DBUS_TYPE_UINT32, &id,
2260 DBUS_TYPE_INVALID)) {
2261 log_error("Could not append arguments to message.");
2266 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2267 log_error("Failed to issue method call: %s", error.message);
2273 /* Interpret as PID */
2275 if (!(m = dbus_message_new_method_call(
2276 "org.freedesktop.systemd1",
2277 "/org/freedesktop/systemd1",
2278 "org.freedesktop.systemd1.Manager",
2280 log_error("Could not allocate message.");
2285 if (!dbus_message_append_args(m,
2286 DBUS_TYPE_UINT32, &id,
2287 DBUS_TYPE_INVALID)) {
2288 log_error("Could not append arguments to message.");
2293 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2294 log_error("Failed to issue method call: %s", error.message);
2300 if (!dbus_message_get_args(reply, &error,
2301 DBUS_TYPE_OBJECT_PATH, &path,
2302 DBUS_TYPE_INVALID)) {
2303 log_error("Failed to parse reply: %s", error.message);
2308 if ((r = show_one(bus, path, show_properties, &new_line)) < 0)
2311 dbus_message_unref(m);
2312 dbus_message_unref(reply);
2320 dbus_message_unref(m);
2323 dbus_message_unref(reply);
2325 dbus_error_free(&error);
2330 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2332 DBusMessage *m = NULL, *reply = NULL;
2337 dbus_error_init(&error);
2339 log_debug("Got D-Bus request: %s.%s() on %s",
2340 dbus_message_get_interface(message),
2341 dbus_message_get_member(message),
2342 dbus_message_get_path(message));
2344 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2345 log_error("Warning! D-Bus connection terminated.");
2346 dbus_connection_close(connection);
2348 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2349 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2350 const char *id, *path;
2352 if (!dbus_message_get_args(message, &error,
2353 DBUS_TYPE_STRING, &id,
2354 DBUS_TYPE_OBJECT_PATH, &path,
2356 log_error("Failed to parse message: %s", error.message);
2357 else if (streq(dbus_message_get_member(message), "UnitNew"))
2358 printf("Unit %s added.\n", id);
2360 printf("Unit %s removed.\n", id);
2362 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2363 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2367 if (!dbus_message_get_args(message, &error,
2368 DBUS_TYPE_UINT32, &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), "JobNew"))
2373 printf("Job %u added.\n", id);
2375 printf("Job %u removed.\n", id);
2378 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Unit", "Changed") ||
2379 dbus_message_is_signal(message, "org.freedesktop.systemd1.Job", "Changed")) {
2381 const char *path, *interface, *property = "Id";
2382 DBusMessageIter iter, sub;
2384 path = dbus_message_get_path(message);
2385 interface = dbus_message_get_interface(message);
2387 if (!(m = dbus_message_new_method_call(
2388 "org.freedesktop.systemd1",
2390 "org.freedesktop.DBus.Properties",
2392 log_error("Could not allocate message.");
2396 if (!dbus_message_append_args(m,
2397 DBUS_TYPE_STRING, &interface,
2398 DBUS_TYPE_STRING, &property,
2399 DBUS_TYPE_INVALID)) {
2400 log_error("Could not append arguments to message.");
2404 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2405 log_error("Failed to issue method call: %s", error.message);
2409 if (!dbus_message_iter_init(reply, &iter) ||
2410 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2411 log_error("Failed to parse reply.");
2415 dbus_message_iter_recurse(&iter, &sub);
2417 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2420 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2421 log_error("Failed to parse reply.");
2425 dbus_message_iter_get_basic(&sub, &id);
2426 printf("Unit %s changed.\n", id);
2430 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2431 log_error("Failed to parse reply.");
2435 dbus_message_iter_get_basic(&sub, &id);
2436 printf("Job %u changed.\n", id);
2442 dbus_message_unref(m);
2445 dbus_message_unref(reply);
2447 dbus_error_free(&error);
2448 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2452 dbus_message_unref(m);
2455 dbus_message_unref(reply);
2457 dbus_error_free(&error);
2458 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2461 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2462 DBusMessage *m = NULL, *reply = NULL;
2466 dbus_error_init(&error);
2469 dbus_bus_add_match(bus,
2471 "sender='org.freedesktop.systemd1',"
2472 "interface='org.freedesktop.systemd1.Manager',"
2473 "path='/org/freedesktop/systemd1'",
2476 if (dbus_error_is_set(&error)) {
2477 log_error("Failed to add match: %s", error.message);
2482 dbus_bus_add_match(bus,
2484 "sender='org.freedesktop.systemd1',"
2485 "interface='org.freedesktop.systemd1.Unit',"
2489 if (dbus_error_is_set(&error)) {
2490 log_error("Failed to add match: %s", error.message);
2495 dbus_bus_add_match(bus,
2497 "sender='org.freedesktop.systemd1',"
2498 "interface='org.freedesktop.systemd1.Job',"
2502 if (dbus_error_is_set(&error)) {
2503 log_error("Failed to add match: %s", error.message);
2509 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2510 log_error("Failed to add filter.");
2515 if (!(m = dbus_message_new_method_call(
2516 "org.freedesktop.systemd1",
2517 "/org/freedesktop/systemd1",
2518 "org.freedesktop.systemd1.Manager",
2520 log_error("Could not allocate message.");
2525 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2526 log_error("Failed to issue method call: %s", error.message);
2531 while (dbus_connection_read_write_dispatch(bus, -1))
2538 /* This is slightly dirty, since we don't undo the filter or the matches. */
2541 dbus_message_unref(m);
2544 dbus_message_unref(reply);
2546 dbus_error_free(&error);
2551 static int dump(DBusConnection *bus, char **args, unsigned n) {
2552 DBusMessage *m = NULL, *reply = NULL;
2557 dbus_error_init(&error);
2559 if (!(m = dbus_message_new_method_call(
2560 "org.freedesktop.systemd1",
2561 "/org/freedesktop/systemd1",
2562 "org.freedesktop.systemd1.Manager",
2564 log_error("Could not allocate message.");
2568 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2569 log_error("Failed to issue method call: %s", error.message);
2574 if (!dbus_message_get_args(reply, &error,
2575 DBUS_TYPE_STRING, &text,
2576 DBUS_TYPE_INVALID)) {
2577 log_error("Failed to parse reply: %s", error.message);
2582 fputs(text, stdout);
2588 dbus_message_unref(m);
2591 dbus_message_unref(reply);
2593 dbus_error_free(&error);
2598 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2599 DBusMessage *m = NULL, *reply = NULL;
2602 const char *name = "", *path, *id;
2603 dbus_bool_t cleanup = FALSE;
2604 DBusMessageIter iter, sub;
2606 *interface = "org.freedesktop.systemd1.Unit",
2609 dbus_error_init(&error);
2611 if (!(m = dbus_message_new_method_call(
2612 "org.freedesktop.systemd1",
2613 "/org/freedesktop/systemd1",
2614 "org.freedesktop.systemd1.Manager",
2615 "CreateSnapshot"))) {
2616 log_error("Could not allocate message.");
2623 if (!dbus_message_append_args(m,
2624 DBUS_TYPE_STRING, &name,
2625 DBUS_TYPE_BOOLEAN, &cleanup,
2626 DBUS_TYPE_INVALID)) {
2627 log_error("Could not append arguments to message.");
2632 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2633 log_error("Failed to issue method call: %s", error.message);
2638 if (!dbus_message_get_args(reply, &error,
2639 DBUS_TYPE_OBJECT_PATH, &path,
2640 DBUS_TYPE_INVALID)) {
2641 log_error("Failed to parse reply: %s", error.message);
2646 dbus_message_unref(m);
2647 if (!(m = dbus_message_new_method_call(
2648 "org.freedesktop.systemd1",
2650 "org.freedesktop.DBus.Properties",
2652 log_error("Could not allocate message.");
2656 if (!dbus_message_append_args(m,
2657 DBUS_TYPE_STRING, &interface,
2658 DBUS_TYPE_STRING, &property,
2659 DBUS_TYPE_INVALID)) {
2660 log_error("Could not append arguments to message.");
2665 dbus_message_unref(reply);
2666 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2667 log_error("Failed to issue method call: %s", error.message);
2672 if (!dbus_message_iter_init(reply, &iter) ||
2673 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2674 log_error("Failed to parse reply.");
2679 dbus_message_iter_recurse(&iter, &sub);
2681 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2682 log_error("Failed to parse reply.");
2687 dbus_message_iter_get_basic(&sub, &id);
2695 dbus_message_unref(m);
2698 dbus_message_unref(reply);
2700 dbus_error_free(&error);
2705 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2706 DBusMessage *m = NULL, *reply = NULL;
2714 dbus_error_init(&error);
2716 for (i = 1; i < n; i++) {
2717 const char *path = NULL;
2719 if (!(m = dbus_message_new_method_call(
2720 "org.freedesktop.systemd1",
2721 "/org/freedesktop/systemd1",
2722 "org.freedesktop.systemd1.Manager",
2724 log_error("Could not allocate message.");
2729 if (!dbus_message_append_args(m,
2730 DBUS_TYPE_STRING, &args[i],
2731 DBUS_TYPE_INVALID)) {
2732 log_error("Could not append arguments to message.");
2737 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2738 log_error("Failed to issue method call: %s", error.message);
2743 if (!dbus_message_get_args(reply, &error,
2744 DBUS_TYPE_OBJECT_PATH, &path,
2745 DBUS_TYPE_INVALID)) {
2746 log_error("Failed to parse reply: %s", error.message);
2751 dbus_message_unref(m);
2752 if (!(m = dbus_message_new_method_call(
2753 "org.freedesktop.systemd1",
2755 "org.freedesktop.systemd1.Snapshot",
2757 log_error("Could not allocate message.");
2762 dbus_message_unref(reply);
2763 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2764 log_error("Failed to issue method call: %s", error.message);
2769 dbus_message_unref(m);
2770 dbus_message_unref(reply);
2778 dbus_message_unref(m);
2781 dbus_message_unref(reply);
2783 dbus_error_free(&error);
2788 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2789 DBusMessage *m = NULL, *reply = NULL;
2794 dbus_error_init(&error);
2796 if (arg_action == ACTION_RELOAD)
2798 else if (arg_action == ACTION_REEXEC)
2799 method = "Reexecute";
2801 assert(arg_action == ACTION_SYSTEMCTL);
2804 streq(args[0], "clear-jobs") ||
2805 streq(args[0], "cancel") ? "ClearJobs" :
2806 streq(args[0], "daemon-reexec") ? "Reexecute" :
2807 streq(args[0], "reset-maintenance") ? "ResetMaintenance" :
2808 streq(args[0], "daemon-exit") ? "Exit" :
2812 if (!(m = dbus_message_new_method_call(
2813 "org.freedesktop.systemd1",
2814 "/org/freedesktop/systemd1",
2815 "org.freedesktop.systemd1.Manager",
2817 log_error("Could not allocate message.");
2821 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2823 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
2824 /* There's always a fallback possible for
2825 * legacy actions. */
2830 log_error("Failed to issue method call: %s", error.message);
2839 dbus_message_unref(m);
2842 dbus_message_unref(reply);
2844 dbus_error_free(&error);
2849 static int reset_maintenance(DBusConnection *bus, char **args, unsigned n) {
2850 DBusMessage *m = NULL, *reply = NULL;
2856 dbus_error_init(&error);
2859 return daemon_reload(bus, args, n);
2861 for (i = 1; i < n; i++) {
2863 if (!(m = dbus_message_new_method_call(
2864 "org.freedesktop.systemd1",
2865 "/org/freedesktop/systemd1",
2866 "org.freedesktop.systemd1.Manager",
2867 "ResetMaintenanceUnit"))) {
2868 log_error("Could not allocate message.");
2873 if (!dbus_message_append_args(m,
2874 DBUS_TYPE_STRING, args + i,
2875 DBUS_TYPE_INVALID)) {
2876 log_error("Could not append arguments to message.");
2881 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2882 log_error("Failed to issue method call: %s", error.message);
2887 dbus_message_unref(m);
2888 dbus_message_unref(reply);
2896 dbus_message_unref(m);
2899 dbus_message_unref(reply);
2901 dbus_error_free(&error);
2906 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
2907 DBusMessage *m = NULL, *reply = NULL;
2909 DBusMessageIter iter, sub, sub2;
2912 *interface = "org.freedesktop.systemd1.Manager",
2913 *property = "Environment";
2915 dbus_error_init(&error);
2917 if (!(m = dbus_message_new_method_call(
2918 "org.freedesktop.systemd1",
2919 "/org/freedesktop/systemd1",
2920 "org.freedesktop.DBus.Properties",
2922 log_error("Could not allocate message.");
2926 if (!dbus_message_append_args(m,
2927 DBUS_TYPE_STRING, &interface,
2928 DBUS_TYPE_STRING, &property,
2929 DBUS_TYPE_INVALID)) {
2930 log_error("Could not append arguments to message.");
2935 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2936 log_error("Failed to issue method call: %s", error.message);
2941 if (!dbus_message_iter_init(reply, &iter) ||
2942 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2943 log_error("Failed to parse reply.");
2948 dbus_message_iter_recurse(&iter, &sub);
2950 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
2951 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
2952 log_error("Failed to parse reply.");
2957 dbus_message_iter_recurse(&sub, &sub2);
2959 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
2962 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
2963 log_error("Failed to parse reply.");
2968 dbus_message_iter_get_basic(&sub2, &text);
2969 printf("%s\n", text);
2971 dbus_message_iter_next(&sub2);
2978 dbus_message_unref(m);
2981 dbus_message_unref(reply);
2983 dbus_error_free(&error);
2988 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
2989 DBusMessage *m = NULL, *reply = NULL;
2993 DBusMessageIter iter, sub;
2996 dbus_error_init(&error);
2998 method = streq(args[0], "set-environment")
3000 : "UnsetEnvironment";
3002 if (!(m = dbus_message_new_method_call(
3003 "org.freedesktop.systemd1",
3004 "/org/freedesktop/systemd1",
3005 "org.freedesktop.systemd1.Manager",
3008 log_error("Could not allocate message.");
3012 dbus_message_iter_init_append(m, &iter);
3014 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3015 log_error("Could not append arguments to message.");
3020 for (i = 1; i < n; i++)
3021 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3022 log_error("Could not append arguments to message.");
3027 if (!dbus_message_iter_close_container(&iter, &sub)) {
3028 log_error("Could not append arguments to message.");
3033 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3034 log_error("Failed to issue method call: %s", error.message);
3043 dbus_message_unref(m);
3046 dbus_message_unref(reply);
3048 dbus_error_free(&error);
3061 static Hashmap *will_install = NULL, *have_installed = NULL;
3062 static Set *remove_symlinks_to = NULL;
3064 static void install_info_free(InstallInfo *i) {
3069 strv_free(i->aliases);
3070 strv_free(i->wanted_by);
3074 static void install_info_hashmap_free(Hashmap *m) {
3077 while ((i = hashmap_steal_first(m)))
3078 install_info_free(i);
3083 static bool unit_name_valid(const char *name) {
3085 /* This is a minimal version of unit_name_valid() from
3091 if (ignore_file(name))
3097 static int install_info_add(const char *name) {
3101 assert(will_install);
3103 if (!unit_name_valid(name))
3106 if (hashmap_get(have_installed, name) ||
3107 hashmap_get(will_install, name))
3110 if (!(i = new0(InstallInfo, 1))) {
3115 if (!(i->name = strdup(name))) {
3120 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3127 install_info_free(i);
3132 static int config_parse_also(
3133 const char *filename,
3135 const char *section,
3149 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3153 if (!(n = strndup(w, l)))
3156 r = install_info_add(n);
3166 static int mark_symlink_for_removal(const char *p) {
3171 assert(path_is_absolute(p));
3173 if (!remove_symlinks_to)
3176 if (!(n = strdup(p)))
3179 path_kill_slashes(n);
3181 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3183 return r == -EEXIST ? 0 : r;
3189 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3198 if (!(d = fdopendir(fd))) {
3199 close_nointr_nofail(fd);
3205 while ((de = readdir(d))) {
3206 bool is_dir = false, is_link = false;
3208 if (ignore_file(de->d_name))
3211 if (de->d_type == DT_LNK)
3213 else if (de->d_type == DT_DIR)
3215 else if (de->d_type == DT_UNKNOWN) {
3218 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3219 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3226 is_link = S_ISLNK(st.st_mode);
3227 is_dir = S_ISDIR(st.st_mode);
3235 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3236 log_error("Failed to open %s/%s: %m", root, de->d_name);
3243 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3244 log_error("Failed to allocate directory string.");
3245 close_nointr_nofail(nfd);
3250 /* This will close nfd, regardless whether it succeeds or not */
3251 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3257 } else if (is_link) {
3261 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3262 log_error("Failed to allocate symlink string.");
3267 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3268 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3276 if ((c = canonicalize_file_name(dest))) {
3277 /* This might fail if the destination
3278 * is already removed */
3284 path_kill_slashes(dest);
3285 if (set_get(remove_symlinks_to, dest)) {
3288 log_info("rm '%s'", p);
3290 if (unlink(p) < 0) {
3291 log_error("Cannot unlink symlink %s: %m", p);
3296 rmdir_parents(p, config_path);
3297 path_kill_slashes(p);
3299 if (!set_get(remove_symlinks_to, p)) {
3301 if ((r = mark_symlink_for_removal(p)) < 0) {
3320 static int remove_marked_symlinks(const char *config_path) {
3324 assert(config_path);
3326 if (set_size(remove_symlinks_to) <= 0)
3329 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3336 if ((cfd = dup(fd)) < 0) {
3341 /* This takes possession of cfd and closes it */
3342 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3348 close_nointr_nofail(fd);
3353 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3360 if (streq(verb, "enable")) {
3363 mkdir_parents(new_path, 0755);
3365 if (symlink(old_path, new_path) >= 0) {
3368 log_info("ln -s '%s' '%s'", old_path, new_path);
3373 if (errno != EEXIST) {
3374 log_error("Cannot link %s to %s: %m", old_path, new_path);
3378 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3380 if (errno == EINVAL) {
3381 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3385 log_error("readlink() failed: %s", strerror(-r));
3389 if (streq(dest, old_path)) {
3395 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3404 log_info("ln -s '%s' '%s'", old_path, new_path);
3406 if (symlink(old_path, new_path) >= 0)
3409 log_error("Cannot link %s to %s: %m", old_path, new_path);
3412 } else if (streq(verb, "disable")) {
3415 if ((r = mark_symlink_for_removal(old_path)) < 0)
3418 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3419 if (errno == ENOENT)
3422 if (errno == EINVAL) {
3423 log_warning("File %s not a symlink, ignoring.", old_path);
3427 log_error("readlink() failed: %s", strerror(-r));
3431 if (!streq(dest, old_path)) {
3432 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3439 if ((r = mark_symlink_for_removal(new_path)) < 0)
3443 log_info("rm '%s'", new_path);
3445 if (unlink(new_path) >= 0)
3448 log_error("Cannot unlink %s: %m", new_path);
3451 } else if (streq(verb, "is-enabled")) {
3454 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3456 if (errno == ENOENT || errno == EINVAL)
3459 log_error("readlink() failed: %s", strerror(-r));
3463 if (streq(dest, old_path)) {
3471 assert_not_reached("Unknown action.");
3474 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3476 char *alias_path = NULL;
3481 assert(config_path);
3483 STRV_FOREACH(s, i->aliases) {
3485 if (!unit_name_valid(*s)) {
3486 log_error("Invalid name %s.", *s);
3492 if (!(alias_path = path_make_absolute(*s, config_path))) {
3493 log_error("Out of memory");
3498 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3501 if (streq(verb, "disable"))
3502 rmdir_parents(alias_path, config_path);
3513 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3515 char *alias_path = NULL;
3520 assert(config_path);
3522 STRV_FOREACH(s, i->wanted_by) {
3523 if (!unit_name_valid(*s)) {
3524 log_error("Invalid name %s.", *s);
3532 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3533 log_error("Out of memory");
3538 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3541 if (streq(verb, "disable"))
3542 rmdir_parents(alias_path, config_path);
3553 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3555 const ConfigItem items[] = {
3556 { "Alias", config_parse_strv, &i->aliases, "Install" },
3557 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3558 { "Also", config_parse_also, NULL, "Install" },
3560 { NULL, NULL, NULL, NULL }
3564 char *filename = NULL;
3571 STRV_FOREACH(p, paths->unit_path) {
3574 if (!(filename = path_make_absolute(i->name, *p))) {
3575 log_error("Out of memory");
3579 /* Ensure that we don't follow symlinks */
3580 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3581 if ((f = fdopen(fd, "re")))
3584 if (errno == ELOOP) {
3585 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3590 if (errno != ENOENT) {
3591 log_error("Failed to open %s: %m", filename);
3601 log_error("Couldn't find %s.", i->name);
3607 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3614 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3617 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3620 if ((r = mark_symlink_for_removal(filename)) < 0)
3623 if ((r = remove_marked_symlinks(config_path)) < 0)
3629 static char *get_config_path(void) {
3631 if (arg_session && arg_global)
3632 return strdup(SESSION_CONFIG_UNIT_PATH);
3637 if (session_config_home(&p) < 0)
3643 return strdup(SYSTEM_CONFIG_UNIT_PATH);
3646 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3650 char *config_path = NULL;
3653 const char *verb = args[0];
3655 dbus_error_init(&error);
3658 if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3659 log_error("Failed to determine lookup paths: %s", strerror(-r));
3663 if (!(config_path = get_config_path())) {
3664 log_error("Failed to determine config path");
3669 will_install = hashmap_new(string_hash_func, string_compare_func);
3670 have_installed = hashmap_new(string_hash_func, string_compare_func);
3672 if (!will_install || !have_installed) {
3673 log_error("Failed to allocate unit sets.");
3678 if (!arg_defaults && streq(verb, "disable"))
3679 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3680 log_error("Failed to allocate symlink sets.");
3685 for (j = 1; j < n; j++)
3686 if ((r = install_info_add(args[j])) < 0)
3689 while ((i = hashmap_first(will_install))) {
3692 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3694 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3702 /* In test mode and found something */
3708 if (streq(verb, "is-enabled"))
3709 r = r > 0 ? 0 : -ENOENT;
3711 /* Don't try to reload anything if the user asked us to not do this */
3713 /* Don't try to reload anything when updating a unit globally */
3715 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3716 (arg_session || sd_booted() > 0) &&
3717 /* Don't try to reload anything if we are running in a chroot environment */
3718 (arg_session || running_in_chroot() <= 0) ) {
3721 if ((q = daemon_reload(bus, args, n)) < 0)
3726 install_info_hashmap_free(will_install);
3727 install_info_hashmap_free(have_installed);
3729 set_free_free(remove_symlinks_to);
3731 lookup_paths_free(&paths);
3738 static int systemctl_help(void) {
3740 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3741 "Send control commands to or query the systemd manager.\n\n"
3742 " -h --help Show this help\n"
3743 " -t --type=TYPE List only units of a particular type\n"
3744 " -p --property=NAME Show only properties by this name\n"
3745 " -a --all Show all units/properties, including dead/empty ones\n"
3746 " --full Don't ellipsize unit names on output\n"
3747 " --fail When queueing a new job, fail if conflicting jobs are\n"
3749 " -q --quiet Suppress output\n"
3750 " --no-block Do not wait until operation finished\n"
3751 " --system Connect to system bus\n"
3752 " --session Connect to session bus\n"
3753 " --order When generating graph for dot, show only order\n"
3754 " --require When generating graph for dot, show only requirement\n"
3755 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3756 " --global Enable/disable unit files globally\n"
3757 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3759 " --force When enabling unit files, override existing symlinks\n"
3760 " --defaults When disabling unit files, remove default symlinks only\n\n"
3762 " list-units List units\n"
3763 " start [NAME...] Start (activate) one or more units\n"
3764 " stop [NAME...] Stop (deactivate) one or more units\n"
3765 " reload [NAME...] Reload one or more units\n"
3766 " restart [NAME...] Start or restart one or more units\n"
3767 " try-restart [NAME...] Restart one or more units if active\n"
3768 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3769 " otherwise start or restart\n"
3770 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3771 " otherwise restart if active\n"
3772 " isolate [NAME] Start one unit and stop all others\n"
3773 " is-active [NAME...] Check whether units are active\n"
3774 " status [NAME...|PID...] Show runtime status of one or more units\n"
3775 " show [NAME...|JOB...] Show properties of one or more\n"
3776 " units/jobs or the manager\n"
3777 " reset-maintenance [NAME...] Reset maintenance state for all, one,\n"
3779 " enable [NAME...] Enable one or more unit files\n"
3780 " disable [NAME...] Disable one or more unit files\n"
3781 " is-enabled [NAME...] Check whether unit files are enabled\n"
3782 " load [NAME...] Load one or more units\n"
3783 " list-jobs List jobs\n"
3784 " cancel [JOB...] Cancel all, one, or more jobs\n"
3785 " monitor Monitor unit/job changes\n"
3786 " dump Dump server status\n"
3787 " dot Dump dependency graph for dot(1)\n"
3788 " snapshot [NAME] Create a snapshot\n"
3789 " delete [NAME...] Remove one or more snapshots\n"
3790 " daemon-reload Reload systemd manager configuration\n"
3791 " daemon-reexec Reexecute systemd manager\n"
3792 " daemon-exit Ask the systemd manager to quit\n"
3793 " show-environment Dump environment\n"
3794 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3795 " unset-environment [NAME...] Unset one or more environment variables\n"
3796 " halt Shut down and halt the system\n"
3797 " poweroff Shut down and power-off the system\n"
3798 " reboot Shut down and reboot the system\n"
3799 " rescue Enter system rescue mode\n"
3800 " emergency Enter system emergency mode\n"
3801 " default Enter system default mode\n",
3802 program_invocation_short_name);
3807 static int halt_help(void) {
3809 printf("%s [OPTIONS...]\n\n"
3810 "%s the system.\n\n"
3811 " --help Show this help\n"
3812 " --halt Halt the machine\n"
3813 " -p --poweroff Switch off the machine\n"
3814 " --reboot Reboot the machine\n"
3815 " -f --force Force immediate halt/power-off/reboot\n"
3816 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3817 " -d --no-wtmp Don't write wtmp record\n"
3818 " -n --no-sync Don't sync before halt/power-off/reboot\n"
3819 " --no-wall Don't send wall message before halt/power-off/reboot\n",
3820 program_invocation_short_name,
3821 arg_action == ACTION_REBOOT ? "Reboot" :
3822 arg_action == ACTION_POWEROFF ? "Power off" :
3828 static int shutdown_help(void) {
3830 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3831 "Shut down the system.\n\n"
3832 " --help Show this help\n"
3833 " -H --halt Halt the machine\n"
3834 " -P --poweroff Power-off the machine\n"
3835 " -r --reboot Reboot the machine\n"
3836 " -h Equivalent to --poweroff, overriden by --halt\n"
3837 " -k Don't halt/power-off/reboot, just send warnings\n"
3838 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3839 " -c Cancel a pending shutdown\n",
3840 program_invocation_short_name);
3845 static int telinit_help(void) {
3847 printf("%s [OPTIONS...] {COMMAND}\n\n"
3848 "Send control commands to the init daemon.\n\n"
3849 " --help Show this help\n"
3850 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
3852 " 0 Power-off the machine\n"
3853 " 6 Reboot the machine\n"
3854 " 2, 3, 4, 5 Start runlevelX.target unit\n"
3855 " 1, s, S Enter rescue mode\n"
3856 " q, Q Reload init daemon configuration\n"
3857 " u, U Reexecute init daemon\n",
3858 program_invocation_short_name);
3863 static int runlevel_help(void) {
3865 printf("%s [OPTIONS...]\n\n"
3866 "Prints the previous and current runlevel of the init system.\n\n"
3867 " --help Show this help\n",
3868 program_invocation_short_name);
3873 static int systemctl_parse_argv(int argc, char *argv[]) {
3890 static const struct option options[] = {
3891 { "help", no_argument, NULL, 'h' },
3892 { "type", required_argument, NULL, 't' },
3893 { "property", required_argument, NULL, 'p' },
3894 { "all", no_argument, NULL, 'a' },
3895 { "full", no_argument, NULL, ARG_FULL },
3896 { "fail", no_argument, NULL, ARG_FAIL },
3897 { "session", no_argument, NULL, ARG_SESSION },
3898 { "system", no_argument, NULL, ARG_SYSTEM },
3899 { "global", no_argument, NULL, ARG_GLOBAL },
3900 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
3901 { "no-wall", no_argument, NULL, ARG_NO_WALL },
3902 { "quiet", no_argument, NULL, 'q' },
3903 { "order", no_argument, NULL, ARG_ORDER },
3904 { "require", no_argument, NULL, ARG_REQUIRE },
3905 { "force", no_argument, NULL, ARG_FORCE },
3906 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
3907 { "defaults", no_argument, NULL, ARG_DEFAULTS },
3908 { NULL, 0, NULL, 0 }
3916 while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
3931 if (!(l = strv_append(arg_property, optarg)))
3934 strv_free(arg_property);
3937 /* If the user asked for a particular
3938 * property, show it to him, even if it is
3957 arg_session = false;
3961 arg_no_block = true;
3969 arg_dot = DOT_ORDER;
3973 arg_dot = DOT_REQUIRE;
3989 arg_no_reload = true;
3998 arg_defaults = true;
4005 log_error("Unknown option code %c", c);
4013 static int halt_parse_argv(int argc, char *argv[]) {
4022 static const struct option options[] = {
4023 { "help", no_argument, NULL, ARG_HELP },
4024 { "halt", no_argument, NULL, ARG_HALT },
4025 { "poweroff", no_argument, NULL, 'p' },
4026 { "reboot", no_argument, NULL, ARG_REBOOT },
4027 { "force", no_argument, NULL, 'f' },
4028 { "wtmp-only", no_argument, NULL, 'w' },
4029 { "no-wtmp", no_argument, NULL, 'd' },
4030 { "no-sync", no_argument, NULL, 'n' },
4031 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4032 { NULL, 0, NULL, 0 }
4040 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4041 if (runlevel == '0' || runlevel == '6')
4042 arg_immediate = true;
4044 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4052 arg_action = ACTION_HALT;
4056 if (arg_action != ACTION_REBOOT)
4057 arg_action = ACTION_POWEROFF;
4061 arg_action = ACTION_REBOOT;
4065 arg_immediate = true;
4086 /* Compatibility nops */
4093 log_error("Unknown option code %c", c);
4098 if (optind < argc) {
4099 log_error("Too many arguments.");
4106 static int parse_time_spec(const char *t, usec_t *_u) {
4110 if (streq(t, "now"))
4112 else if (t[0] == '+') {
4115 if (safe_atou64(t + 1, &u) < 0)
4118 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4127 hour = strtol(t, &e, 10);
4128 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4131 minute = strtol(e+1, &e, 10);
4132 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4135 n = now(CLOCK_REALTIME);
4136 s = (time_t) (n / USEC_PER_SEC);
4139 assert_se(localtime_r(&s, &tm));
4141 tm.tm_hour = (int) hour;
4142 tm.tm_min = (int) minute;
4145 assert_se(s = mktime(&tm));
4147 *_u = (usec_t) s * USEC_PER_SEC;
4150 *_u += USEC_PER_DAY;
4156 static int shutdown_parse_argv(int argc, char *argv[]) {
4163 static const struct option options[] = {
4164 { "help", no_argument, NULL, ARG_HELP },
4165 { "halt", no_argument, NULL, 'H' },
4166 { "poweroff", no_argument, NULL, 'P' },
4167 { "reboot", no_argument, NULL, 'r' },
4168 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4169 { NULL, 0, NULL, 0 }
4177 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4185 arg_action = ACTION_HALT;
4189 arg_action = ACTION_POWEROFF;
4193 arg_action = ACTION_REBOOT;
4197 if (arg_action != ACTION_HALT)
4198 arg_action = ACTION_POWEROFF;
4211 /* Compatibility nops */
4215 arg_action = ACTION_CANCEL_SHUTDOWN;
4222 log_error("Unknown option code %c", c);
4227 if (argc > optind) {
4228 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4229 log_error("Failed to parse time specification: %s", argv[optind]);
4233 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4235 /* We skip the time argument */
4236 if (argc > optind + 1)
4237 arg_wall = argv + optind + 1;
4244 static int telinit_parse_argv(int argc, char *argv[]) {
4251 static const struct option options[] = {
4252 { "help", no_argument, NULL, ARG_HELP },
4253 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4254 { NULL, 0, NULL, 0 }
4257 static const struct {
4261 { '0', ACTION_POWEROFF },
4262 { '6', ACTION_REBOOT },
4263 { '1', ACTION_RESCUE },
4264 { '2', ACTION_RUNLEVEL2 },
4265 { '3', ACTION_RUNLEVEL3 },
4266 { '4', ACTION_RUNLEVEL4 },
4267 { '5', ACTION_RUNLEVEL5 },
4268 { 's', ACTION_RESCUE },
4269 { 'S', ACTION_RESCUE },
4270 { 'q', ACTION_RELOAD },
4271 { 'Q', ACTION_RELOAD },
4272 { 'u', ACTION_REEXEC },
4273 { 'U', ACTION_REEXEC }
4282 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4297 log_error("Unknown option code %c", c);
4302 if (optind >= argc) {
4307 if (optind + 1 < argc) {
4308 log_error("Too many arguments.");
4312 if (strlen(argv[optind]) != 1) {
4313 log_error("Expected single character argument.");
4317 for (i = 0; i < ELEMENTSOF(table); i++)
4318 if (table[i].from == argv[optind][0])
4321 if (i >= ELEMENTSOF(table)) {
4322 log_error("Unknown command %s.", argv[optind]);
4326 arg_action = table[i].to;
4333 static int runlevel_parse_argv(int argc, char *argv[]) {
4339 static const struct option options[] = {
4340 { "help", no_argument, NULL, ARG_HELP },
4341 { NULL, 0, NULL, 0 }
4349 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4360 log_error("Unknown option code %c", c);
4365 if (optind < argc) {
4366 log_error("Too many arguments.");
4373 static int parse_argv(int argc, char *argv[]) {
4377 if (program_invocation_short_name) {
4379 if (strstr(program_invocation_short_name, "halt")) {
4380 arg_action = ACTION_HALT;
4381 return halt_parse_argv(argc, argv);
4382 } else if (strstr(program_invocation_short_name, "poweroff")) {
4383 arg_action = ACTION_POWEROFF;
4384 return halt_parse_argv(argc, argv);
4385 } else if (strstr(program_invocation_short_name, "reboot")) {
4386 arg_action = ACTION_REBOOT;
4387 return halt_parse_argv(argc, argv);
4388 } else if (strstr(program_invocation_short_name, "shutdown")) {
4389 arg_action = ACTION_POWEROFF;
4390 return shutdown_parse_argv(argc, argv);
4391 } else if (strstr(program_invocation_short_name, "init")) {
4393 if (sd_booted() > 0) {
4394 arg_action = ACTION_INVALID;
4395 return telinit_parse_argv(argc, argv);
4397 /* Hmm, so some other init system is
4398 * running, we need to forward this
4399 * request to it. For now we simply
4400 * guess that it is Upstart. */
4402 execv("/lib/upstart/telinit", argv);
4404 log_error("Couldn't find an alternative telinit implementation to spawn.");
4408 } else if (strstr(program_invocation_short_name, "runlevel")) {
4409 arg_action = ACTION_RUNLEVEL;
4410 return runlevel_parse_argv(argc, argv);
4414 arg_action = ACTION_SYSTEMCTL;
4415 return systemctl_parse_argv(argc, argv);
4418 static int action_to_runlevel(void) {
4420 static const char table[_ACTION_MAX] = {
4421 [ACTION_HALT] = '0',
4422 [ACTION_POWEROFF] = '0',
4423 [ACTION_REBOOT] = '6',
4424 [ACTION_RUNLEVEL2] = '2',
4425 [ACTION_RUNLEVEL3] = '3',
4426 [ACTION_RUNLEVEL4] = '4',
4427 [ACTION_RUNLEVEL5] = '5',
4428 [ACTION_RESCUE] = '1'
4431 assert(arg_action < _ACTION_MAX);
4433 return table[arg_action];
4436 static int talk_upstart(void) {
4437 DBusMessage *m = NULL, *reply = NULL;
4439 int previous, rl, r;
4441 env1_buf[] = "RUNLEVEL=X",
4442 env2_buf[] = "PREVLEVEL=X";
4443 char *env1 = env1_buf, *env2 = env2_buf;
4444 const char *emit = "runlevel";
4445 dbus_bool_t b_false = FALSE;
4446 DBusMessageIter iter, sub;
4447 DBusConnection *bus;
4449 dbus_error_init(&error);
4451 if (!(rl = action_to_runlevel()))
4454 if (utmp_get_runlevel(&previous, NULL) < 0)
4457 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4458 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4463 log_error("Failed to connect to Upstart bus: %s", error.message);
4468 if ((r = bus_check_peercred(bus)) < 0) {
4469 log_error("Failed to verify owner of bus.");
4473 if (!(m = dbus_message_new_method_call(
4474 "com.ubuntu.Upstart",
4475 "/com/ubuntu/Upstart",
4476 "com.ubuntu.Upstart0_6",
4479 log_error("Could not allocate message.");
4484 dbus_message_iter_init_append(m, &iter);
4486 env1_buf[sizeof(env1_buf)-2] = rl;
4487 env2_buf[sizeof(env2_buf)-2] = previous;
4489 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4490 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4491 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4492 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4493 !dbus_message_iter_close_container(&iter, &sub) ||
4494 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4495 log_error("Could not append arguments to message.");
4500 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4502 if (error_is_no_service(&error)) {
4507 log_error("Failed to issue method call: %s", error.message);
4516 dbus_message_unref(m);
4519 dbus_message_unref(reply);
4522 dbus_connection_close(bus);
4523 dbus_connection_unref(bus);
4526 dbus_error_free(&error);
4531 static int talk_initctl(void) {
4532 struct init_request request;
4536 if (!(rl = action_to_runlevel()))
4540 request.magic = INIT_MAGIC;
4541 request.sleeptime = 0;
4542 request.cmd = INIT_CMD_RUNLVL;
4543 request.runlevel = rl;
4545 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4547 if (errno == ENOENT)
4550 log_error("Failed to open "INIT_FIFO": %m");
4555 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4556 close_nointr_nofail(fd);
4559 log_error("Failed to write to "INIT_FIFO": %m");
4560 return errno ? -errno : -EIO;
4566 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4568 static const struct {
4576 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4578 { "list-units", LESS, 1, list_units },
4579 { "list-jobs", EQUAL, 1, list_jobs },
4580 { "clear-jobs", EQUAL, 1, daemon_reload },
4581 { "load", MORE, 2, load_unit },
4582 { "cancel", MORE, 2, cancel_job },
4583 { "start", MORE, 2, start_unit },
4584 { "stop", MORE, 2, start_unit },
4585 { "reload", MORE, 2, start_unit },
4586 { "restart", MORE, 2, start_unit },
4587 { "try-restart", MORE, 2, start_unit },
4588 { "reload-or-restart", MORE, 2, start_unit },
4589 { "reload-or-try-restart", MORE, 2, start_unit },
4590 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4591 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4592 { "isolate", EQUAL, 2, start_unit },
4593 { "is-active", MORE, 2, check_unit },
4594 { "check", MORE, 2, check_unit },
4595 { "show", MORE, 1, show },
4596 { "status", MORE, 2, show },
4597 { "monitor", EQUAL, 1, monitor },
4598 { "dump", EQUAL, 1, dump },
4599 { "dot", EQUAL, 1, dot },
4600 { "snapshot", LESS, 2, snapshot },
4601 { "delete", MORE, 2, delete_snapshot },
4602 { "daemon-reload", EQUAL, 1, daemon_reload },
4603 { "daemon-reexec", EQUAL, 1, daemon_reload },
4604 { "daemon-exit", EQUAL, 1, daemon_reload },
4605 { "show-environment", EQUAL, 1, show_enviroment },
4606 { "set-environment", MORE, 2, set_environment },
4607 { "unset-environment", MORE, 2, set_environment },
4608 { "halt", EQUAL, 1, start_special },
4609 { "poweroff", EQUAL, 1, start_special },
4610 { "reboot", EQUAL, 1, start_special },
4611 { "default", EQUAL, 1, start_special },
4612 { "rescue", EQUAL, 1, start_special },
4613 { "emergency", EQUAL, 1, start_special },
4614 { "reset-maintenance", MORE, 1, reset_maintenance },
4615 { "enable", MORE, 2, enable_unit },
4616 { "disable", MORE, 2, enable_unit },
4617 { "is-enabled", MORE, 2, enable_unit }
4627 left = argc - optind;
4630 /* Special rule: no arguments means "list-units" */
4633 if (streq(argv[optind], "help")) {
4638 for (i = 0; i < ELEMENTSOF(verbs); i++)
4639 if (streq(argv[optind], verbs[i].verb))
4642 if (i >= ELEMENTSOF(verbs)) {
4643 log_error("Unknown operation %s", argv[optind]);
4648 switch (verbs[i].argc_cmp) {
4651 if (left != verbs[i].argc) {
4652 log_error("Invalid number of arguments.");
4659 if (left < verbs[i].argc) {
4660 log_error("Too few arguments.");
4667 if (left > verbs[i].argc) {
4668 log_error("Too many arguments.");
4675 assert_not_reached("Unknown comparison operator.");
4678 /* Require a bus connection for all operations but
4680 if (!streq(verbs[i].verb, "enable") &&
4681 !streq(verbs[i].verb, "disable") &&
4683 log_error("Failed to get D-Bus connection: %s", error->message);
4687 return verbs[i].dispatch(bus, argv + optind, left);
4690 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
4692 struct msghdr msghdr;
4694 union sockaddr_union sockaddr;
4695 struct ucred *ucred;
4697 struct cmsghdr cmsghdr;
4698 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
4700 struct shutdownd_command c;
4708 strncpy(c.wall_message, message, sizeof(c.wall_message));
4710 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4714 sockaddr.sa.sa_family = AF_UNIX;
4715 sockaddr.un.sun_path[0] = 0;
4716 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
4719 iovec.iov_base = (char*) &c;
4720 iovec.iov_len = sizeof(c);
4723 control.cmsghdr.cmsg_level = SOL_SOCKET;
4724 control.cmsghdr.cmsg_type = SCM_CREDENTIALS;
4725 control.cmsghdr.cmsg_len = CMSG_LEN(sizeof(struct ucred));
4727 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
4728 ucred->pid = getpid();
4729 ucred->uid = getuid();
4730 ucred->gid = getgid();
4733 msghdr.msg_name = &sockaddr;
4734 msghdr.msg_namelen = sizeof(sa_family_t) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
4736 msghdr.msg_iov = &iovec;
4737 msghdr.msg_iovlen = 1;
4738 msghdr.msg_control = &control;
4739 msghdr.msg_controllen = control.cmsghdr.cmsg_len;
4741 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
4742 close_nointr_nofail(fd);
4746 close_nointr_nofail(fd);
4750 static int reload_with_fallback(DBusConnection *bus) {
4753 /* First, try systemd via D-Bus. */
4754 if (daemon_reload(bus, NULL, 0) > 0)
4758 /* Nothing else worked, so let's try signals */
4759 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
4761 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
4762 log_error("kill() failed: %m");
4769 static int start_with_fallback(DBusConnection *bus) {
4772 /* First, try systemd via D-Bus. */
4773 if (start_unit(bus, NULL, 0) > 0)
4777 /* Hmm, talking to systemd via D-Bus didn't work. Then
4778 * let's try to talk to Upstart via D-Bus. */
4779 if (talk_upstart() > 0)
4782 /* Nothing else worked, so let's try
4784 if (talk_initctl() > 0)
4787 log_error("Failed to talk to init daemon.");
4791 warn_wall(arg_action);
4795 static int halt_main(DBusConnection *bus) {
4798 if (geteuid() != 0) {
4799 log_error("Must to be root.");
4805 char date[FORMAT_TIMESTAMP_MAX];
4807 m = strv_join(arg_wall, " ");
4808 r = send_shutdownd(arg_when,
4809 arg_action == ACTION_HALT ? 'H' :
4810 arg_action == ACTION_POWEROFF ? 'P' :
4817 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
4819 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
4820 format_timestamp(date, sizeof(date), arg_when));
4825 if (!arg_dry && !arg_immediate)
4826 return start_with_fallback(bus);
4829 if (sd_booted() > 0)
4830 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
4831 else if ((r = utmp_put_shutdown(0)) < 0)
4832 log_warning("Failed to write utmp record: %s", strerror(-r));
4841 /* Make sure C-A-D is handled by the kernel from this
4843 reboot(RB_ENABLE_CAD);
4845 switch (arg_action) {
4848 log_info("Halting.");
4849 reboot(RB_HALT_SYSTEM);
4852 case ACTION_POWEROFF:
4853 log_info("Powering off.");
4854 reboot(RB_POWER_OFF);
4858 log_info("Rebooting.");
4859 reboot(RB_AUTOBOOT);
4863 assert_not_reached("Unknown halt action.");
4866 /* We should never reach this. */
4870 static int runlevel_main(void) {
4871 int r, runlevel, previous;
4873 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
4874 printf("unknown\n");
4879 previous <= 0 ? 'N' : previous,
4880 runlevel <= 0 ? 'N' : runlevel);
4885 int main(int argc, char*argv[]) {
4887 DBusConnection *bus = NULL;
4890 dbus_error_init(&error);
4892 log_parse_environment();
4895 if ((r = parse_argv(argc, argv)) < 0)
4902 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
4903 * let's shortcut this */
4904 if (arg_action == ACTION_RUNLEVEL) {
4905 retval = runlevel_main() < 0;
4909 bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
4911 switch (arg_action) {
4913 case ACTION_SYSTEMCTL: {
4914 retval = systemctl_main(bus, argc, argv, &error) < 0;
4919 case ACTION_POWEROFF:
4921 retval = halt_main(bus) < 0;
4924 case ACTION_RUNLEVEL2:
4925 case ACTION_RUNLEVEL3:
4926 case ACTION_RUNLEVEL4:
4927 case ACTION_RUNLEVEL5:
4929 case ACTION_EMERGENCY:
4930 case ACTION_DEFAULT:
4931 retval = start_with_fallback(bus) < 0;
4936 retval = reload_with_fallback(bus) < 0;
4939 case ACTION_CANCEL_SHUTDOWN:
4940 retval = send_shutdownd(0, 0, false, NULL) < 0;
4943 case ACTION_INVALID:
4944 case ACTION_RUNLEVEL:
4946 assert_not_reached("Unknown action");
4952 dbus_connection_close(bus);
4953 dbus_connection_unref(bus);
4956 dbus_error_free(&error);
4960 strv_free(arg_property);