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;
73 static bool arg_skip_fsck = false;
74 static bool arg_force_fsck = false;
91 ACTION_CANCEL_SHUTDOWN,
93 } arg_action = ACTION_SYSTEMCTL;
100 static bool private_bus = false;
102 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
104 static bool on_tty(void) {
107 if (_unlikely_(t < 0))
108 t = isatty(STDOUT_FILENO) > 0;
113 static const char *ansi_highlight(bool b) {
118 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
121 static const char *ansi_highlight_green(bool b) {
126 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
129 static bool error_is_no_service(DBusError *error) {
133 if (!dbus_error_is_set(error))
136 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
139 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
142 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
145 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
150 if (dbus_message_iter_get_arg_type(iter) != type)
153 dbus_message_iter_get_basic(iter, data);
155 if (!dbus_message_iter_next(iter) != !next)
161 static void warn_wall(enum action action) {
162 static const char *table[_ACTION_MAX] = {
163 [ACTION_HALT] = "The system is going down for system halt NOW!",
164 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
165 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
166 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
167 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
176 if (!(p = strv_join(arg_wall, " "))) {
177 log_error("Failed to join strings.");
193 utmp_wall(table[action]);
198 const char *description;
199 const char *load_state;
200 const char *active_state;
201 const char *sub_state;
202 const char *following;
203 const char *unit_path;
205 const char *job_type;
206 const char *job_path;
209 static int compare_unit_info(const void *a, const void *b) {
211 const struct unit_info *u = a, *v = b;
213 d1 = strrchr(u->id, '.');
214 d2 = strrchr(v->id, '.');
219 if ((r = strcasecmp(d1, d2)) != 0)
223 return strcasecmp(u->id, v->id);
226 static int list_units(DBusConnection *bus, char **args, unsigned n) {
227 DBusMessage *m = NULL, *reply = NULL;
230 DBusMessageIter iter, sub, sub2;
231 unsigned c = 0, k, n_units = 0;
232 struct unit_info *unit_infos = NULL;
234 dbus_error_init(&error);
238 if (!(m = dbus_message_new_method_call(
239 "org.freedesktop.systemd1",
240 "/org/freedesktop/systemd1",
241 "org.freedesktop.systemd1.Manager",
243 log_error("Could not allocate message.");
247 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
248 log_error("Failed to issue method call: %s", error.message);
253 if (!dbus_message_iter_init(reply, &iter) ||
254 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
255 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
256 log_error("Failed to parse reply.");
261 dbus_message_iter_recurse(&iter, &sub);
263 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
266 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
267 log_error("Failed to parse reply.");
275 n_units = MAX(2*c, 16);
276 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
279 log_error("Failed to allocate unit array.");
289 dbus_message_iter_recurse(&sub, &sub2);
291 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
292 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
293 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
294 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
295 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
296 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
297 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
298 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
299 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
300 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
301 log_error("Failed to parse reply.");
306 dbus_message_iter_next(&sub);
310 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
312 if (isatty(STDOUT_FILENO))
313 printf("%-45s %-6s %-12s %-12s %-15s %s\n", "UNIT", "LOAD", "ACTIVE", "SUB", "JOB", "DESCRIPTION");
315 for (k = 0; k < c; k++) {
317 struct unit_info *u = unit_infos+k;
319 if ((!arg_type || ((dot = strrchr(u->id, '.')) &&
320 streq(dot+1, arg_type))) &&
321 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0)) {
324 const char *on, *off;
326 if (streq(u->active_state, "maintenance")) {
327 on = ansi_highlight(true);
328 off = ansi_highlight(false);
332 e = arg_full ? NULL : ellipsize(u->id, 45, 33);
333 printf("%-45s %-6s %s%-12s %-12s%s%n", e ? e : u->id, u->load_state, on, u->active_state, u->sub_state, off, &a);
336 a -= strlen(on) + strlen(off);
339 printf(" => %-12s%n", u->job_type, &b);
343 if (a + b + 2 < columns()) {
347 printf(" %.*s", columns() - a - b - 2, u->description);
354 if (isatty(STDOUT_FILENO)) {
356 printf("\nLOAD = Load State, reflects whether the unit configuration was properly loaded.\n"
357 "ACTIVE = Active State, the high-level unit activation state, i.e. generalization of the substate.\n"
358 "SUB = Substate, the low-level unit activation state, possible values depend on unit type.\n"
359 "JOB = Job, shows pending jobs for the unit.\n");
362 printf("\n%u units listed.\n", c);
364 printf("\n%u units listed. Pass --all to see inactive units, too.\n", c);
371 dbus_message_unref(m);
374 dbus_message_unref(reply);
378 dbus_error_free(&error);
383 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
384 static const char * const colors[] = {
385 "Requires", "[color=\"black\"]",
386 "RequiresOverridable", "[color=\"black\"]",
387 "Requisite", "[color=\"darkblue\"]",
388 "RequisiteOverridable", "[color=\"darkblue\"]",
389 "Wants", "[color=\"darkgrey\"]",
390 "Conflicts", "[color=\"red\"]",
391 "ConflictedBy", "[color=\"red\"]",
392 "After", "[color=\"green\"]"
395 const char *c = NULL;
402 for (i = 0; i < ELEMENTSOF(colors); i += 2)
403 if (streq(colors[i], prop)) {
411 if (arg_dot != DOT_ALL)
412 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
415 switch (dbus_message_iter_get_arg_type(iter)) {
417 case DBUS_TYPE_ARRAY:
419 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
422 dbus_message_iter_recurse(iter, &sub);
424 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
427 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
428 dbus_message_iter_get_basic(&sub, &s);
429 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
431 dbus_message_iter_next(&sub);
441 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
442 DBusMessage *m = NULL, *reply = NULL;
443 const char *interface = "org.freedesktop.systemd1.Unit";
446 DBusMessageIter iter, sub, sub2, sub3;
451 dbus_error_init(&error);
453 if (!(m = dbus_message_new_method_call(
454 "org.freedesktop.systemd1",
456 "org.freedesktop.DBus.Properties",
458 log_error("Could not allocate message.");
463 if (!dbus_message_append_args(m,
464 DBUS_TYPE_STRING, &interface,
465 DBUS_TYPE_INVALID)) {
466 log_error("Could not append arguments to message.");
471 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
472 log_error("Failed to issue method call: %s", error.message);
477 if (!dbus_message_iter_init(reply, &iter) ||
478 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
479 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
480 log_error("Failed to parse reply.");
485 dbus_message_iter_recurse(&iter, &sub);
487 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
490 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
491 log_error("Failed to parse reply.");
496 dbus_message_iter_recurse(&sub, &sub2);
498 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
499 log_error("Failed to parse reply.");
504 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
505 log_error("Failed to parse reply.");
510 dbus_message_iter_recurse(&sub2, &sub3);
512 if (dot_one_property(name, prop, &sub3)) {
513 log_error("Failed to parse reply.");
518 dbus_message_iter_next(&sub);
525 dbus_message_unref(m);
528 dbus_message_unref(reply);
530 dbus_error_free(&error);
535 static int dot(DBusConnection *bus, char **args, unsigned n) {
536 DBusMessage *m = NULL, *reply = NULL;
539 DBusMessageIter iter, sub, sub2;
541 dbus_error_init(&error);
545 if (!(m = dbus_message_new_method_call(
546 "org.freedesktop.systemd1",
547 "/org/freedesktop/systemd1",
548 "org.freedesktop.systemd1.Manager",
550 log_error("Could not allocate message.");
554 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
555 log_error("Failed to issue method call: %s", error.message);
560 if (!dbus_message_iter_init(reply, &iter) ||
561 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
562 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
563 log_error("Failed to parse reply.");
568 printf("digraph systemd {\n");
570 dbus_message_iter_recurse(&iter, &sub);
571 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
572 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
574 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
575 log_error("Failed to parse reply.");
580 dbus_message_iter_recurse(&sub, &sub2);
582 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
583 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
584 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
585 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
586 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
587 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
588 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
589 log_error("Failed to parse reply.");
594 if ((r = dot_one(bus, id, unit_path)) < 0)
597 /* printf("\t\"%s\";\n", id); */
598 dbus_message_iter_next(&sub);
603 log_info(" Color legend: black = Requires\n"
604 " dark blue = Requisite\n"
605 " dark grey = Wants\n"
609 if (isatty(fileno(stdout)))
610 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
611 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
617 dbus_message_unref(m);
620 dbus_message_unref(reply);
622 dbus_error_free(&error);
627 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
628 DBusMessage *m = NULL, *reply = NULL;
631 DBusMessageIter iter, sub, sub2;
634 dbus_error_init(&error);
638 if (!(m = dbus_message_new_method_call(
639 "org.freedesktop.systemd1",
640 "/org/freedesktop/systemd1",
641 "org.freedesktop.systemd1.Manager",
643 log_error("Could not allocate message.");
647 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
648 log_error("Failed to issue method call: %s", error.message);
653 if (!dbus_message_iter_init(reply, &iter) ||
654 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
655 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
656 log_error("Failed to parse reply.");
661 dbus_message_iter_recurse(&iter, &sub);
663 printf("%4s %-45s %-17s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
665 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
666 const char *name, *type, *state, *job_path, *unit_path;
670 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
671 log_error("Failed to parse reply.");
676 dbus_message_iter_recurse(&sub, &sub2);
678 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
679 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
680 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
681 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
682 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
683 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
684 log_error("Failed to parse reply.");
689 e = arg_full ? NULL : ellipsize(name, 45, 33);
690 printf("%4u %-45s %-17s %-7s\n", id, e ? e : name, type, state);
695 dbus_message_iter_next(&sub);
698 printf("\n%u jobs listed.\n", k);
703 dbus_message_unref(m);
706 dbus_message_unref(reply);
708 dbus_error_free(&error);
713 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
714 DBusMessage *m = NULL, *reply = NULL;
719 dbus_error_init(&error);
724 for (i = 1; i < n; i++) {
726 if (!(m = dbus_message_new_method_call(
727 "org.freedesktop.systemd1",
728 "/org/freedesktop/systemd1",
729 "org.freedesktop.systemd1.Manager",
731 log_error("Could not allocate message.");
736 if (!dbus_message_append_args(m,
737 DBUS_TYPE_STRING, &args[i],
738 DBUS_TYPE_INVALID)) {
739 log_error("Could not append arguments to message.");
744 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
745 log_error("Failed to issue method call: %s", error.message);
750 dbus_message_unref(m);
751 dbus_message_unref(reply);
760 dbus_message_unref(m);
763 dbus_message_unref(reply);
765 dbus_error_free(&error);
770 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
771 DBusMessage *m = NULL, *reply = NULL;
776 dbus_error_init(&error);
782 return daemon_reload(bus, args, n);
784 for (i = 1; i < n; i++) {
788 if (!(m = dbus_message_new_method_call(
789 "org.freedesktop.systemd1",
790 "/org/freedesktop/systemd1",
791 "org.freedesktop.systemd1.Manager",
793 log_error("Could not allocate message.");
798 if ((r = safe_atou(args[i], &id)) < 0) {
799 log_error("Failed to parse job id: %s", strerror(-r));
803 assert_cc(sizeof(uint32_t) == sizeof(id));
804 if (!dbus_message_append_args(m,
805 DBUS_TYPE_UINT32, &id,
806 DBUS_TYPE_INVALID)) {
807 log_error("Could not append arguments to message.");
812 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
813 log_error("Failed to issue method call: %s", error.message);
818 if (!dbus_message_get_args(reply, &error,
819 DBUS_TYPE_OBJECT_PATH, &path,
820 DBUS_TYPE_INVALID)) {
821 log_error("Failed to parse reply: %s", error.message);
826 dbus_message_unref(m);
827 if (!(m = dbus_message_new_method_call(
828 "org.freedesktop.systemd1",
830 "org.freedesktop.systemd1.Job",
832 log_error("Could not allocate message.");
837 dbus_message_unref(reply);
838 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
839 log_error("Failed to issue method call: %s", error.message);
844 dbus_message_unref(m);
845 dbus_message_unref(reply);
853 dbus_message_unref(m);
856 dbus_message_unref(reply);
858 dbus_error_free(&error);
863 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
864 DBusMessage *m = NULL, *reply = NULL;
865 dbus_bool_t b = FALSE;
866 DBusMessageIter iter, sub;
868 *interface = "org.freedesktop.systemd1.Unit",
869 *property = "NeedDaemonReload",
872 /* We ignore all errors here, since this is used to show a warning only */
874 if (!(m = dbus_message_new_method_call(
875 "org.freedesktop.systemd1",
876 "/org/freedesktop/systemd1",
877 "org.freedesktop.systemd1.Manager",
881 if (!dbus_message_append_args(m,
882 DBUS_TYPE_STRING, &unit,
886 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
889 if (!dbus_message_get_args(reply, NULL,
890 DBUS_TYPE_OBJECT_PATH, &path,
894 dbus_message_unref(m);
895 if (!(m = dbus_message_new_method_call(
896 "org.freedesktop.systemd1",
898 "org.freedesktop.DBus.Properties",
902 if (!dbus_message_append_args(m,
903 DBUS_TYPE_STRING, &interface,
904 DBUS_TYPE_STRING, &property,
905 DBUS_TYPE_INVALID)) {
909 dbus_message_unref(reply);
910 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
913 if (!dbus_message_iter_init(reply, &iter) ||
914 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
917 dbus_message_iter_recurse(&iter, &sub);
919 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
922 dbus_message_iter_get_basic(&sub, &b);
926 dbus_message_unref(m);
929 dbus_message_unref(reply);
934 typedef struct WaitData {
939 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
947 dbus_error_init(&error);
949 log_debug("Got D-Bus request: %s.%s() on %s",
950 dbus_message_get_interface(message),
951 dbus_message_get_member(message),
952 dbus_message_get_path(message));
954 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
955 log_error("Warning! D-Bus connection terminated.");
956 dbus_connection_close(connection);
958 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
961 dbus_bool_t success = true;
963 if (!dbus_message_get_args(message, &error,
964 DBUS_TYPE_UINT32, &id,
965 DBUS_TYPE_OBJECT_PATH, &path,
966 DBUS_TYPE_BOOLEAN, &success,
968 log_error("Failed to parse message: %s", error.message);
972 if ((p = set_remove(d->set, (char*) path)))
980 dbus_error_free(&error);
981 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
984 static int enable_wait_for_jobs(DBusConnection *bus) {
992 dbus_error_init(&error);
993 dbus_bus_add_match(bus,
995 "sender='org.freedesktop.systemd1',"
996 "interface='org.freedesktop.systemd1.Manager',"
997 "member='JobRemoved',"
998 "path='/org/freedesktop/systemd1'",
1001 if (dbus_error_is_set(&error)) {
1002 log_error("Failed to add match: %s", error.message);
1003 dbus_error_free(&error);
1007 /* This is slightly dirty, since we don't undo the match registrations. */
1011 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1022 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1023 log_error("Failed to add filter.");
1028 while (!set_isempty(s) &&
1029 dbus_connection_read_write_dispatch(bus, -1))
1032 if (!arg_quiet && d.failed)
1033 log_error("Job failed, see logs for details.");
1035 r = d.failed ? -EIO : 0;
1038 /* This is slightly dirty, since we don't undo the filter registration. */
1043 static int start_unit_one(
1044 DBusConnection *bus,
1050 DBusMessage *m = NULL, *reply = NULL;
1059 assert(arg_no_block || s);
1061 dbus_error_init(&error);
1063 if (!(m = dbus_message_new_method_call(
1064 "org.freedesktop.systemd1",
1065 "/org/freedesktop/systemd1",
1066 "org.freedesktop.systemd1.Manager",
1068 log_error("Could not allocate message.");
1073 if (!dbus_message_append_args(m,
1074 DBUS_TYPE_STRING, &name,
1075 DBUS_TYPE_STRING, &mode,
1076 DBUS_TYPE_INVALID)) {
1077 log_error("Could not append arguments to message.");
1082 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1084 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
1085 /* There's always a fallback possible for
1086 * legacy actions. */
1091 log_error("Failed to issue method call: %s", error.message);
1096 if (!dbus_message_get_args(reply, &error,
1097 DBUS_TYPE_OBJECT_PATH, &path,
1098 DBUS_TYPE_INVALID)) {
1099 log_error("Failed to parse reply: %s", error.message);
1104 if (need_daemon_reload(bus, name))
1105 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1106 arg_session ? "--session" : "--system");
1108 if (!arg_no_block) {
1111 if (!(p = strdup(path))) {
1112 log_error("Failed to duplicate path.");
1117 if ((r = set_put(s, p)) < 0) {
1119 log_error("Failed to add path to set.");
1128 dbus_message_unref(m);
1131 dbus_message_unref(reply);
1133 dbus_error_free(&error);
1138 static enum action verb_to_action(const char *verb) {
1139 if (streq(verb, "halt"))
1141 else if (streq(verb, "poweroff"))
1142 return ACTION_POWEROFF;
1143 else if (streq(verb, "reboot"))
1144 return ACTION_REBOOT;
1145 else if (streq(verb, "rescue"))
1146 return ACTION_RESCUE;
1147 else if (streq(verb, "emergency"))
1148 return ACTION_EMERGENCY;
1149 else if (streq(verb, "default"))
1150 return ACTION_DEFAULT;
1152 return ACTION_INVALID;
1155 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1157 static const char * const table[_ACTION_MAX] = {
1158 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1159 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1160 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1161 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1162 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1163 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1164 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1165 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1166 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1167 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET
1172 const char *method, *mode, *one_name;
1177 if (arg_action == ACTION_SYSTEMCTL) {
1179 streq(args[0], "stop") ? "StopUnit" :
1180 streq(args[0], "reload") ? "ReloadUnit" :
1181 streq(args[0], "restart") ? "RestartUnit" :
1182 streq(args[0], "try-restart") ? "TryRestartUnit" :
1183 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1184 streq(args[0], "reload-or-try-restart") ||
1185 streq(args[0], "force-reload") ||
1186 streq(args[0], "condrestart") ? "ReloadOrTryRestartUnit" :
1190 (streq(args[0], "isolate") ||
1191 streq(args[0], "rescue") ||
1192 streq(args[0], "emergency")) ? "isolate" :
1196 one_name = table[verb_to_action(args[0])];
1199 assert(arg_action < ELEMENTSOF(table));
1200 assert(table[arg_action]);
1202 method = "StartUnit";
1204 mode = (arg_action == ACTION_EMERGENCY ||
1205 arg_action == ACTION_RESCUE) ? "isolate" : "replace";
1207 one_name = table[arg_action];
1210 if (!arg_no_block) {
1211 if ((r = enable_wait_for_jobs(bus)) < 0) {
1212 log_error("Could not watch jobs: %s", strerror(-r));
1216 if (!(s = set_new(string_hash_func, string_compare_func))) {
1217 log_error("Failed to allocate set.");
1226 if ((r = start_unit_one(bus, method, one_name, mode, s)) <= 0)
1229 for (i = 1; i < n; i++)
1230 if ((r = start_unit_one(bus, method, args[i], mode, s)) < 0)
1235 if ((r = wait_for_jobs(bus, s)) < 0)
1247 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1253 r = start_unit(bus, args, n);
1256 warn_wall(verb_to_action(args[0]));
1261 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1262 DBusMessage *m = NULL, *reply = NULL;
1264 *interface = "org.freedesktop.systemd1.Unit",
1265 *property = "ActiveState";
1266 int r = -EADDRNOTAVAIL;
1273 dbus_error_init(&error);
1275 for (i = 1; i < n; i++) {
1276 const char *path = NULL;
1278 DBusMessageIter iter, sub;
1280 if (!(m = dbus_message_new_method_call(
1281 "org.freedesktop.systemd1",
1282 "/org/freedesktop/systemd1",
1283 "org.freedesktop.systemd1.Manager",
1285 log_error("Could not allocate message.");
1290 if (!dbus_message_append_args(m,
1291 DBUS_TYPE_STRING, &args[i],
1292 DBUS_TYPE_INVALID)) {
1293 log_error("Could not append arguments to message.");
1298 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1300 /* Hmm, cannot figure out anything about this unit... */
1304 dbus_error_free(&error);
1308 if (!dbus_message_get_args(reply, &error,
1309 DBUS_TYPE_OBJECT_PATH, &path,
1310 DBUS_TYPE_INVALID)) {
1311 log_error("Failed to parse reply: %s", error.message);
1316 dbus_message_unref(m);
1317 if (!(m = dbus_message_new_method_call(
1318 "org.freedesktop.systemd1",
1320 "org.freedesktop.DBus.Properties",
1322 log_error("Could not allocate message.");
1327 if (!dbus_message_append_args(m,
1328 DBUS_TYPE_STRING, &interface,
1329 DBUS_TYPE_STRING, &property,
1330 DBUS_TYPE_INVALID)) {
1331 log_error("Could not append arguments to message.");
1336 dbus_message_unref(reply);
1337 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1338 log_error("Failed to issue method call: %s", error.message);
1343 if (!dbus_message_iter_init(reply, &iter) ||
1344 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1345 log_error("Failed to parse reply.");
1350 dbus_message_iter_recurse(&iter, &sub);
1352 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1353 log_error("Failed to parse reply.");
1358 dbus_message_iter_get_basic(&sub, &state);
1363 if (streq(state, "active") || startswith(state, "reloading"))
1366 dbus_message_unref(m);
1367 dbus_message_unref(reply);
1373 dbus_message_unref(m);
1376 dbus_message_unref(reply);
1378 dbus_error_free(&error);
1383 typedef struct ExecStatusInfo {
1389 usec_t start_timestamp;
1390 usec_t exit_timestamp;
1395 LIST_FIELDS(struct ExecStatusInfo, exec);
1398 static void exec_status_info_free(ExecStatusInfo *i) {
1406 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1407 uint64_t start_timestamp, exit_timestamp;
1408 DBusMessageIter sub2, sub3;
1412 int32_t code, status;
1418 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1421 dbus_message_iter_recurse(sub, &sub2);
1423 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1426 if (!(i->path = strdup(path)))
1429 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1430 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1434 dbus_message_iter_recurse(&sub2, &sub3);
1435 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1436 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1437 dbus_message_iter_next(&sub3);
1442 if (!(i->argv = new0(char*, n+1)))
1446 dbus_message_iter_recurse(&sub2, &sub3);
1447 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1450 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1451 dbus_message_iter_get_basic(&sub3, &s);
1452 dbus_message_iter_next(&sub3);
1454 if (!(i->argv[n++] = strdup(s)))
1458 if (!dbus_message_iter_next(&sub2) ||
1459 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1460 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1461 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1462 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1463 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1464 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1468 i->start_timestamp = (usec_t) start_timestamp;
1469 i->exit_timestamp = (usec_t) exit_timestamp;
1470 i->pid = (pid_t) pid;
1477 typedef struct UnitStatusInfo {
1479 const char *load_state;
1480 const char *active_state;
1481 const char *sub_state;
1483 const char *description;
1486 const char *default_control_group;
1488 bool need_daemon_reload;
1493 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)
1590 printf("status=%i", p->status);
1592 printf("signal=%s", signal_to_string(p->status));
1595 if (i->main_pid == p->pid &&
1596 i->start_timestamp == p->start_timestamp &&
1597 i->exit_timestamp == p->start_timestamp)
1598 /* Let's not show this twice */
1601 if (p->pid == i->control_pid)
1605 if (i->main_pid > 0 || i->control_pid > 0) {
1608 if (i->main_pid > 0) {
1609 printf(" Main: %u", (unsigned) i->main_pid);
1613 get_process_name(i->main_pid, &t);
1618 } else if (i->exit_code > 0) {
1619 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1621 if (i->exit_code == CLD_EXITED)
1622 printf("status=%i", i->exit_status);
1624 printf("signal=%s", signal_to_string(i->exit_status));
1629 if (i->main_pid > 0 && i->control_pid > 0)
1632 if (i->control_pid > 0) {
1635 printf(" Control: %u", (unsigned) i->control_pid);
1637 get_process_name(i->control_pid, &t);
1648 printf("\t Status: \"%s\"\n", i->status_text);
1650 if (i->default_control_group) {
1653 printf("\t CGroup: %s\n", i->default_control_group);
1655 if ((c = columns()) > 18)
1660 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
1663 if (i->need_daemon_reload)
1664 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1665 ansi_highlight(true),
1666 ansi_highlight(false),
1667 arg_session ? "--session" : "--system");
1670 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1672 switch (dbus_message_iter_get_arg_type(iter)) {
1674 case DBUS_TYPE_STRING: {
1677 dbus_message_iter_get_basic(iter, &s);
1680 if (streq(name, "Id"))
1682 else if (streq(name, "LoadState"))
1684 else if (streq(name, "ActiveState"))
1685 i->active_state = s;
1686 else if (streq(name, "SubState"))
1688 else if (streq(name, "Description"))
1690 else if (streq(name, "FragmentPath"))
1692 else if (streq(name, "SysVPath"))
1694 else if (streq(name, "DefaultControlGroup"))
1695 i->default_control_group = s;
1696 else if (streq(name, "StatusText"))
1698 else if (streq(name, "SysFSPath"))
1700 else if (streq(name, "Where"))
1702 else if (streq(name, "What"))
1709 case DBUS_TYPE_BOOLEAN: {
1712 dbus_message_iter_get_basic(iter, &b);
1714 if (streq(name, "Accept"))
1716 else if (streq(name, "NeedDaemonReload"))
1717 i->need_daemon_reload = b;
1722 case DBUS_TYPE_UINT32: {
1725 dbus_message_iter_get_basic(iter, &u);
1727 if (streq(name, "MainPID")) {
1729 i->main_pid = (pid_t) u;
1732 } else if (streq(name, "ControlPID"))
1733 i->control_pid = (pid_t) u;
1734 else if (streq(name, "ExecMainPID")) {
1736 i->main_pid = (pid_t) u;
1737 } else if (streq(name, "NAccepted"))
1739 else if (streq(name, "NConnections"))
1740 i->n_connections = u;
1745 case DBUS_TYPE_INT32: {
1748 dbus_message_iter_get_basic(iter, &j);
1750 if (streq(name, "ExecMainCode"))
1751 i->exit_code = (int) j;
1752 else if (streq(name, "ExecMainStatus"))
1753 i->exit_status = (int) j;
1758 case DBUS_TYPE_UINT64: {
1761 dbus_message_iter_get_basic(iter, &u);
1763 if (streq(name, "ExecMainStartTimestamp"))
1764 i->start_timestamp = (usec_t) u;
1765 else if (streq(name, "ExecMainExitTimestamp"))
1766 i->exit_timestamp = (usec_t) u;
1771 case DBUS_TYPE_ARRAY: {
1773 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
1774 startswith(name, "Exec")) {
1775 DBusMessageIter sub;
1777 dbus_message_iter_recurse(iter, &sub);
1778 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1779 ExecStatusInfo *info;
1782 if (!(info = new0(ExecStatusInfo, 1)))
1785 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
1790 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
1792 dbus_message_iter_next(&sub);
1803 static int print_property(const char *name, DBusMessageIter *iter) {
1807 /* This is a low-level property printer, see
1808 * print_status_info() for the nicer output */
1810 if (arg_property && !strv_find(arg_property, name))
1813 switch (dbus_message_iter_get_arg_type(iter)) {
1815 case DBUS_TYPE_STRING: {
1817 dbus_message_iter_get_basic(iter, &s);
1819 if (arg_all || s[0])
1820 printf("%s=%s\n", name, s);
1825 case DBUS_TYPE_BOOLEAN: {
1827 dbus_message_iter_get_basic(iter, &b);
1828 printf("%s=%s\n", name, yes_no(b));
1833 case DBUS_TYPE_UINT64: {
1835 dbus_message_iter_get_basic(iter, &u);
1837 /* Yes, heuristics! But we can change this check
1838 * should it turn out to not be sufficient */
1840 if (strstr(name, "Timestamp")) {
1841 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
1843 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
1844 printf("%s=%s\n", name, strempty(t));
1845 } else if (strstr(name, "USec")) {
1846 char timespan[FORMAT_TIMESPAN_MAX];
1848 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
1850 printf("%s=%llu\n", name, (unsigned long long) u);
1855 case DBUS_TYPE_UINT32: {
1857 dbus_message_iter_get_basic(iter, &u);
1859 if (strstr(name, "UMask") || strstr(name, "Mode"))
1860 printf("%s=%04o\n", name, u);
1862 printf("%s=%u\n", name, (unsigned) u);
1867 case DBUS_TYPE_INT32: {
1869 dbus_message_iter_get_basic(iter, &i);
1871 printf("%s=%i\n", name, (int) i);
1875 case DBUS_TYPE_STRUCT: {
1876 DBusMessageIter sub;
1877 dbus_message_iter_recurse(iter, &sub);
1879 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
1882 dbus_message_iter_get_basic(&sub, &u);
1885 printf("%s=%u\n", name, (unsigned) u);
1887 printf("%s=\n", name);
1890 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
1893 dbus_message_iter_get_basic(&sub, &s);
1895 if (arg_all || s[0])
1896 printf("%s=%s\n", name, s);
1904 case DBUS_TYPE_ARRAY:
1906 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
1907 DBusMessageIter sub;
1910 dbus_message_iter_recurse(iter, &sub);
1912 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1913 printf("%s=", name);
1915 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1918 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
1919 dbus_message_iter_get_basic(&sub, &s);
1920 printf("%s%s", space ? " " : "", s);
1923 dbus_message_iter_next(&sub);
1931 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
1932 DBusMessageIter sub;
1934 dbus_message_iter_recurse(iter, &sub);
1936 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1937 printf("%s=", name);
1939 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1942 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
1943 dbus_message_iter_get_basic(&sub, &u);
1946 dbus_message_iter_next(&sub);
1954 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
1955 DBusMessageIter sub, sub2;
1957 dbus_message_iter_recurse(iter, &sub);
1958 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1959 const char *type, *path;
1961 dbus_message_iter_recurse(&sub, &sub2);
1963 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
1964 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
1965 printf("%s=%s\n", type, path);
1967 dbus_message_iter_next(&sub);
1972 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
1973 DBusMessageIter sub, sub2;
1975 dbus_message_iter_recurse(iter, &sub);
1976 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1978 uint64_t value, next_elapse;
1980 dbus_message_iter_recurse(&sub, &sub2);
1982 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
1983 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
1984 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
1985 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
1987 printf("%s={ value=%s ; next_elapse=%s }\n",
1989 format_timespan(timespan1, sizeof(timespan1), value),
1990 format_timespan(timespan2, sizeof(timespan2), next_elapse));
1993 dbus_message_iter_next(&sub);
1998 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
1999 DBusMessageIter sub;
2001 dbus_message_iter_recurse(iter, &sub);
2002 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2003 ExecStatusInfo info;
2006 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2007 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2010 t = strv_join(info.argv, " ");
2012 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2016 yes_no(info.ignore),
2017 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2018 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2019 (unsigned) info. pid,
2020 sigchld_code_to_string(info.code),
2022 info.code == CLD_EXITED ? "" : "/",
2023 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2029 strv_free(info.argv);
2031 dbus_message_iter_next(&sub);
2041 printf("%s=[unprintable]\n", name);
2046 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2047 DBusMessage *m = NULL, *reply = NULL;
2048 const char *interface = "";
2051 DBusMessageIter iter, sub, sub2, sub3;
2052 UnitStatusInfo info;
2060 dbus_error_init(&error);
2062 if (!(m = dbus_message_new_method_call(
2063 "org.freedesktop.systemd1",
2065 "org.freedesktop.DBus.Properties",
2067 log_error("Could not allocate message.");
2072 if (!dbus_message_append_args(m,
2073 DBUS_TYPE_STRING, &interface,
2074 DBUS_TYPE_INVALID)) {
2075 log_error("Could not append arguments to message.");
2080 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2081 log_error("Failed to issue method call: %s", error.message);
2086 if (!dbus_message_iter_init(reply, &iter) ||
2087 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2088 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2089 log_error("Failed to parse reply.");
2094 dbus_message_iter_recurse(&iter, &sub);
2101 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2104 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2105 log_error("Failed to parse reply.");
2110 dbus_message_iter_recurse(&sub, &sub2);
2112 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2113 log_error("Failed to parse reply.");
2118 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2119 log_error("Failed to parse reply.");
2124 dbus_message_iter_recurse(&sub2, &sub3);
2126 if (show_properties)
2127 r = print_property(name, &sub3);
2129 r = status_property(name, &sub3, &info);
2132 log_error("Failed to parse reply.");
2137 dbus_message_iter_next(&sub);
2140 if (!show_properties)
2141 print_status_info(&info);
2143 while ((p = info.exec)) {
2144 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2145 exec_status_info_free(p);
2152 dbus_message_unref(m);
2155 dbus_message_unref(reply);
2157 dbus_error_free(&error);
2162 static int show(DBusConnection *bus, char **args, unsigned n) {
2163 DBusMessage *m = NULL, *reply = NULL;
2167 bool show_properties, new_line = false;
2172 dbus_error_init(&error);
2174 show_properties = !streq(args[0], "status");
2176 if (show_properties && n <= 1) {
2177 /* If not argument is specified inspect the manager
2180 r = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2184 for (i = 1; i < n; i++) {
2185 const char *path = NULL;
2188 if (safe_atou32(args[i], &id) < 0) {
2190 /* Interpret as unit name */
2192 if (!(m = dbus_message_new_method_call(
2193 "org.freedesktop.systemd1",
2194 "/org/freedesktop/systemd1",
2195 "org.freedesktop.systemd1.Manager",
2197 log_error("Could not allocate message.");
2202 if (!dbus_message_append_args(m,
2203 DBUS_TYPE_STRING, &args[i],
2204 DBUS_TYPE_INVALID)) {
2205 log_error("Could not append arguments to message.");
2210 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2212 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2213 log_error("Failed to issue method call: %s", error.message);
2218 dbus_error_free(&error);
2220 dbus_message_unref(m);
2221 if (!(m = dbus_message_new_method_call(
2222 "org.freedesktop.systemd1",
2223 "/org/freedesktop/systemd1",
2224 "org.freedesktop.systemd1.Manager",
2226 log_error("Could not allocate message.");
2231 if (!dbus_message_append_args(m,
2232 DBUS_TYPE_STRING, &args[i],
2233 DBUS_TYPE_INVALID)) {
2234 log_error("Could not append arguments to message.");
2239 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2240 log_error("Failed to issue method call: %s", error.message);
2246 } else if (show_properties) {
2248 /* Interpret as job id */
2250 if (!(m = dbus_message_new_method_call(
2251 "org.freedesktop.systemd1",
2252 "/org/freedesktop/systemd1",
2253 "org.freedesktop.systemd1.Manager",
2255 log_error("Could not allocate message.");
2260 if (!dbus_message_append_args(m,
2261 DBUS_TYPE_UINT32, &id,
2262 DBUS_TYPE_INVALID)) {
2263 log_error("Could not append arguments to message.");
2268 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2269 log_error("Failed to issue method call: %s", error.message);
2275 /* Interpret as PID */
2277 if (!(m = dbus_message_new_method_call(
2278 "org.freedesktop.systemd1",
2279 "/org/freedesktop/systemd1",
2280 "org.freedesktop.systemd1.Manager",
2282 log_error("Could not allocate message.");
2287 if (!dbus_message_append_args(m,
2288 DBUS_TYPE_UINT32, &id,
2289 DBUS_TYPE_INVALID)) {
2290 log_error("Could not append arguments to message.");
2295 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2296 log_error("Failed to issue method call: %s", error.message);
2302 if (!dbus_message_get_args(reply, &error,
2303 DBUS_TYPE_OBJECT_PATH, &path,
2304 DBUS_TYPE_INVALID)) {
2305 log_error("Failed to parse reply: %s", error.message);
2310 if ((r = show_one(bus, path, show_properties, &new_line)) < 0)
2313 dbus_message_unref(m);
2314 dbus_message_unref(reply);
2322 dbus_message_unref(m);
2325 dbus_message_unref(reply);
2327 dbus_error_free(&error);
2332 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2334 DBusMessage *m = NULL, *reply = NULL;
2339 dbus_error_init(&error);
2341 log_debug("Got D-Bus request: %s.%s() on %s",
2342 dbus_message_get_interface(message),
2343 dbus_message_get_member(message),
2344 dbus_message_get_path(message));
2346 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2347 log_error("Warning! D-Bus connection terminated.");
2348 dbus_connection_close(connection);
2350 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2351 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2352 const char *id, *path;
2354 if (!dbus_message_get_args(message, &error,
2355 DBUS_TYPE_STRING, &id,
2356 DBUS_TYPE_OBJECT_PATH, &path,
2358 log_error("Failed to parse message: %s", error.message);
2359 else if (streq(dbus_message_get_member(message), "UnitNew"))
2360 printf("Unit %s added.\n", id);
2362 printf("Unit %s removed.\n", id);
2364 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2365 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2369 if (!dbus_message_get_args(message, &error,
2370 DBUS_TYPE_UINT32, &id,
2371 DBUS_TYPE_OBJECT_PATH, &path,
2373 log_error("Failed to parse message: %s", error.message);
2374 else if (streq(dbus_message_get_member(message), "JobNew"))
2375 printf("Job %u added.\n", id);
2377 printf("Job %u removed.\n", id);
2380 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Unit", "Changed") ||
2381 dbus_message_is_signal(message, "org.freedesktop.systemd1.Job", "Changed")) {
2383 const char *path, *interface, *property = "Id";
2384 DBusMessageIter iter, sub;
2386 path = dbus_message_get_path(message);
2387 interface = dbus_message_get_interface(message);
2389 if (!(m = dbus_message_new_method_call(
2390 "org.freedesktop.systemd1",
2392 "org.freedesktop.DBus.Properties",
2394 log_error("Could not allocate message.");
2398 if (!dbus_message_append_args(m,
2399 DBUS_TYPE_STRING, &interface,
2400 DBUS_TYPE_STRING, &property,
2401 DBUS_TYPE_INVALID)) {
2402 log_error("Could not append arguments to message.");
2406 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2407 log_error("Failed to issue method call: %s", error.message);
2411 if (!dbus_message_iter_init(reply, &iter) ||
2412 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2413 log_error("Failed to parse reply.");
2417 dbus_message_iter_recurse(&iter, &sub);
2419 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2422 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2423 log_error("Failed to parse reply.");
2427 dbus_message_iter_get_basic(&sub, &id);
2428 printf("Unit %s changed.\n", id);
2432 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2433 log_error("Failed to parse reply.");
2437 dbus_message_iter_get_basic(&sub, &id);
2438 printf("Job %u changed.\n", id);
2444 dbus_message_unref(m);
2447 dbus_message_unref(reply);
2449 dbus_error_free(&error);
2450 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2454 dbus_message_unref(m);
2457 dbus_message_unref(reply);
2459 dbus_error_free(&error);
2460 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2463 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2464 DBusMessage *m = NULL, *reply = NULL;
2468 dbus_error_init(&error);
2471 dbus_bus_add_match(bus,
2473 "sender='org.freedesktop.systemd1',"
2474 "interface='org.freedesktop.systemd1.Manager',"
2475 "path='/org/freedesktop/systemd1'",
2478 if (dbus_error_is_set(&error)) {
2479 log_error("Failed to add match: %s", error.message);
2484 dbus_bus_add_match(bus,
2486 "sender='org.freedesktop.systemd1',"
2487 "interface='org.freedesktop.systemd1.Unit',"
2491 if (dbus_error_is_set(&error)) {
2492 log_error("Failed to add match: %s", error.message);
2497 dbus_bus_add_match(bus,
2499 "sender='org.freedesktop.systemd1',"
2500 "interface='org.freedesktop.systemd1.Job',"
2504 if (dbus_error_is_set(&error)) {
2505 log_error("Failed to add match: %s", error.message);
2511 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2512 log_error("Failed to add filter.");
2517 if (!(m = dbus_message_new_method_call(
2518 "org.freedesktop.systemd1",
2519 "/org/freedesktop/systemd1",
2520 "org.freedesktop.systemd1.Manager",
2522 log_error("Could not allocate message.");
2527 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2528 log_error("Failed to issue method call: %s", error.message);
2533 while (dbus_connection_read_write_dispatch(bus, -1))
2540 /* This is slightly dirty, since we don't undo the filter or the matches. */
2543 dbus_message_unref(m);
2546 dbus_message_unref(reply);
2548 dbus_error_free(&error);
2553 static int dump(DBusConnection *bus, char **args, unsigned n) {
2554 DBusMessage *m = NULL, *reply = NULL;
2559 dbus_error_init(&error);
2561 if (!(m = dbus_message_new_method_call(
2562 "org.freedesktop.systemd1",
2563 "/org/freedesktop/systemd1",
2564 "org.freedesktop.systemd1.Manager",
2566 log_error("Could not allocate message.");
2570 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2571 log_error("Failed to issue method call: %s", error.message);
2576 if (!dbus_message_get_args(reply, &error,
2577 DBUS_TYPE_STRING, &text,
2578 DBUS_TYPE_INVALID)) {
2579 log_error("Failed to parse reply: %s", error.message);
2584 fputs(text, stdout);
2590 dbus_message_unref(m);
2593 dbus_message_unref(reply);
2595 dbus_error_free(&error);
2600 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2601 DBusMessage *m = NULL, *reply = NULL;
2604 const char *name = "", *path, *id;
2605 dbus_bool_t cleanup = FALSE;
2606 DBusMessageIter iter, sub;
2608 *interface = "org.freedesktop.systemd1.Unit",
2611 dbus_error_init(&error);
2613 if (!(m = dbus_message_new_method_call(
2614 "org.freedesktop.systemd1",
2615 "/org/freedesktop/systemd1",
2616 "org.freedesktop.systemd1.Manager",
2617 "CreateSnapshot"))) {
2618 log_error("Could not allocate message.");
2625 if (!dbus_message_append_args(m,
2626 DBUS_TYPE_STRING, &name,
2627 DBUS_TYPE_BOOLEAN, &cleanup,
2628 DBUS_TYPE_INVALID)) {
2629 log_error("Could not append arguments to message.");
2634 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2635 log_error("Failed to issue method call: %s", error.message);
2640 if (!dbus_message_get_args(reply, &error,
2641 DBUS_TYPE_OBJECT_PATH, &path,
2642 DBUS_TYPE_INVALID)) {
2643 log_error("Failed to parse reply: %s", error.message);
2648 dbus_message_unref(m);
2649 if (!(m = dbus_message_new_method_call(
2650 "org.freedesktop.systemd1",
2652 "org.freedesktop.DBus.Properties",
2654 log_error("Could not allocate message.");
2658 if (!dbus_message_append_args(m,
2659 DBUS_TYPE_STRING, &interface,
2660 DBUS_TYPE_STRING, &property,
2661 DBUS_TYPE_INVALID)) {
2662 log_error("Could not append arguments to message.");
2667 dbus_message_unref(reply);
2668 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2669 log_error("Failed to issue method call: %s", error.message);
2674 if (!dbus_message_iter_init(reply, &iter) ||
2675 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2676 log_error("Failed to parse reply.");
2681 dbus_message_iter_recurse(&iter, &sub);
2683 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2684 log_error("Failed to parse reply.");
2689 dbus_message_iter_get_basic(&sub, &id);
2697 dbus_message_unref(m);
2700 dbus_message_unref(reply);
2702 dbus_error_free(&error);
2707 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2708 DBusMessage *m = NULL, *reply = NULL;
2716 dbus_error_init(&error);
2718 for (i = 1; i < n; i++) {
2719 const char *path = NULL;
2721 if (!(m = dbus_message_new_method_call(
2722 "org.freedesktop.systemd1",
2723 "/org/freedesktop/systemd1",
2724 "org.freedesktop.systemd1.Manager",
2726 log_error("Could not allocate message.");
2731 if (!dbus_message_append_args(m,
2732 DBUS_TYPE_STRING, &args[i],
2733 DBUS_TYPE_INVALID)) {
2734 log_error("Could not append arguments to message.");
2739 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2740 log_error("Failed to issue method call: %s", error.message);
2745 if (!dbus_message_get_args(reply, &error,
2746 DBUS_TYPE_OBJECT_PATH, &path,
2747 DBUS_TYPE_INVALID)) {
2748 log_error("Failed to parse reply: %s", error.message);
2753 dbus_message_unref(m);
2754 if (!(m = dbus_message_new_method_call(
2755 "org.freedesktop.systemd1",
2757 "org.freedesktop.systemd1.Snapshot",
2759 log_error("Could not allocate message.");
2764 dbus_message_unref(reply);
2765 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2766 log_error("Failed to issue method call: %s", error.message);
2771 dbus_message_unref(m);
2772 dbus_message_unref(reply);
2780 dbus_message_unref(m);
2783 dbus_message_unref(reply);
2785 dbus_error_free(&error);
2790 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2791 DBusMessage *m = NULL, *reply = NULL;
2796 dbus_error_init(&error);
2798 if (arg_action == ACTION_RELOAD)
2800 else if (arg_action == ACTION_REEXEC)
2801 method = "Reexecute";
2803 assert(arg_action == ACTION_SYSTEMCTL);
2806 streq(args[0], "clear-jobs") ||
2807 streq(args[0], "cancel") ? "ClearJobs" :
2808 streq(args[0], "daemon-reexec") ? "Reexecute" :
2809 streq(args[0], "reset-maintenance") ? "ResetMaintenance" :
2810 streq(args[0], "daemon-exit") ? "Exit" :
2814 if (!(m = dbus_message_new_method_call(
2815 "org.freedesktop.systemd1",
2816 "/org/freedesktop/systemd1",
2817 "org.freedesktop.systemd1.Manager",
2819 log_error("Could not allocate message.");
2823 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2825 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
2826 /* There's always a fallback possible for
2827 * legacy actions. */
2832 log_error("Failed to issue method call: %s", error.message);
2841 dbus_message_unref(m);
2844 dbus_message_unref(reply);
2846 dbus_error_free(&error);
2851 static int reset_maintenance(DBusConnection *bus, char **args, unsigned n) {
2852 DBusMessage *m = NULL, *reply = NULL;
2858 dbus_error_init(&error);
2861 return daemon_reload(bus, args, n);
2863 for (i = 1; i < n; i++) {
2865 if (!(m = dbus_message_new_method_call(
2866 "org.freedesktop.systemd1",
2867 "/org/freedesktop/systemd1",
2868 "org.freedesktop.systemd1.Manager",
2869 "ResetMaintenanceUnit"))) {
2870 log_error("Could not allocate message.");
2875 if (!dbus_message_append_args(m,
2876 DBUS_TYPE_STRING, args + i,
2877 DBUS_TYPE_INVALID)) {
2878 log_error("Could not append arguments to message.");
2883 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2884 log_error("Failed to issue method call: %s", error.message);
2889 dbus_message_unref(m);
2890 dbus_message_unref(reply);
2898 dbus_message_unref(m);
2901 dbus_message_unref(reply);
2903 dbus_error_free(&error);
2908 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
2909 DBusMessage *m = NULL, *reply = NULL;
2911 DBusMessageIter iter, sub, sub2;
2914 *interface = "org.freedesktop.systemd1.Manager",
2915 *property = "Environment";
2917 dbus_error_init(&error);
2919 if (!(m = dbus_message_new_method_call(
2920 "org.freedesktop.systemd1",
2921 "/org/freedesktop/systemd1",
2922 "org.freedesktop.DBus.Properties",
2924 log_error("Could not allocate message.");
2928 if (!dbus_message_append_args(m,
2929 DBUS_TYPE_STRING, &interface,
2930 DBUS_TYPE_STRING, &property,
2931 DBUS_TYPE_INVALID)) {
2932 log_error("Could not append arguments to message.");
2937 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2938 log_error("Failed to issue method call: %s", error.message);
2943 if (!dbus_message_iter_init(reply, &iter) ||
2944 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2945 log_error("Failed to parse reply.");
2950 dbus_message_iter_recurse(&iter, &sub);
2952 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
2953 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
2954 log_error("Failed to parse reply.");
2959 dbus_message_iter_recurse(&sub, &sub2);
2961 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
2964 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
2965 log_error("Failed to parse reply.");
2970 dbus_message_iter_get_basic(&sub2, &text);
2971 printf("%s\n", text);
2973 dbus_message_iter_next(&sub2);
2980 dbus_message_unref(m);
2983 dbus_message_unref(reply);
2985 dbus_error_free(&error);
2990 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
2991 DBusMessage *m = NULL, *reply = NULL;
2995 DBusMessageIter iter, sub;
2998 dbus_error_init(&error);
3000 method = streq(args[0], "set-environment")
3002 : "UnsetEnvironment";
3004 if (!(m = dbus_message_new_method_call(
3005 "org.freedesktop.systemd1",
3006 "/org/freedesktop/systemd1",
3007 "org.freedesktop.systemd1.Manager",
3010 log_error("Could not allocate message.");
3014 dbus_message_iter_init_append(m, &iter);
3016 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3017 log_error("Could not append arguments to message.");
3022 for (i = 1; i < n; i++)
3023 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3024 log_error("Could not append arguments to message.");
3029 if (!dbus_message_iter_close_container(&iter, &sub)) {
3030 log_error("Could not append arguments to message.");
3035 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3036 log_error("Failed to issue method call: %s", error.message);
3045 dbus_message_unref(m);
3048 dbus_message_unref(reply);
3050 dbus_error_free(&error);
3063 static Hashmap *will_install = NULL, *have_installed = NULL;
3064 static Set *remove_symlinks_to = NULL;
3066 static void install_info_free(InstallInfo *i) {
3071 strv_free(i->aliases);
3072 strv_free(i->wanted_by);
3076 static void install_info_hashmap_free(Hashmap *m) {
3079 while ((i = hashmap_steal_first(m)))
3080 install_info_free(i);
3085 static bool unit_name_valid(const char *name) {
3087 /* This is a minimal version of unit_name_valid() from
3093 if (ignore_file(name))
3099 static int install_info_add(const char *name) {
3103 assert(will_install);
3105 if (!unit_name_valid(name))
3108 if (hashmap_get(have_installed, name) ||
3109 hashmap_get(will_install, name))
3112 if (!(i = new0(InstallInfo, 1))) {
3117 if (!(i->name = strdup(name))) {
3122 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3129 install_info_free(i);
3134 static int config_parse_also(
3135 const char *filename,
3137 const char *section,
3151 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3155 if (!(n = strndup(w, l)))
3158 r = install_info_add(n);
3168 static int mark_symlink_for_removal(const char *p) {
3173 assert(path_is_absolute(p));
3175 if (!remove_symlinks_to)
3178 if (!(n = strdup(p)))
3181 path_kill_slashes(n);
3183 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3185 return r == -EEXIST ? 0 : r;
3191 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3200 if (!(d = fdopendir(fd))) {
3201 close_nointr_nofail(fd);
3207 while ((de = readdir(d))) {
3208 bool is_dir = false, is_link = false;
3210 if (ignore_file(de->d_name))
3213 if (de->d_type == DT_LNK)
3215 else if (de->d_type == DT_DIR)
3217 else if (de->d_type == DT_UNKNOWN) {
3220 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3221 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3228 is_link = S_ISLNK(st.st_mode);
3229 is_dir = S_ISDIR(st.st_mode);
3237 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3238 log_error("Failed to open %s/%s: %m", root, de->d_name);
3245 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3246 log_error("Failed to allocate directory string.");
3247 close_nointr_nofail(nfd);
3252 /* This will close nfd, regardless whether it succeeds or not */
3253 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3259 } else if (is_link) {
3263 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3264 log_error("Failed to allocate symlink string.");
3269 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3270 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3278 if ((c = canonicalize_file_name(dest))) {
3279 /* This might fail if the destination
3280 * is already removed */
3286 path_kill_slashes(dest);
3287 if (set_get(remove_symlinks_to, dest)) {
3290 log_info("rm '%s'", p);
3292 if (unlink(p) < 0) {
3293 log_error("Cannot unlink symlink %s: %m", p);
3298 rmdir_parents(p, config_path);
3299 path_kill_slashes(p);
3301 if (!set_get(remove_symlinks_to, p)) {
3303 if ((r = mark_symlink_for_removal(p)) < 0) {
3322 static int remove_marked_symlinks(const char *config_path) {
3326 assert(config_path);
3328 if (set_size(remove_symlinks_to) <= 0)
3331 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3338 if ((cfd = dup(fd)) < 0) {
3343 /* This takes possession of cfd and closes it */
3344 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3350 close_nointr_nofail(fd);
3355 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3362 if (streq(verb, "enable")) {
3365 mkdir_parents(new_path, 0755);
3367 if (symlink(old_path, new_path) >= 0) {
3370 log_info("ln -s '%s' '%s'", old_path, new_path);
3375 if (errno != EEXIST) {
3376 log_error("Cannot link %s to %s: %m", old_path, new_path);
3380 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3382 if (errno == EINVAL) {
3383 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3387 log_error("readlink() failed: %s", strerror(-r));
3391 if (streq(dest, old_path)) {
3397 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3406 log_info("ln -s '%s' '%s'", old_path, new_path);
3408 if (symlink(old_path, new_path) >= 0)
3411 log_error("Cannot link %s to %s: %m", old_path, new_path);
3414 } else if (streq(verb, "disable")) {
3417 if ((r = mark_symlink_for_removal(old_path)) < 0)
3420 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3421 if (errno == ENOENT)
3424 if (errno == EINVAL) {
3425 log_warning("File %s not a symlink, ignoring.", old_path);
3429 log_error("readlink() failed: %s", strerror(-r));
3433 if (!streq(dest, old_path)) {
3434 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3441 if ((r = mark_symlink_for_removal(new_path)) < 0)
3445 log_info("rm '%s'", new_path);
3447 if (unlink(new_path) >= 0)
3450 log_error("Cannot unlink %s: %m", new_path);
3453 } else if (streq(verb, "is-enabled")) {
3456 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3458 if (errno == ENOENT || errno == EINVAL)
3461 log_error("readlink() failed: %s", strerror(-r));
3465 if (streq(dest, old_path)) {
3473 assert_not_reached("Unknown action.");
3476 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3478 char *alias_path = NULL;
3483 assert(config_path);
3485 STRV_FOREACH(s, i->aliases) {
3487 if (!unit_name_valid(*s)) {
3488 log_error("Invalid name %s.", *s);
3494 if (!(alias_path = path_make_absolute(*s, config_path))) {
3495 log_error("Out of memory");
3500 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3503 if (streq(verb, "disable"))
3504 rmdir_parents(alias_path, config_path);
3515 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3517 char *alias_path = NULL;
3522 assert(config_path);
3524 STRV_FOREACH(s, i->wanted_by) {
3525 if (!unit_name_valid(*s)) {
3526 log_error("Invalid name %s.", *s);
3534 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3535 log_error("Out of memory");
3540 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3543 if (streq(verb, "disable"))
3544 rmdir_parents(alias_path, config_path);
3555 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3557 const ConfigItem items[] = {
3558 { "Alias", config_parse_strv, &i->aliases, "Install" },
3559 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3560 { "Also", config_parse_also, NULL, "Install" },
3562 { NULL, NULL, NULL, NULL }
3566 char *filename = NULL;
3573 STRV_FOREACH(p, paths->unit_path) {
3576 if (!(filename = path_make_absolute(i->name, *p))) {
3577 log_error("Out of memory");
3581 /* Ensure that we don't follow symlinks */
3582 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3583 if ((f = fdopen(fd, "re")))
3586 if (errno == ELOOP) {
3587 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3592 if (errno != ENOENT) {
3593 log_error("Failed to open %s: %m", filename);
3603 log_error("Couldn't find %s.", i->name);
3609 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3616 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3619 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3622 if ((r = mark_symlink_for_removal(filename)) < 0)
3625 if ((r = remove_marked_symlinks(config_path)) < 0)
3631 static char *get_config_path(void) {
3633 if (arg_session && arg_global)
3634 return strdup(SESSION_CONFIG_UNIT_PATH);
3639 if (session_config_home(&p) < 0)
3645 return strdup(SYSTEM_CONFIG_UNIT_PATH);
3648 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3652 char *config_path = NULL;
3655 const char *verb = args[0];
3657 dbus_error_init(&error);
3660 if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3661 log_error("Failed to determine lookup paths: %s", strerror(-r));
3665 if (!(config_path = get_config_path())) {
3666 log_error("Failed to determine config path");
3671 will_install = hashmap_new(string_hash_func, string_compare_func);
3672 have_installed = hashmap_new(string_hash_func, string_compare_func);
3674 if (!will_install || !have_installed) {
3675 log_error("Failed to allocate unit sets.");
3680 if (!arg_defaults && streq(verb, "disable"))
3681 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3682 log_error("Failed to allocate symlink sets.");
3687 for (j = 1; j < n; j++)
3688 if ((r = install_info_add(args[j])) < 0)
3691 while ((i = hashmap_first(will_install))) {
3694 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3696 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3704 /* In test mode and found something */
3710 if (streq(verb, "is-enabled"))
3711 r = r > 0 ? 0 : -ENOENT;
3713 /* Don't try to reload anything if the user asked us to not do this */
3715 /* Don't try to reload anything when updating a unit globally */
3717 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3718 (arg_session || sd_booted() > 0) &&
3719 /* Don't try to reload anything if we are running in a chroot environment */
3720 (arg_session || running_in_chroot() <= 0) ) {
3723 if ((q = daemon_reload(bus, args, n)) < 0)
3728 install_info_hashmap_free(will_install);
3729 install_info_hashmap_free(have_installed);
3731 set_free_free(remove_symlinks_to);
3733 lookup_paths_free(&paths);
3740 static int systemctl_help(void) {
3742 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3743 "Send control commands to or query the systemd manager.\n\n"
3744 " -h --help Show this help\n"
3745 " -t --type=TYPE List only units of a particular type\n"
3746 " -p --property=NAME Show only properties by this name\n"
3747 " -a --all Show all units/properties, including dead/empty ones\n"
3748 " --full Don't ellipsize unit names on output\n"
3749 " --fail When queueing a new job, fail if conflicting jobs are\n"
3751 " -q --quiet Suppress output\n"
3752 " --no-block Do not wait until operation finished\n"
3753 " --system Connect to system bus\n"
3754 " --session Connect to session bus\n"
3755 " --order When generating graph for dot, show only order\n"
3756 " --require When generating graph for dot, show only requirement\n"
3757 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3758 " --global Enable/disable unit files globally\n"
3759 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3761 " --force When enabling unit files, override existing symlinks\n"
3762 " --defaults When disabling unit files, remove default symlinks only\n\n"
3764 " list-units List units\n"
3765 " start [NAME...] Start (activate) one or more units\n"
3766 " stop [NAME...] Stop (deactivate) one or more units\n"
3767 " reload [NAME...] Reload one or more units\n"
3768 " restart [NAME...] Start or restart one or more units\n"
3769 " try-restart [NAME...] Restart one or more units if active\n"
3770 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3771 " otherwise start or restart\n"
3772 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3773 " otherwise restart if active\n"
3774 " isolate [NAME] Start one unit and stop all others\n"
3775 " is-active [NAME...] Check whether units are active\n"
3776 " status [NAME...|PID...] Show runtime status of one or more units\n"
3777 " show [NAME...|JOB...] Show properties of one or more\n"
3778 " units/jobs or the manager\n"
3779 " reset-maintenance [NAME...] Reset maintenance state for all, one,\n"
3781 " enable [NAME...] Enable one or more unit files\n"
3782 " disable [NAME...] Disable one or more unit files\n"
3783 " is-enabled [NAME...] Check whether unit files are enabled\n"
3784 " load [NAME...] Load one or more units\n"
3785 " list-jobs List jobs\n"
3786 " cancel [JOB...] Cancel all, one, or more jobs\n"
3787 " monitor Monitor unit/job changes\n"
3788 " dump Dump server status\n"
3789 " dot Dump dependency graph for dot(1)\n"
3790 " snapshot [NAME] Create a snapshot\n"
3791 " delete [NAME...] Remove one or more snapshots\n"
3792 " daemon-reload Reload systemd manager configuration\n"
3793 " daemon-reexec Reexecute systemd manager\n"
3794 " daemon-exit Ask the systemd manager to quit\n"
3795 " show-environment Dump environment\n"
3796 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3797 " unset-environment [NAME...] Unset one or more environment variables\n"
3798 " halt Shut down and halt the system\n"
3799 " poweroff Shut down and power-off the system\n"
3800 " reboot Shut down and reboot the system\n"
3801 " rescue Enter system rescue mode\n"
3802 " emergency Enter system emergency mode\n"
3803 " default Enter system default mode\n",
3804 program_invocation_short_name);
3809 static int halt_help(void) {
3811 printf("%s [OPTIONS...]\n\n"
3812 "%s the system.\n\n"
3813 " --help Show this help\n"
3814 " --halt Halt the machine\n"
3815 " -p --poweroff Switch off the machine\n"
3816 " --reboot Reboot the machine\n"
3817 " -f --force Force immediate halt/power-off/reboot\n"
3818 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3819 " -d --no-wtmp Don't write wtmp record\n"
3820 " -n --no-sync Don't sync before halt/power-off/reboot\n"
3821 " --no-wall Don't send wall message before halt/power-off/reboot\n",
3822 program_invocation_short_name,
3823 arg_action == ACTION_REBOOT ? "Reboot" :
3824 arg_action == ACTION_POWEROFF ? "Power off" :
3830 static int shutdown_help(void) {
3832 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3833 "Shut down the system.\n\n"
3834 " --help Show this help\n"
3835 " -H --halt Halt the machine\n"
3836 " -P --poweroff Power-off the machine\n"
3837 " -r --reboot Reboot the machine\n"
3838 " -h Equivalent to --poweroff, overriden by --halt\n"
3839 " -k Don't halt/power-off/reboot, just send warnings\n"
3840 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3841 " -f Skip fsck on reboot\n"
3842 " -F Force fsck on reboot\n"
3843 " -c Cancel a pending shutdown\n",
3844 program_invocation_short_name);
3849 static int telinit_help(void) {
3851 printf("%s [OPTIONS...] {COMMAND}\n\n"
3852 "Send control commands to the init daemon.\n\n"
3853 " --help Show this help\n"
3854 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
3856 " 0 Power-off the machine\n"
3857 " 6 Reboot the machine\n"
3858 " 2, 3, 4, 5 Start runlevelX.target unit\n"
3859 " 1, s, S Enter rescue mode\n"
3860 " q, Q Reload init daemon configuration\n"
3861 " u, U Reexecute init daemon\n",
3862 program_invocation_short_name);
3867 static int runlevel_help(void) {
3869 printf("%s [OPTIONS...]\n\n"
3870 "Prints the previous and current runlevel of the init system.\n\n"
3871 " --help Show this help\n",
3872 program_invocation_short_name);
3877 static int systemctl_parse_argv(int argc, char *argv[]) {
3894 static const struct option options[] = {
3895 { "help", no_argument, NULL, 'h' },
3896 { "type", required_argument, NULL, 't' },
3897 { "property", required_argument, NULL, 'p' },
3898 { "all", no_argument, NULL, 'a' },
3899 { "full", no_argument, NULL, ARG_FULL },
3900 { "fail", no_argument, NULL, ARG_FAIL },
3901 { "session", no_argument, NULL, ARG_SESSION },
3902 { "system", no_argument, NULL, ARG_SYSTEM },
3903 { "global", no_argument, NULL, ARG_GLOBAL },
3904 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
3905 { "no-wall", no_argument, NULL, ARG_NO_WALL },
3906 { "quiet", no_argument, NULL, 'q' },
3907 { "order", no_argument, NULL, ARG_ORDER },
3908 { "require", no_argument, NULL, ARG_REQUIRE },
3909 { "force", no_argument, NULL, ARG_FORCE },
3910 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
3911 { "defaults", no_argument, NULL, ARG_DEFAULTS },
3912 { NULL, 0, NULL, 0 }
3920 while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
3935 if (!(l = strv_append(arg_property, optarg)))
3938 strv_free(arg_property);
3941 /* If the user asked for a particular
3942 * property, show it to him, even if it is
3961 arg_session = false;
3965 arg_no_block = true;
3973 arg_dot = DOT_ORDER;
3977 arg_dot = DOT_REQUIRE;
3993 arg_no_reload = true;
4002 arg_defaults = true;
4009 log_error("Unknown option code %c", c);
4017 static int halt_parse_argv(int argc, char *argv[]) {
4026 static const struct option options[] = {
4027 { "help", no_argument, NULL, ARG_HELP },
4028 { "halt", no_argument, NULL, ARG_HALT },
4029 { "poweroff", no_argument, NULL, 'p' },
4030 { "reboot", no_argument, NULL, ARG_REBOOT },
4031 { "force", no_argument, NULL, 'f' },
4032 { "wtmp-only", no_argument, NULL, 'w' },
4033 { "no-wtmp", no_argument, NULL, 'd' },
4034 { "no-sync", no_argument, NULL, 'n' },
4035 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4036 { NULL, 0, NULL, 0 }
4044 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4045 if (runlevel == '0' || runlevel == '6')
4046 arg_immediate = true;
4048 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4056 arg_action = ACTION_HALT;
4060 if (arg_action != ACTION_REBOOT)
4061 arg_action = ACTION_POWEROFF;
4065 arg_action = ACTION_REBOOT;
4069 arg_immediate = true;
4090 /* Compatibility nops */
4097 log_error("Unknown option code %c", c);
4102 if (optind < argc) {
4103 log_error("Too many arguments.");
4110 static int parse_time_spec(const char *t, usec_t *_u) {
4114 if (streq(t, "now"))
4116 else if (t[0] == '+') {
4119 if (safe_atou64(t + 1, &u) < 0)
4122 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4131 hour = strtol(t, &e, 10);
4132 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4135 minute = strtol(e+1, &e, 10);
4136 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4139 n = now(CLOCK_REALTIME);
4140 s = (time_t) (n / USEC_PER_SEC);
4143 assert_se(localtime_r(&s, &tm));
4145 tm.tm_hour = (int) hour;
4146 tm.tm_min = (int) minute;
4149 assert_se(s = mktime(&tm));
4151 *_u = (usec_t) s * USEC_PER_SEC;
4154 *_u += USEC_PER_DAY;
4160 static int shutdown_parse_argv(int argc, char *argv[]) {
4167 static const struct option options[] = {
4168 { "help", no_argument, NULL, ARG_HELP },
4169 { "halt", no_argument, NULL, 'H' },
4170 { "poweroff", no_argument, NULL, 'P' },
4171 { "reboot", no_argument, NULL, 'r' },
4172 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4173 { NULL, 0, NULL, 0 }
4181 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4189 arg_action = ACTION_HALT;
4193 arg_action = ACTION_POWEROFF;
4197 arg_action = ACTION_REBOOT;
4201 if (arg_action != ACTION_HALT)
4202 arg_action = ACTION_POWEROFF;
4215 /* Compatibility nops */
4219 arg_skip_fsck = true;
4223 arg_force_fsck = true;
4227 arg_action = ACTION_CANCEL_SHUTDOWN;
4234 log_error("Unknown option code %c", c);
4239 if (argc > optind) {
4240 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4241 log_error("Failed to parse time specification: %s", argv[optind]);
4245 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4247 /* We skip the time argument */
4248 if (argc > optind + 1)
4249 arg_wall = argv + optind + 1;
4256 static int telinit_parse_argv(int argc, char *argv[]) {
4263 static const struct option options[] = {
4264 { "help", no_argument, NULL, ARG_HELP },
4265 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4266 { NULL, 0, NULL, 0 }
4269 static const struct {
4273 { '0', ACTION_POWEROFF },
4274 { '6', ACTION_REBOOT },
4275 { '1', ACTION_RESCUE },
4276 { '2', ACTION_RUNLEVEL2 },
4277 { '3', ACTION_RUNLEVEL3 },
4278 { '4', ACTION_RUNLEVEL4 },
4279 { '5', ACTION_RUNLEVEL5 },
4280 { 's', ACTION_RESCUE },
4281 { 'S', ACTION_RESCUE },
4282 { 'q', ACTION_RELOAD },
4283 { 'Q', ACTION_RELOAD },
4284 { 'u', ACTION_REEXEC },
4285 { 'U', ACTION_REEXEC }
4294 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4309 log_error("Unknown option code %c", c);
4314 if (optind >= argc) {
4319 if (optind + 1 < argc) {
4320 log_error("Too many arguments.");
4324 if (strlen(argv[optind]) != 1) {
4325 log_error("Expected single character argument.");
4329 for (i = 0; i < ELEMENTSOF(table); i++)
4330 if (table[i].from == argv[optind][0])
4333 if (i >= ELEMENTSOF(table)) {
4334 log_error("Unknown command %s.", argv[optind]);
4338 arg_action = table[i].to;
4345 static int runlevel_parse_argv(int argc, char *argv[]) {
4351 static const struct option options[] = {
4352 { "help", no_argument, NULL, ARG_HELP },
4353 { NULL, 0, NULL, 0 }
4361 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4372 log_error("Unknown option code %c", c);
4377 if (optind < argc) {
4378 log_error("Too many arguments.");
4385 static int parse_argv(int argc, char *argv[]) {
4389 if (program_invocation_short_name) {
4391 if (strstr(program_invocation_short_name, "halt")) {
4392 arg_action = ACTION_HALT;
4393 return halt_parse_argv(argc, argv);
4394 } else if (strstr(program_invocation_short_name, "poweroff")) {
4395 arg_action = ACTION_POWEROFF;
4396 return halt_parse_argv(argc, argv);
4397 } else if (strstr(program_invocation_short_name, "reboot")) {
4398 arg_action = ACTION_REBOOT;
4399 return halt_parse_argv(argc, argv);
4400 } else if (strstr(program_invocation_short_name, "shutdown")) {
4401 arg_action = ACTION_POWEROFF;
4402 return shutdown_parse_argv(argc, argv);
4403 } else if (strstr(program_invocation_short_name, "init")) {
4405 if (sd_booted() > 0) {
4406 arg_action = ACTION_INVALID;
4407 return telinit_parse_argv(argc, argv);
4409 /* Hmm, so some other init system is
4410 * running, we need to forward this
4411 * request to it. For now we simply
4412 * guess that it is Upstart. */
4414 execv("/lib/upstart/telinit", argv);
4416 log_error("Couldn't find an alternative telinit implementation to spawn.");
4420 } else if (strstr(program_invocation_short_name, "runlevel")) {
4421 arg_action = ACTION_RUNLEVEL;
4422 return runlevel_parse_argv(argc, argv);
4426 arg_action = ACTION_SYSTEMCTL;
4427 return systemctl_parse_argv(argc, argv);
4430 static int action_to_runlevel(void) {
4432 static const char table[_ACTION_MAX] = {
4433 [ACTION_HALT] = '0',
4434 [ACTION_POWEROFF] = '0',
4435 [ACTION_REBOOT] = '6',
4436 [ACTION_RUNLEVEL2] = '2',
4437 [ACTION_RUNLEVEL3] = '3',
4438 [ACTION_RUNLEVEL4] = '4',
4439 [ACTION_RUNLEVEL5] = '5',
4440 [ACTION_RESCUE] = '1'
4443 assert(arg_action < _ACTION_MAX);
4445 return table[arg_action];
4448 static int talk_upstart(void) {
4449 DBusMessage *m = NULL, *reply = NULL;
4451 int previous, rl, r;
4453 env1_buf[] = "RUNLEVEL=X",
4454 env2_buf[] = "PREVLEVEL=X";
4455 char *env1 = env1_buf, *env2 = env2_buf;
4456 const char *emit = "runlevel";
4457 dbus_bool_t b_false = FALSE;
4458 DBusMessageIter iter, sub;
4459 DBusConnection *bus;
4461 dbus_error_init(&error);
4463 if (!(rl = action_to_runlevel()))
4466 if (utmp_get_runlevel(&previous, NULL) < 0)
4469 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4470 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4475 log_error("Failed to connect to Upstart bus: %s", error.message);
4480 if ((r = bus_check_peercred(bus)) < 0) {
4481 log_error("Failed to verify owner of bus.");
4485 if (!(m = dbus_message_new_method_call(
4486 "com.ubuntu.Upstart",
4487 "/com/ubuntu/Upstart",
4488 "com.ubuntu.Upstart0_6",
4491 log_error("Could not allocate message.");
4496 dbus_message_iter_init_append(m, &iter);
4498 env1_buf[sizeof(env1_buf)-2] = rl;
4499 env2_buf[sizeof(env2_buf)-2] = previous;
4501 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4502 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4503 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4504 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4505 !dbus_message_iter_close_container(&iter, &sub) ||
4506 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4507 log_error("Could not append arguments to message.");
4512 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4514 if (error_is_no_service(&error)) {
4519 log_error("Failed to issue method call: %s", error.message);
4528 dbus_message_unref(m);
4531 dbus_message_unref(reply);
4534 dbus_connection_close(bus);
4535 dbus_connection_unref(bus);
4538 dbus_error_free(&error);
4543 static int talk_initctl(void) {
4544 struct init_request request;
4548 if (!(rl = action_to_runlevel()))
4552 request.magic = INIT_MAGIC;
4553 request.sleeptime = 0;
4554 request.cmd = INIT_CMD_RUNLVL;
4555 request.runlevel = rl;
4557 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4559 if (errno == ENOENT)
4562 log_error("Failed to open "INIT_FIFO": %m");
4567 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4568 close_nointr_nofail(fd);
4571 log_error("Failed to write to "INIT_FIFO": %m");
4572 return errno ? -errno : -EIO;
4578 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4580 static const struct {
4588 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4590 { "list-units", LESS, 1, list_units },
4591 { "list-jobs", EQUAL, 1, list_jobs },
4592 { "clear-jobs", EQUAL, 1, daemon_reload },
4593 { "load", MORE, 2, load_unit },
4594 { "cancel", MORE, 2, cancel_job },
4595 { "start", MORE, 2, start_unit },
4596 { "stop", MORE, 2, start_unit },
4597 { "reload", MORE, 2, start_unit },
4598 { "restart", MORE, 2, start_unit },
4599 { "try-restart", MORE, 2, start_unit },
4600 { "reload-or-restart", MORE, 2, start_unit },
4601 { "reload-or-try-restart", MORE, 2, start_unit },
4602 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4603 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4604 { "isolate", EQUAL, 2, start_unit },
4605 { "is-active", MORE, 2, check_unit },
4606 { "check", MORE, 2, check_unit },
4607 { "show", MORE, 1, show },
4608 { "status", MORE, 2, show },
4609 { "monitor", EQUAL, 1, monitor },
4610 { "dump", EQUAL, 1, dump },
4611 { "dot", EQUAL, 1, dot },
4612 { "snapshot", LESS, 2, snapshot },
4613 { "delete", MORE, 2, delete_snapshot },
4614 { "daemon-reload", EQUAL, 1, daemon_reload },
4615 { "daemon-reexec", EQUAL, 1, daemon_reload },
4616 { "daemon-exit", EQUAL, 1, daemon_reload },
4617 { "show-environment", EQUAL, 1, show_enviroment },
4618 { "set-environment", MORE, 2, set_environment },
4619 { "unset-environment", MORE, 2, set_environment },
4620 { "halt", EQUAL, 1, start_special },
4621 { "poweroff", EQUAL, 1, start_special },
4622 { "reboot", EQUAL, 1, start_special },
4623 { "default", EQUAL, 1, start_special },
4624 { "rescue", EQUAL, 1, start_special },
4625 { "emergency", EQUAL, 1, start_special },
4626 { "reset-maintenance", MORE, 1, reset_maintenance },
4627 { "enable", MORE, 2, enable_unit },
4628 { "disable", MORE, 2, enable_unit },
4629 { "is-enabled", MORE, 2, enable_unit }
4639 left = argc - optind;
4642 /* Special rule: no arguments means "list-units" */
4645 if (streq(argv[optind], "help")) {
4650 for (i = 0; i < ELEMENTSOF(verbs); i++)
4651 if (streq(argv[optind], verbs[i].verb))
4654 if (i >= ELEMENTSOF(verbs)) {
4655 log_error("Unknown operation %s", argv[optind]);
4660 switch (verbs[i].argc_cmp) {
4663 if (left != verbs[i].argc) {
4664 log_error("Invalid number of arguments.");
4671 if (left < verbs[i].argc) {
4672 log_error("Too few arguments.");
4679 if (left > verbs[i].argc) {
4680 log_error("Too many arguments.");
4687 assert_not_reached("Unknown comparison operator.");
4690 /* Require a bus connection for all operations but
4692 if (!streq(verbs[i].verb, "enable") &&
4693 !streq(verbs[i].verb, "disable") &&
4695 log_error("Failed to get D-Bus connection: %s", error->message);
4699 return verbs[i].dispatch(bus, argv + optind, left);
4702 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
4704 struct msghdr msghdr;
4706 union sockaddr_union sockaddr;
4707 struct ucred *ucred;
4709 struct cmsghdr cmsghdr;
4710 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
4712 struct shutdownd_command c;
4720 strncpy(c.wall_message, message, sizeof(c.wall_message));
4722 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4726 sockaddr.sa.sa_family = AF_UNIX;
4727 sockaddr.un.sun_path[0] = 0;
4728 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
4731 iovec.iov_base = (char*) &c;
4732 iovec.iov_len = sizeof(c);
4735 control.cmsghdr.cmsg_level = SOL_SOCKET;
4736 control.cmsghdr.cmsg_type = SCM_CREDENTIALS;
4737 control.cmsghdr.cmsg_len = CMSG_LEN(sizeof(struct ucred));
4739 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
4740 ucred->pid = getpid();
4741 ucred->uid = getuid();
4742 ucred->gid = getgid();
4745 msghdr.msg_name = &sockaddr;
4746 msghdr.msg_namelen = sizeof(sa_family_t) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
4748 msghdr.msg_iov = &iovec;
4749 msghdr.msg_iovlen = 1;
4750 msghdr.msg_control = &control;
4751 msghdr.msg_controllen = control.cmsghdr.cmsg_len;
4753 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
4754 close_nointr_nofail(fd);
4758 close_nointr_nofail(fd);
4762 static int reload_with_fallback(DBusConnection *bus) {
4765 /* First, try systemd via D-Bus. */
4766 if (daemon_reload(bus, NULL, 0) > 0)
4770 /* Nothing else worked, so let's try signals */
4771 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
4773 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
4774 log_error("kill() failed: %m");
4781 static int start_with_fallback(DBusConnection *bus) {
4784 /* First, try systemd via D-Bus. */
4785 if (start_unit(bus, NULL, 0) > 0)
4789 /* Hmm, talking to systemd via D-Bus didn't work. Then
4790 * let's try to talk to Upstart via D-Bus. */
4791 if (talk_upstart() > 0)
4794 /* Nothing else worked, so let's try
4796 if (talk_initctl() > 0)
4799 log_error("Failed to talk to init daemon.");
4803 warn_wall(arg_action);
4807 static int halt_main(DBusConnection *bus) {
4810 if (geteuid() != 0) {
4811 log_error("Must to be root.");
4815 if (arg_force_fsck) {
4816 if ((r = touch("/forcefsck")) < 0)
4817 log_warning("Failed to create /forcefsck: %s", strerror(-r));
4818 } else if (arg_skip_fsck) {
4819 if ((r = touch("/fastboot")) < 0)
4820 log_warning("Failed to create /fastboot: %s", strerror(-r));
4825 char date[FORMAT_TIMESTAMP_MAX];
4827 m = strv_join(arg_wall, " ");
4828 r = send_shutdownd(arg_when,
4829 arg_action == ACTION_HALT ? 'H' :
4830 arg_action == ACTION_POWEROFF ? 'P' :
4837 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
4839 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
4840 format_timestamp(date, sizeof(date), arg_when));
4845 if (!arg_dry && !arg_immediate)
4846 return start_with_fallback(bus);
4849 if (sd_booted() > 0)
4850 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
4851 else if ((r = utmp_put_shutdown(0)) < 0)
4852 log_warning("Failed to write utmp record: %s", strerror(-r));
4861 /* Make sure C-A-D is handled by the kernel from this
4863 reboot(RB_ENABLE_CAD);
4865 switch (arg_action) {
4868 log_info("Halting.");
4869 reboot(RB_HALT_SYSTEM);
4872 case ACTION_POWEROFF:
4873 log_info("Powering off.");
4874 reboot(RB_POWER_OFF);
4878 log_info("Rebooting.");
4879 reboot(RB_AUTOBOOT);
4883 assert_not_reached("Unknown halt action.");
4886 /* We should never reach this. */
4890 static int runlevel_main(void) {
4891 int r, runlevel, previous;
4893 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
4894 printf("unknown\n");
4899 previous <= 0 ? 'N' : previous,
4900 runlevel <= 0 ? 'N' : runlevel);
4905 int main(int argc, char*argv[]) {
4907 DBusConnection *bus = NULL;
4910 dbus_error_init(&error);
4912 log_parse_environment();
4915 if ((r = parse_argv(argc, argv)) < 0)
4922 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
4923 * let's shortcut this */
4924 if (arg_action == ACTION_RUNLEVEL) {
4925 retval = runlevel_main() < 0;
4929 bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
4931 switch (arg_action) {
4933 case ACTION_SYSTEMCTL: {
4934 retval = systemctl_main(bus, argc, argv, &error) < 0;
4939 case ACTION_POWEROFF:
4941 retval = halt_main(bus) < 0;
4944 case ACTION_RUNLEVEL2:
4945 case ACTION_RUNLEVEL3:
4946 case ACTION_RUNLEVEL4:
4947 case ACTION_RUNLEVEL5:
4949 case ACTION_EMERGENCY:
4950 case ACTION_DEFAULT:
4951 retval = start_with_fallback(bus) < 0;
4956 retval = reload_with_fallback(bus) < 0;
4959 case ACTION_CANCEL_SHUTDOWN:
4960 retval = send_shutdownd(0, 0, false, NULL) < 0;
4963 case ACTION_INVALID:
4964 case ACTION_RUNLEVEL:
4966 assert_not_reached("Unknown action");
4972 dbus_connection_close(bus);
4973 dbus_connection_unref(bus);
4976 dbus_error_free(&error);
4980 strv_free(arg_property);