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>
36 #include <dbus/dbus.h>
42 #include "utmp-wtmp.h"
46 #include "dbus-common.h"
47 #include "cgroup-show.h"
48 #include "cgroup-util.h"
50 #include "path-lookup.h"
51 #include "conf-parser.h"
52 #include "sd-daemon.h"
53 #include "shutdownd.h"
54 #include "exit-status.h"
55 #include "bus-errors.h"
57 #include "unit-name.h"
59 static const char *arg_type = NULL;
60 static char **arg_property = NULL;
61 static bool arg_all = false;
62 static bool arg_fail = false;
63 static bool arg_session = false;
64 static bool arg_global = false;
65 static bool arg_immediate = false;
66 static bool arg_no_block = false;
67 static bool arg_no_wtmp = false;
68 static bool arg_no_sync = false;
69 static bool arg_no_wall = false;
70 static bool arg_no_reload = false;
71 static bool arg_dry = false;
72 static bool arg_quiet = false;
73 static bool arg_full = false;
74 static bool arg_force = false;
75 static bool arg_defaults = false;
76 static char **arg_wall = NULL;
77 static const char *arg_kill_who = NULL;
78 static const char *arg_kill_mode = NULL;
79 static int arg_signal = SIGTERM;
80 static usec_t arg_when = 0;
99 ACTION_CANCEL_SHUTDOWN,
101 } arg_action = ACTION_SYSTEMCTL;
108 static bool private_bus = false;
110 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
112 static bool on_tty(void) {
115 if (_unlikely_(t < 0))
116 t = isatty(STDOUT_FILENO) > 0;
121 static const char *ansi_highlight(bool b) {
126 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
129 static const char *ansi_highlight_green(bool b) {
134 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
137 static bool error_is_no_service(const DBusError *error) {
140 if (!dbus_error_is_set(error))
143 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
146 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
149 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
152 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
155 if (!dbus_error_is_set(error))
158 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
159 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
160 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
161 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
162 return EXIT_NOPERMISSION;
164 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
165 return EXIT_NOTINSTALLED;
167 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
168 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
169 return EXIT_NOTIMPLEMENTED;
171 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
172 return EXIT_NOTCONFIGURED;
180 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
185 if (dbus_message_iter_get_arg_type(iter) != type)
188 dbus_message_iter_get_basic(iter, data);
190 if (!dbus_message_iter_next(iter) != !next)
196 static void warn_wall(enum action action) {
197 static const char *table[_ACTION_MAX] = {
198 [ACTION_HALT] = "The system is going down for system halt NOW!",
199 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
200 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
201 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
202 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
203 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
212 if (!(p = strv_join(arg_wall, " "))) {
213 log_error("Failed to join strings.");
229 utmp_wall(table[action]);
234 const char *description;
235 const char *load_state;
236 const char *active_state;
237 const char *sub_state;
238 const char *following;
239 const char *unit_path;
241 const char *job_type;
242 const char *job_path;
245 static int compare_unit_info(const void *a, const void *b) {
247 const struct unit_info *u = a, *v = b;
249 d1 = strrchr(u->id, '.');
250 d2 = strrchr(v->id, '.');
255 if ((r = strcasecmp(d1, d2)) != 0)
259 return strcasecmp(u->id, v->id);
262 static bool output_show_job(const struct unit_info *u) {
265 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
266 streq(dot+1, arg_type))) &&
267 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0);
270 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
271 unsigned active_len, sub_len, job_len, n_shown = 0;
272 const struct unit_info *u;
274 active_len = sizeof("ACTIVE")-1;
275 sub_len = sizeof("SUB")-1;
276 job_len = sizeof("JOB")-1;
278 for (u = unit_infos; u < unit_infos + c; u++) {
279 if (!output_show_job(u))
282 active_len = MAX(active_len, strlen(u->active_state));
283 sub_len = MAX(sub_len, strlen(u->sub_state));
285 job_len = MAX(job_len, strlen(u->job_type));
289 printf("%-25s %-6s %-*s %-*s %-*s", "UNIT", "LOAD",
290 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
291 if (columns() >= 80+12 || arg_full)
292 printf(" %s\n", "DESCRIPTION");
297 for (u = unit_infos; u < unit_infos + c; u++) {
300 const char *on_loaded, *off_loaded;
301 const char *on_active, *off_active;
303 if (!output_show_job(u))
308 if (!streq(u->load_state, "loaded") &&
309 !streq(u->load_state, "banned")) {
310 on_loaded = ansi_highlight(true);
311 off_loaded = ansi_highlight(false);
313 on_loaded = off_loaded = "";
315 if (streq(u->active_state, "failed")) {
316 on_active = ansi_highlight(true);
317 off_active = ansi_highlight(false);
319 on_active = off_active = "";
321 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
323 printf("%-25s %s%-6s%s %s%-*s %-*s%s%n",
325 on_loaded, u->load_state, off_loaded,
326 on_active, active_len, u->active_state,
327 sub_len, u->sub_state, off_active,
332 a -= strlen(on_loaded) + strlen(off_loaded);
333 a -= strlen(on_active) + strlen(off_active);
336 printf(" %-*s", job_len, u->job_type);
340 if (a + b + 1 < columns()) {
342 printf(" %-*s", job_len, "");
345 printf(" %s", u->description);
347 printf(" %.*s", columns() - a - b - 1, u->description);
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", n_shown);
362 printf("\n%u units listed. Pass --all to see inactive units, too.\n", n_shown);
366 static int list_units(DBusConnection *bus, char **args, unsigned n) {
367 DBusMessage *m = NULL, *reply = NULL;
370 DBusMessageIter iter, sub, sub2;
371 unsigned c = 0, n_units = 0;
372 struct unit_info *unit_infos = NULL;
374 dbus_error_init(&error);
378 if (!(m = dbus_message_new_method_call(
379 "org.freedesktop.systemd1",
380 "/org/freedesktop/systemd1",
381 "org.freedesktop.systemd1.Manager",
383 log_error("Could not allocate message.");
387 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
388 log_error("Failed to issue method call: %s", bus_error_message(&error));
393 if (!dbus_message_iter_init(reply, &iter) ||
394 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
395 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
396 log_error("Failed to parse reply.");
401 dbus_message_iter_recurse(&iter, &sub);
403 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
406 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
407 log_error("Failed to parse reply.");
415 n_units = MAX(2*c, 16);
416 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
419 log_error("Failed to allocate unit array.");
429 dbus_message_iter_recurse(&sub, &sub2);
431 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
432 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
433 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
434 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
435 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
436 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
437 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
438 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
439 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
440 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
441 log_error("Failed to parse reply.");
446 dbus_message_iter_next(&sub);
450 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
451 output_units_list(unit_infos, c);
457 dbus_message_unref(m);
460 dbus_message_unref(reply);
464 dbus_error_free(&error);
469 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
470 static const char * const colors[] = {
471 "Requires", "[color=\"black\"]",
472 "RequiresOverridable", "[color=\"black\"]",
473 "Requisite", "[color=\"darkblue\"]",
474 "RequisiteOverridable", "[color=\"darkblue\"]",
475 "Wants", "[color=\"darkgrey\"]",
476 "Conflicts", "[color=\"red\"]",
477 "ConflictedBy", "[color=\"red\"]",
478 "After", "[color=\"green\"]"
481 const char *c = NULL;
488 for (i = 0; i < ELEMENTSOF(colors); i += 2)
489 if (streq(colors[i], prop)) {
497 if (arg_dot != DOT_ALL)
498 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
501 switch (dbus_message_iter_get_arg_type(iter)) {
503 case DBUS_TYPE_ARRAY:
505 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
508 dbus_message_iter_recurse(iter, &sub);
510 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
513 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
514 dbus_message_iter_get_basic(&sub, &s);
515 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
517 dbus_message_iter_next(&sub);
527 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
528 DBusMessage *m = NULL, *reply = NULL;
529 const char *interface = "org.freedesktop.systemd1.Unit";
532 DBusMessageIter iter, sub, sub2, sub3;
537 dbus_error_init(&error);
539 if (!(m = dbus_message_new_method_call(
540 "org.freedesktop.systemd1",
542 "org.freedesktop.DBus.Properties",
544 log_error("Could not allocate message.");
549 if (!dbus_message_append_args(m,
550 DBUS_TYPE_STRING, &interface,
551 DBUS_TYPE_INVALID)) {
552 log_error("Could not append arguments to message.");
557 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
558 log_error("Failed to issue method call: %s", bus_error_message(&error));
563 if (!dbus_message_iter_init(reply, &iter) ||
564 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
565 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
566 log_error("Failed to parse reply.");
571 dbus_message_iter_recurse(&iter, &sub);
573 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
576 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
577 log_error("Failed to parse reply.");
582 dbus_message_iter_recurse(&sub, &sub2);
584 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
585 log_error("Failed to parse reply.");
590 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
591 log_error("Failed to parse reply.");
596 dbus_message_iter_recurse(&sub2, &sub3);
598 if (dot_one_property(name, prop, &sub3)) {
599 log_error("Failed to parse reply.");
604 dbus_message_iter_next(&sub);
611 dbus_message_unref(m);
614 dbus_message_unref(reply);
616 dbus_error_free(&error);
621 static int dot(DBusConnection *bus, char **args, unsigned n) {
622 DBusMessage *m = NULL, *reply = NULL;
625 DBusMessageIter iter, sub, sub2;
627 dbus_error_init(&error);
631 if (!(m = dbus_message_new_method_call(
632 "org.freedesktop.systemd1",
633 "/org/freedesktop/systemd1",
634 "org.freedesktop.systemd1.Manager",
636 log_error("Could not allocate message.");
640 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
641 log_error("Failed to issue method call: %s", bus_error_message(&error));
646 if (!dbus_message_iter_init(reply, &iter) ||
647 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
648 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
649 log_error("Failed to parse reply.");
654 printf("digraph systemd {\n");
656 dbus_message_iter_recurse(&iter, &sub);
657 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
658 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
660 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
661 log_error("Failed to parse reply.");
666 dbus_message_iter_recurse(&sub, &sub2);
668 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
669 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
670 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
671 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
672 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
673 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
674 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
675 log_error("Failed to parse reply.");
680 if ((r = dot_one(bus, id, unit_path)) < 0)
683 /* printf("\t\"%s\";\n", id); */
684 dbus_message_iter_next(&sub);
689 log_info(" Color legend: black = Requires\n"
690 " dark blue = Requisite\n"
691 " dark grey = Wants\n"
695 if (isatty(fileno(stdout)))
696 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
697 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
703 dbus_message_unref(m);
706 dbus_message_unref(reply);
708 dbus_error_free(&error);
713 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
714 DBusMessage *m = NULL, *reply = NULL;
717 DBusMessageIter iter, sub, sub2;
720 dbus_error_init(&error);
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.");
733 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
734 log_error("Failed to issue method call: %s", bus_error_message(&error));
739 if (!dbus_message_iter_init(reply, &iter) ||
740 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
741 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
742 log_error("Failed to parse reply.");
747 dbus_message_iter_recurse(&iter, &sub);
749 if (isatty(STDOUT_FILENO))
750 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
752 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
753 const char *name, *type, *state, *job_path, *unit_path;
757 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
758 log_error("Failed to parse reply.");
763 dbus_message_iter_recurse(&sub, &sub2);
765 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
766 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
767 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
768 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
769 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
770 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
771 log_error("Failed to parse reply.");
776 e = arg_full ? NULL : ellipsize(name, 25, 33);
777 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
782 dbus_message_iter_next(&sub);
785 if (isatty(STDOUT_FILENO))
786 printf("\n%u jobs listed.\n", k);
792 dbus_message_unref(m);
795 dbus_message_unref(reply);
797 dbus_error_free(&error);
802 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
803 DBusMessage *m = NULL, *reply = NULL;
808 dbus_error_init(&error);
813 for (i = 1; i < n; i++) {
815 if (!(m = dbus_message_new_method_call(
816 "org.freedesktop.systemd1",
817 "/org/freedesktop/systemd1",
818 "org.freedesktop.systemd1.Manager",
820 log_error("Could not allocate message.");
825 if (!dbus_message_append_args(m,
826 DBUS_TYPE_STRING, &args[i],
827 DBUS_TYPE_INVALID)) {
828 log_error("Could not append arguments to message.");
833 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
834 log_error("Failed to issue method call: %s", bus_error_message(&error));
839 dbus_message_unref(m);
840 dbus_message_unref(reply);
849 dbus_message_unref(m);
852 dbus_message_unref(reply);
854 dbus_error_free(&error);
859 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
860 DBusMessage *m = NULL, *reply = NULL;
865 dbus_error_init(&error);
871 return daemon_reload(bus, args, n);
873 for (i = 1; i < n; i++) {
877 if (!(m = dbus_message_new_method_call(
878 "org.freedesktop.systemd1",
879 "/org/freedesktop/systemd1",
880 "org.freedesktop.systemd1.Manager",
882 log_error("Could not allocate message.");
887 if ((r = safe_atou(args[i], &id)) < 0) {
888 log_error("Failed to parse job id: %s", strerror(-r));
892 assert_cc(sizeof(uint32_t) == sizeof(id));
893 if (!dbus_message_append_args(m,
894 DBUS_TYPE_UINT32, &id,
895 DBUS_TYPE_INVALID)) {
896 log_error("Could not append arguments to message.");
901 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
902 log_error("Failed to issue method call: %s", bus_error_message(&error));
907 if (!dbus_message_get_args(reply, &error,
908 DBUS_TYPE_OBJECT_PATH, &path,
909 DBUS_TYPE_INVALID)) {
910 log_error("Failed to parse reply: %s", bus_error_message(&error));
915 dbus_message_unref(m);
916 if (!(m = dbus_message_new_method_call(
917 "org.freedesktop.systemd1",
919 "org.freedesktop.systemd1.Job",
921 log_error("Could not allocate message.");
926 dbus_message_unref(reply);
927 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
928 log_error("Failed to issue method call: %s", bus_error_message(&error));
933 dbus_message_unref(m);
934 dbus_message_unref(reply);
942 dbus_message_unref(m);
945 dbus_message_unref(reply);
947 dbus_error_free(&error);
952 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
953 DBusMessage *m = NULL, *reply = NULL;
954 dbus_bool_t b = FALSE;
955 DBusMessageIter iter, sub;
957 *interface = "org.freedesktop.systemd1.Unit",
958 *property = "NeedDaemonReload",
961 /* We ignore all errors here, since this is used to show a warning only */
963 if (!(m = dbus_message_new_method_call(
964 "org.freedesktop.systemd1",
965 "/org/freedesktop/systemd1",
966 "org.freedesktop.systemd1.Manager",
970 if (!dbus_message_append_args(m,
971 DBUS_TYPE_STRING, &unit,
975 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
978 if (!dbus_message_get_args(reply, NULL,
979 DBUS_TYPE_OBJECT_PATH, &path,
983 dbus_message_unref(m);
984 if (!(m = dbus_message_new_method_call(
985 "org.freedesktop.systemd1",
987 "org.freedesktop.DBus.Properties",
991 if (!dbus_message_append_args(m,
992 DBUS_TYPE_STRING, &interface,
993 DBUS_TYPE_STRING, &property,
994 DBUS_TYPE_INVALID)) {
998 dbus_message_unref(reply);
999 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1002 if (!dbus_message_iter_init(reply, &iter) ||
1003 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1006 dbus_message_iter_recurse(&iter, &sub);
1008 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1011 dbus_message_iter_get_basic(&sub, &b);
1015 dbus_message_unref(m);
1018 dbus_message_unref(reply);
1023 typedef struct WaitData {
1028 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1036 dbus_error_init(&error);
1038 log_debug("Got D-Bus request: %s.%s() on %s",
1039 dbus_message_get_interface(message),
1040 dbus_message_get_member(message),
1041 dbus_message_get_path(message));
1043 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1044 log_error("Warning! D-Bus connection terminated.");
1045 dbus_connection_close(connection);
1047 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1050 dbus_bool_t success = true;
1052 if (!dbus_message_get_args(message, &error,
1053 DBUS_TYPE_UINT32, &id,
1054 DBUS_TYPE_OBJECT_PATH, &path,
1055 DBUS_TYPE_BOOLEAN, &success,
1057 log_error("Failed to parse message: %s", bus_error_message(&error));
1061 if ((p = set_remove(d->set, (char*) path)))
1069 dbus_error_free(&error);
1070 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1073 static int enable_wait_for_jobs(DBusConnection *bus) {
1081 dbus_error_init(&error);
1082 dbus_bus_add_match(bus,
1084 "sender='org.freedesktop.systemd1',"
1085 "interface='org.freedesktop.systemd1.Manager',"
1086 "member='JobRemoved',"
1087 "path='/org/freedesktop/systemd1'",
1090 if (dbus_error_is_set(&error)) {
1091 log_error("Failed to add match: %s", bus_error_message(&error));
1092 dbus_error_free(&error);
1096 /* This is slightly dirty, since we don't undo the match registrations. */
1100 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1111 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1112 log_error("Failed to add filter.");
1117 while (!set_isempty(s) &&
1118 dbus_connection_read_write_dispatch(bus, -1))
1121 if (!arg_quiet && d.failed)
1122 log_error("Job failed, see system logs for details.");
1124 r = d.failed ? -EIO : 0;
1127 /* This is slightly dirty, since we don't undo the filter registration. */
1132 static int start_unit_one(
1133 DBusConnection *bus,
1140 DBusMessage *m = NULL, *reply = NULL;
1149 assert(arg_no_block || s);
1151 if (!(m = dbus_message_new_method_call(
1152 "org.freedesktop.systemd1",
1153 "/org/freedesktop/systemd1",
1154 "org.freedesktop.systemd1.Manager",
1156 log_error("Could not allocate message.");
1161 if (!dbus_message_append_args(m,
1162 DBUS_TYPE_STRING, &name,
1163 DBUS_TYPE_STRING, &mode,
1164 DBUS_TYPE_INVALID)) {
1165 log_error("Could not append arguments to message.");
1170 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1172 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1173 /* There's always a fallback possible for
1174 * legacy actions. */
1179 log_error("Failed to issue method call: %s", bus_error_message(error));
1184 if (!dbus_message_get_args(reply, error,
1185 DBUS_TYPE_OBJECT_PATH, &path,
1186 DBUS_TYPE_INVALID)) {
1187 log_error("Failed to parse reply: %s", bus_error_message(error));
1192 if (need_daemon_reload(bus, name))
1193 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1194 arg_session ? "--session" : "--system");
1196 if (!arg_no_block) {
1199 if (!(p = strdup(path))) {
1200 log_error("Failed to duplicate path.");
1205 if ((r = set_put(s, p)) < 0) {
1207 log_error("Failed to add path to set.");
1216 dbus_message_unref(m);
1219 dbus_message_unref(reply);
1224 static enum action verb_to_action(const char *verb) {
1225 if (streq(verb, "halt"))
1227 else if (streq(verb, "poweroff"))
1228 return ACTION_POWEROFF;
1229 else if (streq(verb, "reboot"))
1230 return ACTION_REBOOT;
1231 else if (streq(verb, "kexec"))
1232 return ACTION_KEXEC;
1233 else if (streq(verb, "rescue"))
1234 return ACTION_RESCUE;
1235 else if (streq(verb, "emergency"))
1236 return ACTION_EMERGENCY;
1237 else if (streq(verb, "default"))
1238 return ACTION_DEFAULT;
1239 else if (streq(verb, "exit"))
1242 return ACTION_INVALID;
1245 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1247 static const char * const table[_ACTION_MAX] = {
1248 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1249 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1250 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1251 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1252 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1253 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1254 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1255 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1256 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1257 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1258 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1259 [ACTION_EXIT] = SPECIAL_EXIT_TARGET
1264 const char *method, *mode, *one_name;
1268 dbus_error_init(&error);
1272 if (arg_action == ACTION_SYSTEMCTL) {
1274 streq(args[0], "stop") ? "StopUnit" :
1275 streq(args[0], "reload") ? "ReloadUnit" :
1276 streq(args[0], "restart") ? "RestartUnit" :
1277 streq(args[0], "try-restart") ||
1278 streq(args[0], "condrestart") ? "TryRestartUnit" :
1279 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1280 streq(args[0], "reload-or-try-restart") ||
1281 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1285 (streq(args[0], "isolate") ||
1286 streq(args[0], "rescue") ||
1287 streq(args[0], "emergency")) ? "isolate" :
1291 one_name = table[verb_to_action(args[0])];
1294 assert(arg_action < ELEMENTSOF(table));
1295 assert(table[arg_action]);
1297 method = "StartUnit";
1299 mode = (arg_action == ACTION_EMERGENCY ||
1300 arg_action == ACTION_RESCUE ||
1301 arg_action == ACTION_RUNLEVEL2 ||
1302 arg_action == ACTION_RUNLEVEL3 ||
1303 arg_action == ACTION_RUNLEVEL4 ||
1304 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1306 one_name = table[arg_action];
1309 if (!arg_no_block) {
1310 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1311 log_error("Could not watch jobs: %s", strerror(-ret));
1315 if (!(s = set_new(string_hash_func, string_compare_func))) {
1316 log_error("Failed to allocate set.");
1323 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1326 for (i = 1; i < n; i++)
1327 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1328 ret = translate_bus_error_to_exit_status(r, &error);
1329 dbus_error_free(&error);
1334 if ((r = wait_for_jobs(bus, s)) < 0) {
1343 dbus_error_free(&error);
1348 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1355 (streq(args[0], "halt") ||
1356 streq(args[0], "poweroff") ||
1357 streq(args[0], "reboot") ||
1358 streq(args[0], "kexec") ||
1359 streq(args[0], "exit")))
1360 return daemon_reload(bus, args, n);
1362 r = start_unit(bus, args, n);
1365 warn_wall(verb_to_action(args[0]));
1370 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1371 DBusMessage *m = NULL, *reply = NULL;
1373 *interface = "org.freedesktop.systemd1.Unit",
1374 *property = "ActiveState";
1375 int r = 3; /* According to LSB: "program is not running" */
1382 dbus_error_init(&error);
1384 for (i = 1; i < n; i++) {
1385 const char *path = NULL;
1387 DBusMessageIter iter, sub;
1389 if (!(m = dbus_message_new_method_call(
1390 "org.freedesktop.systemd1",
1391 "/org/freedesktop/systemd1",
1392 "org.freedesktop.systemd1.Manager",
1394 log_error("Could not allocate message.");
1399 if (!dbus_message_append_args(m,
1400 DBUS_TYPE_STRING, &args[i],
1401 DBUS_TYPE_INVALID)) {
1402 log_error("Could not append arguments to message.");
1407 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1409 /* Hmm, cannot figure out anything about this unit... */
1413 dbus_error_free(&error);
1414 dbus_message_unref(m);
1418 if (!dbus_message_get_args(reply, &error,
1419 DBUS_TYPE_OBJECT_PATH, &path,
1420 DBUS_TYPE_INVALID)) {
1421 log_error("Failed to parse reply: %s", bus_error_message(&error));
1426 dbus_message_unref(m);
1427 if (!(m = dbus_message_new_method_call(
1428 "org.freedesktop.systemd1",
1430 "org.freedesktop.DBus.Properties",
1432 log_error("Could not allocate message.");
1437 if (!dbus_message_append_args(m,
1438 DBUS_TYPE_STRING, &interface,
1439 DBUS_TYPE_STRING, &property,
1440 DBUS_TYPE_INVALID)) {
1441 log_error("Could not append arguments to message.");
1446 dbus_message_unref(reply);
1447 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1448 log_error("Failed to issue method call: %s", bus_error_message(&error));
1453 if (!dbus_message_iter_init(reply, &iter) ||
1454 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1455 log_error("Failed to parse reply.");
1460 dbus_message_iter_recurse(&iter, &sub);
1462 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1463 log_error("Failed to parse reply.");
1468 dbus_message_iter_get_basic(&sub, &state);
1473 if (streq(state, "active") || streq(state, "reloading"))
1476 dbus_message_unref(m);
1477 dbus_message_unref(reply);
1483 dbus_message_unref(m);
1486 dbus_message_unref(reply);
1488 dbus_error_free(&error);
1493 static int kill_unit(DBusConnection *bus, char **args, unsigned n) {
1494 DBusMessage *m = NULL, *reply = NULL;
1502 dbus_error_init(&error);
1505 arg_kill_who = "all";
1508 arg_kill_mode = streq(arg_kill_who, "all") ? "control-group" : "process";
1510 for (i = 1; i < n; i++) {
1512 if (!(m = dbus_message_new_method_call(
1513 "org.freedesktop.systemd1",
1514 "/org/freedesktop/systemd1",
1515 "org.freedesktop.systemd1.Manager",
1517 log_error("Could not allocate message.");
1522 if (!dbus_message_append_args(m,
1523 DBUS_TYPE_STRING, &args[i],
1524 DBUS_TYPE_STRING, &arg_kill_who,
1525 DBUS_TYPE_STRING, &arg_kill_mode,
1526 DBUS_TYPE_INT32, &arg_signal,
1527 DBUS_TYPE_INVALID)) {
1528 log_error("Could not append arguments to message.");
1533 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1534 log_error("Failed to issue method call: %s", bus_error_message(&error));
1535 dbus_error_free(&error);
1539 dbus_message_unref(m);
1542 dbus_message_unref(reply);
1548 dbus_message_unref(m);
1551 dbus_message_unref(reply);
1553 dbus_error_free(&error);
1558 typedef struct ExecStatusInfo {
1564 usec_t start_timestamp;
1565 usec_t exit_timestamp;
1570 LIST_FIELDS(struct ExecStatusInfo, exec);
1573 static void exec_status_info_free(ExecStatusInfo *i) {
1581 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1582 uint64_t start_timestamp, exit_timestamp;
1583 DBusMessageIter sub2, sub3;
1587 int32_t code, status;
1593 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1596 dbus_message_iter_recurse(sub, &sub2);
1598 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1601 if (!(i->path = strdup(path)))
1604 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1605 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1609 dbus_message_iter_recurse(&sub2, &sub3);
1610 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1611 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1612 dbus_message_iter_next(&sub3);
1617 if (!(i->argv = new0(char*, n+1)))
1621 dbus_message_iter_recurse(&sub2, &sub3);
1622 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1625 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1626 dbus_message_iter_get_basic(&sub3, &s);
1627 dbus_message_iter_next(&sub3);
1629 if (!(i->argv[n++] = strdup(s)))
1633 if (!dbus_message_iter_next(&sub2) ||
1634 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1635 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1636 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1637 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1638 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1639 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1643 i->start_timestamp = (usec_t) start_timestamp;
1644 i->exit_timestamp = (usec_t) exit_timestamp;
1645 i->pid = (pid_t) pid;
1652 typedef struct UnitStatusInfo {
1654 const char *load_state;
1655 const char *active_state;
1656 const char *sub_state;
1658 const char *description;
1659 const char *following;
1662 const char *default_control_group;
1664 usec_t inactive_exit_timestamp;
1665 usec_t active_enter_timestamp;
1666 usec_t active_exit_timestamp;
1667 usec_t inactive_enter_timestamp;
1669 bool need_daemon_reload;
1674 const char *status_text;
1676 #ifdef HAVE_SYSV_COMPAT
1680 usec_t start_timestamp;
1681 usec_t exit_timestamp;
1683 int exit_code, exit_status;
1686 unsigned n_accepted;
1687 unsigned n_connections;
1691 const char *sysfs_path;
1693 /* Mount, Automount */
1699 LIST_HEAD(ExecStatusInfo, exec);
1702 static void print_status_info(UnitStatusInfo *i) {
1704 const char *on, *off, *ss;
1706 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1707 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1711 /* This shows pretty information about a unit. See
1712 * print_property() for a low-level property printer */
1714 printf("%s", strna(i->id));
1716 if (i->description && !streq_ptr(i->id, i->description))
1717 printf(" - %s", i->description);
1722 printf("\t Follow: unit currently follows state of %s\n", i->following);
1724 if (streq_ptr(i->load_state, "failed") ||
1725 streq_ptr(i->load_state, "banned")) {
1726 on = ansi_highlight(true);
1727 off = ansi_highlight(false);
1732 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1734 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1736 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1738 if (streq_ptr(i->active_state, "failed")) {
1739 on = ansi_highlight(true);
1740 off = ansi_highlight(false);
1741 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1742 on = ansi_highlight_green(true);
1743 off = ansi_highlight_green(false);
1748 printf("\t Active: %s%s (%s)%s",
1750 strna(i->active_state),
1754 printf("\t Active: %s%s%s",
1756 strna(i->active_state),
1759 timestamp = (streq_ptr(i->active_state, "active") ||
1760 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1761 (streq_ptr(i->active_state, "inactive") ||
1762 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1763 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1764 i->active_exit_timestamp;
1766 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1767 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1770 printf(" since %s; %s\n", s2, s1);
1772 printf(" since %s\n", s2);
1777 printf("\t Device: %s\n", i->sysfs_path);
1779 printf("\t Where: %s\n", i->where);
1781 printf("\t What: %s\n", i->what);
1784 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1786 LIST_FOREACH(exec, p, i->exec) {
1789 /* Only show exited processes here */
1793 t = strv_join(p->argv, " ");
1794 printf("\t Process: %u (%s, code=%s, ", p->pid, strna(t), sigchld_code_to_string(p->code));
1797 if (p->code == CLD_EXITED) {
1800 printf("status=%i", p->status);
1802 #ifdef HAVE_SYSV_COMPAT
1803 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1805 if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1810 printf("signal=%s", signal_to_string(p->status));
1813 if (i->main_pid == p->pid &&
1814 i->start_timestamp == p->start_timestamp &&
1815 i->exit_timestamp == p->start_timestamp)
1816 /* Let's not show this twice */
1819 if (p->pid == i->control_pid)
1823 if (i->main_pid > 0 || i->control_pid > 0) {
1826 if (i->main_pid > 0) {
1827 printf("Main PID: %u", (unsigned) i->main_pid);
1831 get_process_name(i->main_pid, &t);
1836 } else if (i->exit_code > 0) {
1837 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1839 if (i->exit_code == CLD_EXITED) {
1842 printf("status=%i", i->exit_status);
1844 #ifdef HAVE_SYSV_COMPAT
1845 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1847 if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
1852 printf("signal=%s", signal_to_string(i->exit_status));
1857 if (i->main_pid > 0 && i->control_pid > 0)
1860 if (i->control_pid > 0) {
1863 printf(" Control: %u", (unsigned) i->control_pid);
1865 get_process_name(i->control_pid, &t);
1876 printf("\t Status: \"%s\"\n", i->status_text);
1878 if (i->default_control_group) {
1881 printf("\t CGroup: %s\n", i->default_control_group);
1883 if ((c = columns()) > 18)
1888 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
1891 if (i->need_daemon_reload)
1892 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1893 ansi_highlight(true),
1894 ansi_highlight(false),
1895 arg_session ? "--session" : "--system");
1898 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1900 switch (dbus_message_iter_get_arg_type(iter)) {
1902 case DBUS_TYPE_STRING: {
1905 dbus_message_iter_get_basic(iter, &s);
1908 if (streq(name, "Id"))
1910 else if (streq(name, "LoadState"))
1912 else if (streq(name, "ActiveState"))
1913 i->active_state = s;
1914 else if (streq(name, "SubState"))
1916 else if (streq(name, "Description"))
1918 else if (streq(name, "FragmentPath"))
1920 #ifdef HAVE_SYSV_COMPAT
1921 else if (streq(name, "SysVPath")) {
1926 else if (streq(name, "DefaultControlGroup"))
1927 i->default_control_group = s;
1928 else if (streq(name, "StatusText"))
1930 else if (streq(name, "SysFSPath"))
1932 else if (streq(name, "Where"))
1934 else if (streq(name, "What"))
1936 else if (streq(name, "Following"))
1943 case DBUS_TYPE_BOOLEAN: {
1946 dbus_message_iter_get_basic(iter, &b);
1948 if (streq(name, "Accept"))
1950 else if (streq(name, "NeedDaemonReload"))
1951 i->need_daemon_reload = b;
1956 case DBUS_TYPE_UINT32: {
1959 dbus_message_iter_get_basic(iter, &u);
1961 if (streq(name, "MainPID")) {
1963 i->main_pid = (pid_t) u;
1966 } else if (streq(name, "ControlPID"))
1967 i->control_pid = (pid_t) u;
1968 else if (streq(name, "ExecMainPID")) {
1970 i->main_pid = (pid_t) u;
1971 } else if (streq(name, "NAccepted"))
1973 else if (streq(name, "NConnections"))
1974 i->n_connections = u;
1979 case DBUS_TYPE_INT32: {
1982 dbus_message_iter_get_basic(iter, &j);
1984 if (streq(name, "ExecMainCode"))
1985 i->exit_code = (int) j;
1986 else if (streq(name, "ExecMainStatus"))
1987 i->exit_status = (int) j;
1992 case DBUS_TYPE_UINT64: {
1995 dbus_message_iter_get_basic(iter, &u);
1997 if (streq(name, "ExecMainStartTimestamp"))
1998 i->start_timestamp = (usec_t) u;
1999 else if (streq(name, "ExecMainExitTimestamp"))
2000 i->exit_timestamp = (usec_t) u;
2001 else if (streq(name, "ActiveEnterTimestamp"))
2002 i->active_enter_timestamp = (usec_t) u;
2003 else if (streq(name, "InactiveEnterTimestamp"))
2004 i->inactive_enter_timestamp = (usec_t) u;
2005 else if (streq(name, "InactiveExitTimestamp"))
2006 i->inactive_exit_timestamp = (usec_t) u;
2007 else if (streq(name, "ActiveExitTimestamp"))
2008 i->active_exit_timestamp = (usec_t) u;
2013 case DBUS_TYPE_ARRAY: {
2015 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2016 startswith(name, "Exec")) {
2017 DBusMessageIter sub;
2019 dbus_message_iter_recurse(iter, &sub);
2020 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2021 ExecStatusInfo *info;
2024 if (!(info = new0(ExecStatusInfo, 1)))
2027 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2032 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2034 dbus_message_iter_next(&sub);
2045 static int print_property(const char *name, DBusMessageIter *iter) {
2049 /* This is a low-level property printer, see
2050 * print_status_info() for the nicer output */
2052 if (arg_property && !strv_find(arg_property, name))
2055 switch (dbus_message_iter_get_arg_type(iter)) {
2057 case DBUS_TYPE_STRING: {
2059 dbus_message_iter_get_basic(iter, &s);
2061 if (arg_all || s[0])
2062 printf("%s=%s\n", name, s);
2067 case DBUS_TYPE_BOOLEAN: {
2069 dbus_message_iter_get_basic(iter, &b);
2070 printf("%s=%s\n", name, yes_no(b));
2075 case DBUS_TYPE_UINT64: {
2077 dbus_message_iter_get_basic(iter, &u);
2079 /* Yes, heuristics! But we can change this check
2080 * should it turn out to not be sufficient */
2082 if (strstr(name, "Timestamp")) {
2083 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
2085 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
2086 printf("%s=%s\n", name, strempty(t));
2087 } else if (strstr(name, "USec")) {
2088 char timespan[FORMAT_TIMESPAN_MAX];
2090 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
2092 printf("%s=%llu\n", name, (unsigned long long) u);
2097 case DBUS_TYPE_UINT32: {
2099 dbus_message_iter_get_basic(iter, &u);
2101 if (strstr(name, "UMask") || strstr(name, "Mode"))
2102 printf("%s=%04o\n", name, u);
2104 printf("%s=%u\n", name, (unsigned) u);
2109 case DBUS_TYPE_INT32: {
2111 dbus_message_iter_get_basic(iter, &i);
2113 printf("%s=%i\n", name, (int) i);
2117 case DBUS_TYPE_DOUBLE: {
2119 dbus_message_iter_get_basic(iter, &d);
2121 printf("%s=%g\n", name, d);
2125 case DBUS_TYPE_STRUCT: {
2126 DBusMessageIter sub;
2127 dbus_message_iter_recurse(iter, &sub);
2129 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2132 dbus_message_iter_get_basic(&sub, &u);
2135 printf("%s=%u\n", name, (unsigned) u);
2137 printf("%s=\n", name);
2140 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2143 dbus_message_iter_get_basic(&sub, &s);
2145 if (arg_all || s[0])
2146 printf("%s=%s\n", name, s);
2154 case DBUS_TYPE_ARRAY:
2156 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2157 DBusMessageIter sub;
2160 dbus_message_iter_recurse(iter, &sub);
2162 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2163 printf("%s=", name);
2165 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2168 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2169 dbus_message_iter_get_basic(&sub, &s);
2170 printf("%s%s", space ? " " : "", s);
2173 dbus_message_iter_next(&sub);
2181 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2182 DBusMessageIter sub;
2184 dbus_message_iter_recurse(iter, &sub);
2186 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2187 printf("%s=", name);
2189 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2192 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2193 dbus_message_iter_get_basic(&sub, &u);
2196 dbus_message_iter_next(&sub);
2204 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2205 DBusMessageIter sub, sub2;
2207 dbus_message_iter_recurse(iter, &sub);
2208 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2209 const char *type, *path;
2211 dbus_message_iter_recurse(&sub, &sub2);
2213 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2214 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2215 printf("%s=%s\n", type, path);
2217 dbus_message_iter_next(&sub);
2222 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2223 DBusMessageIter sub, sub2;
2225 dbus_message_iter_recurse(iter, &sub);
2226 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2228 uint64_t value, next_elapse;
2230 dbus_message_iter_recurse(&sub, &sub2);
2232 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2233 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2234 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2235 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2237 printf("%s={ value=%s ; next_elapse=%s }\n",
2239 format_timespan(timespan1, sizeof(timespan1), value),
2240 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2243 dbus_message_iter_next(&sub);
2248 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2249 DBusMessageIter sub;
2251 dbus_message_iter_recurse(iter, &sub);
2252 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2253 ExecStatusInfo info;
2256 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2257 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2260 t = strv_join(info.argv, " ");
2262 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2266 yes_no(info.ignore),
2267 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2268 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2269 (unsigned) info. pid,
2270 sigchld_code_to_string(info.code),
2272 info.code == CLD_EXITED ? "" : "/",
2273 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2279 strv_free(info.argv);
2281 dbus_message_iter_next(&sub);
2291 printf("%s=[unprintable]\n", name);
2296 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2297 DBusMessage *m = NULL, *reply = NULL;
2298 const char *interface = "";
2301 DBusMessageIter iter, sub, sub2, sub3;
2302 UnitStatusInfo info;
2310 dbus_error_init(&error);
2312 if (!(m = dbus_message_new_method_call(
2313 "org.freedesktop.systemd1",
2315 "org.freedesktop.DBus.Properties",
2317 log_error("Could not allocate message.");
2322 if (!dbus_message_append_args(m,
2323 DBUS_TYPE_STRING, &interface,
2324 DBUS_TYPE_INVALID)) {
2325 log_error("Could not append arguments to message.");
2330 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2331 log_error("Failed to issue method call: %s", bus_error_message(&error));
2336 if (!dbus_message_iter_init(reply, &iter) ||
2337 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2338 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2339 log_error("Failed to parse reply.");
2344 dbus_message_iter_recurse(&iter, &sub);
2351 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2354 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2355 log_error("Failed to parse reply.");
2360 dbus_message_iter_recurse(&sub, &sub2);
2362 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2363 log_error("Failed to parse reply.");
2368 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2369 log_error("Failed to parse reply.");
2374 dbus_message_iter_recurse(&sub2, &sub3);
2376 if (show_properties)
2377 r = print_property(name, &sub3);
2379 r = status_property(name, &sub3, &info);
2382 log_error("Failed to parse reply.");
2387 dbus_message_iter_next(&sub);
2392 if (!show_properties)
2393 print_status_info(&info);
2395 if (!streq_ptr(info.active_state, "active") &&
2396 !streq_ptr(info.active_state, "reloading"))
2397 /* According to LSB: "program not running" */
2400 while ((p = info.exec)) {
2401 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2402 exec_status_info_free(p);
2407 dbus_message_unref(m);
2410 dbus_message_unref(reply);
2412 dbus_error_free(&error);
2417 static int show(DBusConnection *bus, char **args, unsigned n) {
2418 DBusMessage *m = NULL, *reply = NULL;
2422 bool show_properties, new_line = false;
2427 dbus_error_init(&error);
2429 show_properties = !streq(args[0], "status");
2431 if (show_properties && n <= 1) {
2432 /* If not argument is specified inspect the manager
2435 ret = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2439 for (i = 1; i < n; i++) {
2440 const char *path = NULL;
2443 if (safe_atou32(args[i], &id) < 0) {
2445 /* Interpret as unit name */
2447 if (!(m = dbus_message_new_method_call(
2448 "org.freedesktop.systemd1",
2449 "/org/freedesktop/systemd1",
2450 "org.freedesktop.systemd1.Manager",
2452 log_error("Could not allocate message.");
2457 if (!dbus_message_append_args(m,
2458 DBUS_TYPE_STRING, &args[i],
2459 DBUS_TYPE_INVALID)) {
2460 log_error("Could not append arguments to message.");
2465 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2467 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2468 log_error("Failed to issue method call: %s", bus_error_message(&error));
2473 dbus_error_free(&error);
2475 dbus_message_unref(m);
2476 if (!(m = dbus_message_new_method_call(
2477 "org.freedesktop.systemd1",
2478 "/org/freedesktop/systemd1",
2479 "org.freedesktop.systemd1.Manager",
2481 log_error("Could not allocate message.");
2486 if (!dbus_message_append_args(m,
2487 DBUS_TYPE_STRING, &args[i],
2488 DBUS_TYPE_INVALID)) {
2489 log_error("Could not append arguments to message.");
2494 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2495 log_error("Failed to issue method call: %s", bus_error_message(&error));
2497 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2498 ret = 4; /* According to LSB: "program or service status is unknown" */
2505 } else if (show_properties) {
2507 /* Interpret as job id */
2509 if (!(m = dbus_message_new_method_call(
2510 "org.freedesktop.systemd1",
2511 "/org/freedesktop/systemd1",
2512 "org.freedesktop.systemd1.Manager",
2514 log_error("Could not allocate message.");
2519 if (!dbus_message_append_args(m,
2520 DBUS_TYPE_UINT32, &id,
2521 DBUS_TYPE_INVALID)) {
2522 log_error("Could not append arguments to message.");
2527 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2528 log_error("Failed to issue method call: %s", bus_error_message(&error));
2534 /* Interpret as PID */
2536 if (!(m = dbus_message_new_method_call(
2537 "org.freedesktop.systemd1",
2538 "/org/freedesktop/systemd1",
2539 "org.freedesktop.systemd1.Manager",
2541 log_error("Could not allocate message.");
2546 if (!dbus_message_append_args(m,
2547 DBUS_TYPE_UINT32, &id,
2548 DBUS_TYPE_INVALID)) {
2549 log_error("Could not append arguments to message.");
2554 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2555 log_error("Failed to issue method call: %s", bus_error_message(&error));
2561 if (!dbus_message_get_args(reply, &error,
2562 DBUS_TYPE_OBJECT_PATH, &path,
2563 DBUS_TYPE_INVALID)) {
2564 log_error("Failed to parse reply: %s", bus_error_message(&error));
2569 if ((r = show_one(bus, path, show_properties, &new_line)) != 0)
2572 dbus_message_unref(m);
2573 dbus_message_unref(reply);
2579 dbus_message_unref(m);
2582 dbus_message_unref(reply);
2584 dbus_error_free(&error);
2589 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2591 DBusMessage *m = NULL, *reply = NULL;
2596 dbus_error_init(&error);
2598 log_debug("Got D-Bus request: %s.%s() on %s",
2599 dbus_message_get_interface(message),
2600 dbus_message_get_member(message),
2601 dbus_message_get_path(message));
2603 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2604 log_error("Warning! D-Bus connection terminated.");
2605 dbus_connection_close(connection);
2607 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2608 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2609 const char *id, *path;
2611 if (!dbus_message_get_args(message, &error,
2612 DBUS_TYPE_STRING, &id,
2613 DBUS_TYPE_OBJECT_PATH, &path,
2615 log_error("Failed to parse message: %s", bus_error_message(&error));
2616 else if (streq(dbus_message_get_member(message), "UnitNew"))
2617 printf("Unit %s added.\n", id);
2619 printf("Unit %s removed.\n", id);
2621 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2622 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2626 if (!dbus_message_get_args(message, &error,
2627 DBUS_TYPE_UINT32, &id,
2628 DBUS_TYPE_OBJECT_PATH, &path,
2630 log_error("Failed to parse message: %s", bus_error_message(&error));
2631 else if (streq(dbus_message_get_member(message), "JobNew"))
2632 printf("Job %u added.\n", id);
2634 printf("Job %u removed.\n", id);
2637 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2639 const char *path, *interface, *property = "Id";
2640 DBusMessageIter iter, sub;
2642 path = dbus_message_get_path(message);
2644 if (!dbus_message_get_args(message, &error,
2645 DBUS_TYPE_STRING, &interface,
2646 DBUS_TYPE_INVALID)) {
2647 log_error("Failed to parse message: %s", bus_error_message(&error));
2651 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2652 !streq(interface, "org.freedesktop.systemd1.Unit"))
2655 if (!(m = dbus_message_new_method_call(
2656 "org.freedesktop.systemd1",
2658 "org.freedesktop.DBus.Properties",
2660 log_error("Could not allocate message.");
2664 if (!dbus_message_append_args(m,
2665 DBUS_TYPE_STRING, &interface,
2666 DBUS_TYPE_STRING, &property,
2667 DBUS_TYPE_INVALID)) {
2668 log_error("Could not append arguments to message.");
2672 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2673 log_error("Failed to issue method call: %s", bus_error_message(&error));
2677 if (!dbus_message_iter_init(reply, &iter) ||
2678 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2679 log_error("Failed to parse reply.");
2683 dbus_message_iter_recurse(&iter, &sub);
2685 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2688 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2689 log_error("Failed to parse reply.");
2693 dbus_message_iter_get_basic(&sub, &id);
2694 printf("Unit %s changed.\n", id);
2698 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2699 log_error("Failed to parse reply.");
2703 dbus_message_iter_get_basic(&sub, &id);
2704 printf("Job %u changed.\n", id);
2710 dbus_message_unref(m);
2713 dbus_message_unref(reply);
2715 dbus_error_free(&error);
2716 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2720 dbus_message_unref(m);
2723 dbus_message_unref(reply);
2725 dbus_error_free(&error);
2726 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2729 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2730 DBusMessage *m = NULL, *reply = NULL;
2734 dbus_error_init(&error);
2737 dbus_bus_add_match(bus,
2739 "sender='org.freedesktop.systemd1',"
2740 "interface='org.freedesktop.systemd1.Manager',"
2741 "path='/org/freedesktop/systemd1'",
2744 if (dbus_error_is_set(&error)) {
2745 log_error("Failed to add match: %s", bus_error_message(&error));
2750 dbus_bus_add_match(bus,
2752 "sender='org.freedesktop.systemd1',"
2753 "interface='org.freedesktop.DBus.Properties',"
2754 "member='PropertiesChanged'",
2757 if (dbus_error_is_set(&error)) {
2758 log_error("Failed to add match: %s", bus_error_message(&error));
2764 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2765 log_error("Failed to add filter.");
2770 if (!(m = dbus_message_new_method_call(
2771 "org.freedesktop.systemd1",
2772 "/org/freedesktop/systemd1",
2773 "org.freedesktop.systemd1.Manager",
2775 log_error("Could not allocate message.");
2780 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2781 log_error("Failed to issue method call: %s", bus_error_message(&error));
2786 while (dbus_connection_read_write_dispatch(bus, -1))
2793 /* This is slightly dirty, since we don't undo the filter or the matches. */
2796 dbus_message_unref(m);
2799 dbus_message_unref(reply);
2801 dbus_error_free(&error);
2806 static int dump(DBusConnection *bus, char **args, unsigned n) {
2807 DBusMessage *m = NULL, *reply = NULL;
2812 dbus_error_init(&error);
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))) {
2824 log_error("Failed to issue method call: %s", bus_error_message(&error));
2829 if (!dbus_message_get_args(reply, &error,
2830 DBUS_TYPE_STRING, &text,
2831 DBUS_TYPE_INVALID)) {
2832 log_error("Failed to parse reply: %s", bus_error_message(&error));
2837 fputs(text, stdout);
2843 dbus_message_unref(m);
2846 dbus_message_unref(reply);
2848 dbus_error_free(&error);
2853 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2854 DBusMessage *m = NULL, *reply = NULL;
2857 const char *name = "", *path, *id;
2858 dbus_bool_t cleanup = FALSE;
2859 DBusMessageIter iter, sub;
2861 *interface = "org.freedesktop.systemd1.Unit",
2864 dbus_error_init(&error);
2866 if (!(m = dbus_message_new_method_call(
2867 "org.freedesktop.systemd1",
2868 "/org/freedesktop/systemd1",
2869 "org.freedesktop.systemd1.Manager",
2870 "CreateSnapshot"))) {
2871 log_error("Could not allocate message.");
2878 if (!dbus_message_append_args(m,
2879 DBUS_TYPE_STRING, &name,
2880 DBUS_TYPE_BOOLEAN, &cleanup,
2881 DBUS_TYPE_INVALID)) {
2882 log_error("Could not append arguments to message.");
2887 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2888 log_error("Failed to issue method call: %s", bus_error_message(&error));
2893 if (!dbus_message_get_args(reply, &error,
2894 DBUS_TYPE_OBJECT_PATH, &path,
2895 DBUS_TYPE_INVALID)) {
2896 log_error("Failed to parse reply: %s", bus_error_message(&error));
2901 dbus_message_unref(m);
2902 if (!(m = dbus_message_new_method_call(
2903 "org.freedesktop.systemd1",
2905 "org.freedesktop.DBus.Properties",
2907 log_error("Could not allocate message.");
2911 if (!dbus_message_append_args(m,
2912 DBUS_TYPE_STRING, &interface,
2913 DBUS_TYPE_STRING, &property,
2914 DBUS_TYPE_INVALID)) {
2915 log_error("Could not append arguments to message.");
2920 dbus_message_unref(reply);
2921 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2922 log_error("Failed to issue method call: %s", bus_error_message(&error));
2927 if (!dbus_message_iter_init(reply, &iter) ||
2928 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2929 log_error("Failed to parse reply.");
2934 dbus_message_iter_recurse(&iter, &sub);
2936 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2937 log_error("Failed to parse reply.");
2942 dbus_message_iter_get_basic(&sub, &id);
2950 dbus_message_unref(m);
2953 dbus_message_unref(reply);
2955 dbus_error_free(&error);
2960 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2961 DBusMessage *m = NULL, *reply = NULL;
2969 dbus_error_init(&error);
2971 for (i = 1; i < n; i++) {
2972 const char *path = NULL;
2974 if (!(m = dbus_message_new_method_call(
2975 "org.freedesktop.systemd1",
2976 "/org/freedesktop/systemd1",
2977 "org.freedesktop.systemd1.Manager",
2979 log_error("Could not allocate message.");
2984 if (!dbus_message_append_args(m,
2985 DBUS_TYPE_STRING, &args[i],
2986 DBUS_TYPE_INVALID)) {
2987 log_error("Could not append arguments to message.");
2992 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2993 log_error("Failed to issue method call: %s", bus_error_message(&error));
2998 if (!dbus_message_get_args(reply, &error,
2999 DBUS_TYPE_OBJECT_PATH, &path,
3000 DBUS_TYPE_INVALID)) {
3001 log_error("Failed to parse reply: %s", bus_error_message(&error));
3006 dbus_message_unref(m);
3007 if (!(m = dbus_message_new_method_call(
3008 "org.freedesktop.systemd1",
3010 "org.freedesktop.systemd1.Snapshot",
3012 log_error("Could not allocate message.");
3017 dbus_message_unref(reply);
3018 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3019 log_error("Failed to issue method call: %s", bus_error_message(&error));
3024 dbus_message_unref(m);
3025 dbus_message_unref(reply);
3033 dbus_message_unref(m);
3036 dbus_message_unref(reply);
3038 dbus_error_free(&error);
3043 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
3044 DBusMessage *m = NULL, *reply = NULL;
3049 dbus_error_init(&error);
3051 if (arg_action == ACTION_RELOAD)
3053 else if (arg_action == ACTION_REEXEC)
3054 method = "Reexecute";
3056 assert(arg_action == ACTION_SYSTEMCTL);
3059 streq(args[0], "clear-jobs") ||
3060 streq(args[0], "cancel") ? "ClearJobs" :
3061 streq(args[0], "daemon-reexec") ? "Reexecute" :
3062 streq(args[0], "reset-failed") ? "ResetFailed" :
3063 streq(args[0], "halt") ? "Halt" :
3064 streq(args[0], "poweroff") ? "PowerOff" :
3065 streq(args[0], "reboot") ? "Reboot" :
3066 streq(args[0], "kexec") ? "KExec" :
3067 streq(args[0], "exit") ? "Exit" :
3068 /* "daemon-reload" */ "Reload";
3071 if (!(m = dbus_message_new_method_call(
3072 "org.freedesktop.systemd1",
3073 "/org/freedesktop/systemd1",
3074 "org.freedesktop.systemd1.Manager",
3076 log_error("Could not allocate message.");
3080 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3082 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3083 /* There's always a fallback possible for
3084 * legacy actions. */
3089 log_error("Failed to issue method call: %s", bus_error_message(&error));
3098 dbus_message_unref(m);
3101 dbus_message_unref(reply);
3103 dbus_error_free(&error);
3108 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3109 DBusMessage *m = NULL, *reply = NULL;
3115 dbus_error_init(&error);
3118 return daemon_reload(bus, args, n);
3120 for (i = 1; i < n; i++) {
3122 if (!(m = dbus_message_new_method_call(
3123 "org.freedesktop.systemd1",
3124 "/org/freedesktop/systemd1",
3125 "org.freedesktop.systemd1.Manager",
3126 "ResetFailedUnit"))) {
3127 log_error("Could not allocate message.");
3132 if (!dbus_message_append_args(m,
3133 DBUS_TYPE_STRING, args + i,
3134 DBUS_TYPE_INVALID)) {
3135 log_error("Could not append arguments to message.");
3140 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3141 log_error("Failed to issue method call: %s", bus_error_message(&error));
3146 dbus_message_unref(m);
3147 dbus_message_unref(reply);
3155 dbus_message_unref(m);
3158 dbus_message_unref(reply);
3160 dbus_error_free(&error);
3165 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3166 DBusMessage *m = NULL, *reply = NULL;
3168 DBusMessageIter iter, sub, sub2;
3171 *interface = "org.freedesktop.systemd1.Manager",
3172 *property = "Environment";
3174 dbus_error_init(&error);
3176 if (!(m = dbus_message_new_method_call(
3177 "org.freedesktop.systemd1",
3178 "/org/freedesktop/systemd1",
3179 "org.freedesktop.DBus.Properties",
3181 log_error("Could not allocate message.");
3185 if (!dbus_message_append_args(m,
3186 DBUS_TYPE_STRING, &interface,
3187 DBUS_TYPE_STRING, &property,
3188 DBUS_TYPE_INVALID)) {
3189 log_error("Could not append arguments to message.");
3194 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3195 log_error("Failed to issue method call: %s", bus_error_message(&error));
3200 if (!dbus_message_iter_init(reply, &iter) ||
3201 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3202 log_error("Failed to parse reply.");
3207 dbus_message_iter_recurse(&iter, &sub);
3209 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3210 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3211 log_error("Failed to parse reply.");
3216 dbus_message_iter_recurse(&sub, &sub2);
3218 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3221 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3222 log_error("Failed to parse reply.");
3227 dbus_message_iter_get_basic(&sub2, &text);
3228 printf("%s\n", text);
3230 dbus_message_iter_next(&sub2);
3237 dbus_message_unref(m);
3240 dbus_message_unref(reply);
3242 dbus_error_free(&error);
3247 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3248 DBusMessage *m = NULL, *reply = NULL;
3252 DBusMessageIter iter, sub;
3255 dbus_error_init(&error);
3257 method = streq(args[0], "set-environment")
3259 : "UnsetEnvironment";
3261 if (!(m = dbus_message_new_method_call(
3262 "org.freedesktop.systemd1",
3263 "/org/freedesktop/systemd1",
3264 "org.freedesktop.systemd1.Manager",
3267 log_error("Could not allocate message.");
3271 dbus_message_iter_init_append(m, &iter);
3273 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3274 log_error("Could not append arguments to message.");
3279 for (i = 1; i < n; i++)
3280 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3281 log_error("Could not append arguments to message.");
3286 if (!dbus_message_iter_close_container(&iter, &sub)) {
3287 log_error("Could not append arguments to message.");
3292 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3293 log_error("Failed to issue method call: %s", bus_error_message(&error));
3302 dbus_message_unref(m);
3305 dbus_message_unref(reply);
3307 dbus_error_free(&error);
3320 static Hashmap *will_install = NULL, *have_installed = NULL;
3321 static Set *remove_symlinks_to = NULL;
3322 static unsigned n_symlinks = 0;
3324 static void install_info_free(InstallInfo *i) {
3329 strv_free(i->aliases);
3330 strv_free(i->wanted_by);
3334 static void install_info_hashmap_free(Hashmap *m) {
3337 while ((i = hashmap_steal_first(m)))
3338 install_info_free(i);
3343 static int install_info_add(const char *name) {
3347 assert(will_install);
3349 if (!unit_name_is_valid_no_type(name, true)) {
3350 log_warning("Unit name %s is not a valid unit name.", name);
3354 if (hashmap_get(have_installed, name) ||
3355 hashmap_get(will_install, name))
3358 if (!(i = new0(InstallInfo, 1))) {
3363 if (!(i->name = strdup(name))) {
3368 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3375 install_info_free(i);
3380 static int config_parse_also(
3381 const char *filename,
3383 const char *section,
3397 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3401 if (!(n = strndup(w, l)))
3404 if ((r = install_info_add(n)) < 0) {
3405 log_warning("Cannot install unit %s: %s", n, strerror(-r));
3416 static int mark_symlink_for_removal(const char *p) {
3421 assert(path_is_absolute(p));
3423 if (!remove_symlinks_to)
3426 if (!(n = strdup(p)))
3429 path_kill_slashes(n);
3431 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3433 return r == -EEXIST ? 0 : r;
3439 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3448 if (!(d = fdopendir(fd))) {
3449 close_nointr_nofail(fd);
3455 while ((de = readdir(d))) {
3456 bool is_dir = false, is_link = false;
3458 if (ignore_file(de->d_name))
3461 if (de->d_type == DT_LNK)
3463 else if (de->d_type == DT_DIR)
3465 else if (de->d_type == DT_UNKNOWN) {
3468 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3469 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3476 is_link = S_ISLNK(st.st_mode);
3477 is_dir = S_ISDIR(st.st_mode);
3485 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3486 log_error("Failed to open %s/%s: %m", root, de->d_name);
3493 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3494 log_error("Failed to allocate directory string.");
3495 close_nointr_nofail(nfd);
3500 /* This will close nfd, regardless whether it succeeds or not */
3501 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3507 } else if (is_link) {
3511 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3512 log_error("Failed to allocate symlink string.");
3517 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3518 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3526 if ((c = canonicalize_file_name(dest))) {
3527 /* This might fail if the destination
3528 * is already removed */
3534 path_kill_slashes(dest);
3535 if (set_get(remove_symlinks_to, dest)) {
3538 log_info("rm '%s'", p);
3540 if (unlink(p) < 0) {
3541 log_error("Cannot unlink symlink %s: %m", p);
3546 rmdir_parents(p, config_path);
3547 path_kill_slashes(p);
3549 if (!set_get(remove_symlinks_to, p)) {
3551 if ((r = mark_symlink_for_removal(p)) < 0) {
3570 static int remove_marked_symlinks(const char *config_path) {
3574 assert(config_path);
3576 if (set_size(remove_symlinks_to) <= 0)
3579 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3586 if ((cfd = dup(fd)) < 0) {
3591 /* This takes possession of cfd and closes it */
3592 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3598 close_nointr_nofail(fd);
3603 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3610 if (streq(verb, "enable")) {
3613 mkdir_parents(new_path, 0755);
3615 if (symlink(old_path, new_path) >= 0) {
3618 log_info("ln -s '%s' '%s'", old_path, new_path);
3623 if (errno != EEXIST) {
3624 log_error("Cannot link %s to %s: %m", old_path, new_path);
3628 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3630 if (errno == EINVAL) {
3631 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3635 log_error("readlink() failed: %s", strerror(-r));
3639 if (streq(dest, old_path)) {
3645 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3654 log_info("ln -s '%s' '%s'", old_path, new_path);
3656 if (symlink(old_path, new_path) >= 0)
3659 log_error("Cannot link %s to %s: %m", old_path, new_path);
3662 } else if (streq(verb, "disable")) {
3665 if ((r = mark_symlink_for_removal(old_path)) < 0)
3668 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3669 if (errno == ENOENT)
3672 if (errno == EINVAL) {
3673 log_warning("File %s not a symlink, ignoring.", old_path);
3677 log_error("readlink() failed: %s", strerror(-r));
3681 if (!streq(dest, old_path)) {
3682 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3689 if ((r = mark_symlink_for_removal(new_path)) < 0)
3693 log_info("rm '%s'", new_path);
3695 if (unlink(new_path) >= 0)
3698 log_error("Cannot unlink %s: %m", new_path);
3701 } else if (streq(verb, "is-enabled")) {
3704 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3706 if (errno == ENOENT || errno == EINVAL)
3709 log_error("readlink() failed: %s", strerror(-r));
3713 if (streq(dest, old_path)) {
3721 assert_not_reached("Unknown action.");
3724 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3726 char *alias_path = NULL;
3731 assert(config_path);
3733 STRV_FOREACH(s, i->aliases) {
3736 if (!(alias_path = path_make_absolute(*s, config_path))) {
3737 log_error("Out of memory");
3742 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3745 if (streq(verb, "disable"))
3746 rmdir_parents(alias_path, config_path);
3756 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3758 char *alias_path = NULL;
3763 assert(config_path);
3765 STRV_FOREACH(s, i->wanted_by) {
3766 if (!unit_name_is_valid_no_type(*s, true)) {
3767 log_error("Invalid name %s.", *s);
3775 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3776 log_error("Out of memory");
3781 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3784 if (streq(verb, "disable"))
3785 rmdir_parents(alias_path, config_path);
3796 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3798 const ConfigItem items[] = {
3799 { "Alias", config_parse_strv, &i->aliases, "Install" },
3800 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3801 { "Also", config_parse_also, NULL, "Install" },
3803 { NULL, NULL, NULL, NULL }
3807 char *filename = NULL;
3814 STRV_FOREACH(p, paths->unit_path) {
3817 if (!(filename = path_make_absolute(i->name, *p))) {
3818 log_error("Out of memory");
3822 /* Ensure that we don't follow symlinks */
3823 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3824 if ((f = fdopen(fd, "re")))
3827 if (errno == ELOOP) {
3828 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3833 if (errno != ENOENT) {
3834 log_error("Failed to open %s: %m", filename);
3844 log_error("Couldn't find %s.", i->name);
3850 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3855 n_symlinks += strv_length(i->aliases);
3856 n_symlinks += strv_length(i->wanted_by);
3860 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3863 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3866 if ((r = mark_symlink_for_removal(filename)) < 0)
3869 if ((r = remove_marked_symlinks(config_path)) < 0)
3875 static char *get_config_path(void) {
3877 if (arg_session && arg_global)
3878 return strdup(SESSION_CONFIG_UNIT_PATH);
3883 if (session_config_home(&p) < 0)
3889 return strdup(SYSTEM_CONFIG_UNIT_PATH);
3892 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3896 char *config_path = NULL;
3899 const char *verb = args[0];
3901 dbus_error_init(&error);
3904 if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3905 log_error("Failed to determine lookup paths: %s", strerror(-r));
3909 if (!(config_path = get_config_path())) {
3910 log_error("Failed to determine config path");
3915 will_install = hashmap_new(string_hash_func, string_compare_func);
3916 have_installed = hashmap_new(string_hash_func, string_compare_func);
3918 if (!will_install || !have_installed) {
3919 log_error("Failed to allocate unit sets.");
3924 if (!arg_defaults && streq(verb, "disable"))
3925 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3926 log_error("Failed to allocate symlink sets.");
3931 for (j = 1; j < n; j++)
3932 if ((r = install_info_add(args[j])) < 0) {
3933 log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
3937 while ((i = hashmap_first(will_install))) {
3940 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3942 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3950 /* In test mode and found something */
3956 if (streq(verb, "is-enabled"))
3957 r = r > 0 ? 0 : -ENOENT;
3959 if (n_symlinks <= 0)
3960 log_warning("Unit files contain no applicable installation information. Ignoring.");
3963 /* Don't try to reload anything if the user asked us to not do this */
3965 /* Don't try to reload anything when updating a unit globally */
3967 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3968 (arg_session || sd_booted() > 0) &&
3969 /* Don't try to reload anything if we are running in a chroot environment */
3970 (arg_session || running_in_chroot() <= 0) ) {
3973 if ((q = daemon_reload(bus, args, n)) < 0)
3979 install_info_hashmap_free(will_install);
3980 install_info_hashmap_free(have_installed);
3982 set_free_free(remove_symlinks_to);
3984 lookup_paths_free(&paths);
3991 static int systemctl_help(void) {
3993 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3994 "Send control commands to or query the systemd manager.\n\n"
3995 " -h --help Show this help\n"
3996 " --version Show package version\n"
3997 " -t --type=TYPE List only units of a particular type\n"
3998 " -p --property=NAME Show only properties by this name\n"
3999 " -a --all Show all units/properties, including dead/empty ones\n"
4000 " --full Don't ellipsize unit names on output\n"
4001 " --fail When queueing a new job, fail if conflicting jobs are\n"
4003 " -q --quiet Suppress output\n"
4004 " --no-block Do not wait until operation finished\n"
4005 " --system Connect to system bus\n"
4006 " --session Connect to session bus\n"
4007 " --order When generating graph for dot, show only order\n"
4008 " --require When generating graph for dot, show only requirement\n"
4009 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4010 " --global Enable/disable unit files globally\n"
4011 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4013 " --kill-mode=MODE How to send signal\n"
4014 " --kill-who=WHO Who to send signal to\n"
4015 " -s --signal=SIGNAL Which signal to send\n"
4016 " -f --force When enabling unit files, override existing symlinks\n"
4017 " When shutting down, execute action immediately\n"
4018 " --defaults When disabling unit files, remove default symlinks only\n\n"
4020 " list-units List units\n"
4021 " start [NAME...] Start (activate) one or more units\n"
4022 " stop [NAME...] Stop (deactivate) one or more units\n"
4023 " reload [NAME...] Reload one or more units\n"
4024 " restart [NAME...] Start or restart one or more units\n"
4025 " try-restart [NAME...] Restart one or more units if active\n"
4026 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4027 " otherwise start or restart\n"
4028 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4029 " otherwise restart if active\n"
4030 " isolate [NAME] Start one unit and stop all others\n"
4031 " kill [NAME...] Send signal to processes of a unit\n"
4032 " is-active [NAME...] Check whether units are active\n"
4033 " status [NAME...|PID...] Show runtime status of one or more units\n"
4034 " show [NAME...|JOB...] Show properties of one or more\n"
4035 " units/jobs or the manager\n"
4036 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4038 " enable [NAME...] Enable one or more unit files\n"
4039 " disable [NAME...] Disable one or more unit files\n"
4040 " is-enabled [NAME...] Check whether unit files are enabled\n"
4041 " load [NAME...] Load one or more units\n"
4042 " list-jobs List jobs\n"
4043 " cancel [JOB...] Cancel all, one, or more jobs\n"
4044 " monitor Monitor unit/job changes\n"
4045 " dump Dump server status\n"
4046 " dot Dump dependency graph for dot(1)\n"
4047 " snapshot [NAME] Create a snapshot\n"
4048 " delete [NAME...] Remove one or more snapshots\n"
4049 " daemon-reload Reload systemd manager configuration\n"
4050 " daemon-reexec Reexecute systemd manager\n"
4051 " show-environment Dump environment\n"
4052 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4053 " unset-environment [NAME...] Unset one or more environment variables\n"
4054 " default Enter system default mode\n"
4055 " rescue Enter system rescue mode\n"
4056 " emergency Enter system emergency mode\n"
4057 " halt Shut down and halt the system\n"
4058 " poweroff Shut down and power-off the system\n"
4059 " reboot Shut down and reboot the system\n"
4060 " kexec Shut down and reboot the system with kexec\n"
4061 " exit Ask for session termination\n",
4062 program_invocation_short_name);
4067 static int halt_help(void) {
4069 printf("%s [OPTIONS...]\n\n"
4070 "%s the system.\n\n"
4071 " --help Show this help\n"
4072 " --halt Halt the machine\n"
4073 " -p --poweroff Switch off the machine\n"
4074 " --reboot Reboot the machine\n"
4075 " -f --force Force immediate halt/power-off/reboot\n"
4076 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4077 " -d --no-wtmp Don't write wtmp record\n"
4078 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4079 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4080 program_invocation_short_name,
4081 arg_action == ACTION_REBOOT ? "Reboot" :
4082 arg_action == ACTION_POWEROFF ? "Power off" :
4088 static int shutdown_help(void) {
4090 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4091 "Shut down the system.\n\n"
4092 " --help Show this help\n"
4093 " -H --halt Halt the machine\n"
4094 " -P --poweroff Power-off the machine\n"
4095 " -r --reboot Reboot the machine\n"
4096 " -h Equivalent to --poweroff, overriden by --halt\n"
4097 " -k Don't halt/power-off/reboot, just send warnings\n"
4098 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4099 " -c Cancel a pending shutdown\n",
4100 program_invocation_short_name);
4105 static int telinit_help(void) {
4107 printf("%s [OPTIONS...] {COMMAND}\n\n"
4108 "Send control commands to the init daemon.\n\n"
4109 " --help Show this help\n"
4110 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4112 " 0 Power-off the machine\n"
4113 " 6 Reboot the machine\n"
4114 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4115 " 1, s, S Enter rescue mode\n"
4116 " q, Q Reload init daemon configuration\n"
4117 " u, U Reexecute init daemon\n",
4118 program_invocation_short_name);
4123 static int runlevel_help(void) {
4125 printf("%s [OPTIONS...]\n\n"
4126 "Prints the previous and current runlevel of the init system.\n\n"
4127 " --help Show this help\n",
4128 program_invocation_short_name);
4133 static int systemctl_parse_argv(int argc, char *argv[]) {
4152 static const struct option options[] = {
4153 { "help", no_argument, NULL, 'h' },
4154 { "version", no_argument, NULL, ARG_VERSION },
4155 { "type", required_argument, NULL, 't' },
4156 { "property", required_argument, NULL, 'p' },
4157 { "all", no_argument, NULL, 'a' },
4158 { "full", no_argument, NULL, ARG_FULL },
4159 { "fail", no_argument, NULL, ARG_FAIL },
4160 { "session", no_argument, NULL, ARG_SESSION },
4161 { "system", no_argument, NULL, ARG_SYSTEM },
4162 { "global", no_argument, NULL, ARG_GLOBAL },
4163 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4164 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4165 { "quiet", no_argument, NULL, 'q' },
4166 { "order", no_argument, NULL, ARG_ORDER },
4167 { "require", no_argument, NULL, ARG_REQUIRE },
4168 { "force", no_argument, NULL, 'f' },
4169 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4170 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4171 { "kill-mode", required_argument, NULL, ARG_KILL_MODE },
4172 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4173 { "signal", required_argument, NULL, 's' },
4174 { NULL, 0, NULL, 0 }
4182 while ((c = getopt_long(argc, argv, "ht:p:aqfs:", options, NULL)) >= 0) {
4191 puts(PACKAGE_STRING);
4193 puts(SYSTEMD_FEATURES);
4203 if (!(l = strv_append(arg_property, optarg)))
4206 strv_free(arg_property);
4209 /* If the user asked for a particular
4210 * property, show it to him, even if it is
4229 arg_session = false;
4233 arg_no_block = true;
4241 arg_dot = DOT_ORDER;
4245 arg_dot = DOT_REQUIRE;
4261 arg_no_reload = true;
4270 arg_defaults = true;
4274 arg_kill_who = optarg;
4278 arg_kill_mode = optarg;
4282 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4283 log_error("Failed to parse signal string %s.", optarg);
4292 log_error("Unknown option code %c", c);
4300 static int halt_parse_argv(int argc, char *argv[]) {
4309 static const struct option options[] = {
4310 { "help", no_argument, NULL, ARG_HELP },
4311 { "halt", no_argument, NULL, ARG_HALT },
4312 { "poweroff", no_argument, NULL, 'p' },
4313 { "reboot", no_argument, NULL, ARG_REBOOT },
4314 { "force", no_argument, NULL, 'f' },
4315 { "wtmp-only", no_argument, NULL, 'w' },
4316 { "no-wtmp", no_argument, NULL, 'd' },
4317 { "no-sync", no_argument, NULL, 'n' },
4318 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4319 { NULL, 0, NULL, 0 }
4327 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4328 if (runlevel == '0' || runlevel == '6')
4329 arg_immediate = true;
4331 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4339 arg_action = ACTION_HALT;
4343 if (arg_action != ACTION_REBOOT)
4344 arg_action = ACTION_POWEROFF;
4348 arg_action = ACTION_REBOOT;
4352 arg_immediate = true;
4373 /* Compatibility nops */
4380 log_error("Unknown option code %c", c);
4385 if (optind < argc) {
4386 log_error("Too many arguments.");
4393 static int parse_time_spec(const char *t, usec_t *_u) {
4397 if (streq(t, "now"))
4399 else if (t[0] == '+') {
4402 if (safe_atou64(t + 1, &u) < 0)
4405 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4414 hour = strtol(t, &e, 10);
4415 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4418 minute = strtol(e+1, &e, 10);
4419 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4422 n = now(CLOCK_REALTIME);
4423 s = (time_t) (n / USEC_PER_SEC);
4426 assert_se(localtime_r(&s, &tm));
4428 tm.tm_hour = (int) hour;
4429 tm.tm_min = (int) minute;
4432 assert_se(s = mktime(&tm));
4434 *_u = (usec_t) s * USEC_PER_SEC;
4437 *_u += USEC_PER_DAY;
4443 static int shutdown_parse_argv(int argc, char *argv[]) {
4450 static const struct option options[] = {
4451 { "help", no_argument, NULL, ARG_HELP },
4452 { "halt", no_argument, NULL, 'H' },
4453 { "poweroff", no_argument, NULL, 'P' },
4454 { "reboot", no_argument, NULL, 'r' },
4455 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4456 { NULL, 0, NULL, 0 }
4464 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4472 arg_action = ACTION_HALT;
4476 arg_action = ACTION_POWEROFF;
4480 arg_action = ACTION_REBOOT;
4484 if (arg_action != ACTION_HALT)
4485 arg_action = ACTION_POWEROFF;
4498 /* Compatibility nops */
4502 arg_action = ACTION_CANCEL_SHUTDOWN;
4509 log_error("Unknown option code %c", c);
4514 if (argc > optind) {
4515 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4516 log_error("Failed to parse time specification: %s", argv[optind]);
4520 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4522 /* We skip the time argument */
4523 if (argc > optind + 1)
4524 arg_wall = argv + optind + 1;
4531 static int telinit_parse_argv(int argc, char *argv[]) {
4538 static const struct option options[] = {
4539 { "help", no_argument, NULL, ARG_HELP },
4540 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4541 { NULL, 0, NULL, 0 }
4544 static const struct {
4548 { '0', ACTION_POWEROFF },
4549 { '6', ACTION_REBOOT },
4550 { '1', ACTION_RESCUE },
4551 { '2', ACTION_RUNLEVEL2 },
4552 { '3', ACTION_RUNLEVEL3 },
4553 { '4', ACTION_RUNLEVEL4 },
4554 { '5', ACTION_RUNLEVEL5 },
4555 { 's', ACTION_RESCUE },
4556 { 'S', ACTION_RESCUE },
4557 { 'q', ACTION_RELOAD },
4558 { 'Q', ACTION_RELOAD },
4559 { 'u', ACTION_REEXEC },
4560 { 'U', ACTION_REEXEC }
4569 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4584 log_error("Unknown option code %c", c);
4589 if (optind >= argc) {
4594 if (optind + 1 < argc) {
4595 log_error("Too many arguments.");
4599 if (strlen(argv[optind]) != 1) {
4600 log_error("Expected single character argument.");
4604 for (i = 0; i < ELEMENTSOF(table); i++)
4605 if (table[i].from == argv[optind][0])
4608 if (i >= ELEMENTSOF(table)) {
4609 log_error("Unknown command %s.", argv[optind]);
4613 arg_action = table[i].to;
4620 static int runlevel_parse_argv(int argc, char *argv[]) {
4626 static const struct option options[] = {
4627 { "help", no_argument, NULL, ARG_HELP },
4628 { NULL, 0, NULL, 0 }
4636 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4647 log_error("Unknown option code %c", c);
4652 if (optind < argc) {
4653 log_error("Too many arguments.");
4660 static int parse_argv(int argc, char *argv[]) {
4664 if (program_invocation_short_name) {
4666 if (strstr(program_invocation_short_name, "halt")) {
4667 arg_action = ACTION_HALT;
4668 return halt_parse_argv(argc, argv);
4669 } else if (strstr(program_invocation_short_name, "poweroff")) {
4670 arg_action = ACTION_POWEROFF;
4671 return halt_parse_argv(argc, argv);
4672 } else if (strstr(program_invocation_short_name, "reboot")) {
4673 arg_action = ACTION_REBOOT;
4674 return halt_parse_argv(argc, argv);
4675 } else if (strstr(program_invocation_short_name, "shutdown")) {
4676 arg_action = ACTION_POWEROFF;
4677 return shutdown_parse_argv(argc, argv);
4678 } else if (strstr(program_invocation_short_name, "init")) {
4680 if (sd_booted() > 0) {
4681 arg_action = ACTION_INVALID;
4682 return telinit_parse_argv(argc, argv);
4684 /* Hmm, so some other init system is
4685 * running, we need to forward this
4686 * request to it. For now we simply
4687 * guess that it is Upstart. */
4689 execv("/lib/upstart/telinit", argv);
4691 log_error("Couldn't find an alternative telinit implementation to spawn.");
4695 } else if (strstr(program_invocation_short_name, "runlevel")) {
4696 arg_action = ACTION_RUNLEVEL;
4697 return runlevel_parse_argv(argc, argv);
4701 arg_action = ACTION_SYSTEMCTL;
4702 return systemctl_parse_argv(argc, argv);
4705 static int action_to_runlevel(void) {
4707 static const char table[_ACTION_MAX] = {
4708 [ACTION_HALT] = '0',
4709 [ACTION_POWEROFF] = '0',
4710 [ACTION_REBOOT] = '6',
4711 [ACTION_RUNLEVEL2] = '2',
4712 [ACTION_RUNLEVEL3] = '3',
4713 [ACTION_RUNLEVEL4] = '4',
4714 [ACTION_RUNLEVEL5] = '5',
4715 [ACTION_RESCUE] = '1'
4718 assert(arg_action < _ACTION_MAX);
4720 return table[arg_action];
4723 static int talk_upstart(void) {
4724 DBusMessage *m = NULL, *reply = NULL;
4726 int previous, rl, r;
4728 env1_buf[] = "RUNLEVEL=X",
4729 env2_buf[] = "PREVLEVEL=X";
4730 char *env1 = env1_buf, *env2 = env2_buf;
4731 const char *emit = "runlevel";
4732 dbus_bool_t b_false = FALSE;
4733 DBusMessageIter iter, sub;
4734 DBusConnection *bus;
4736 dbus_error_init(&error);
4738 if (!(rl = action_to_runlevel()))
4741 if (utmp_get_runlevel(&previous, NULL) < 0)
4744 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4745 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4750 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4755 if ((r = bus_check_peercred(bus)) < 0) {
4756 log_error("Failed to verify owner of bus.");
4760 if (!(m = dbus_message_new_method_call(
4761 "com.ubuntu.Upstart",
4762 "/com/ubuntu/Upstart",
4763 "com.ubuntu.Upstart0_6",
4766 log_error("Could not allocate message.");
4771 dbus_message_iter_init_append(m, &iter);
4773 env1_buf[sizeof(env1_buf)-2] = rl;
4774 env2_buf[sizeof(env2_buf)-2] = previous;
4776 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4777 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4778 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4779 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4780 !dbus_message_iter_close_container(&iter, &sub) ||
4781 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4782 log_error("Could not append arguments to message.");
4787 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4789 if (error_is_no_service(&error)) {
4794 log_error("Failed to issue method call: %s", bus_error_message(&error));
4803 dbus_message_unref(m);
4806 dbus_message_unref(reply);
4809 dbus_connection_flush(bus);
4810 dbus_connection_close(bus);
4811 dbus_connection_unref(bus);
4814 dbus_error_free(&error);
4819 static int talk_initctl(void) {
4820 struct init_request request;
4824 if (!(rl = action_to_runlevel()))
4828 request.magic = INIT_MAGIC;
4829 request.sleeptime = 0;
4830 request.cmd = INIT_CMD_RUNLVL;
4831 request.runlevel = rl;
4833 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4835 if (errno == ENOENT)
4838 log_error("Failed to open "INIT_FIFO": %m");
4843 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4844 close_nointr_nofail(fd);
4847 log_error("Failed to write to "INIT_FIFO": %m");
4848 return errno ? -errno : -EIO;
4854 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4856 static const struct {
4864 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4866 { "list-units", LESS, 1, list_units },
4867 { "list-jobs", EQUAL, 1, list_jobs },
4868 { "clear-jobs", EQUAL, 1, daemon_reload },
4869 { "load", MORE, 2, load_unit },
4870 { "cancel", MORE, 2, cancel_job },
4871 { "start", MORE, 2, start_unit },
4872 { "stop", MORE, 2, start_unit },
4873 { "reload", MORE, 2, start_unit },
4874 { "restart", MORE, 2, start_unit },
4875 { "try-restart", MORE, 2, start_unit },
4876 { "reload-or-restart", MORE, 2, start_unit },
4877 { "reload-or-try-restart", MORE, 2, start_unit },
4878 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4879 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4880 { "isolate", EQUAL, 2, start_unit },
4881 { "kill", MORE, 2, kill_unit },
4882 { "is-active", MORE, 2, check_unit },
4883 { "check", MORE, 2, check_unit },
4884 { "show", MORE, 1, show },
4885 { "status", MORE, 2, show },
4886 { "monitor", EQUAL, 1, monitor },
4887 { "dump", EQUAL, 1, dump },
4888 { "dot", EQUAL, 1, dot },
4889 { "snapshot", LESS, 2, snapshot },
4890 { "delete", MORE, 2, delete_snapshot },
4891 { "daemon-reload", EQUAL, 1, daemon_reload },
4892 { "daemon-reexec", EQUAL, 1, daemon_reload },
4893 { "show-environment", EQUAL, 1, show_enviroment },
4894 { "set-environment", MORE, 2, set_environment },
4895 { "unset-environment", MORE, 2, set_environment },
4896 { "halt", EQUAL, 1, start_special },
4897 { "poweroff", EQUAL, 1, start_special },
4898 { "reboot", EQUAL, 1, start_special },
4899 { "kexec", EQUAL, 1, start_special },
4900 { "default", EQUAL, 1, start_special },
4901 { "rescue", EQUAL, 1, start_special },
4902 { "emergency", EQUAL, 1, start_special },
4903 { "exit", EQUAL, 1, start_special },
4904 { "reset-failed", MORE, 1, reset_failed },
4905 { "enable", MORE, 2, enable_unit },
4906 { "disable", MORE, 2, enable_unit },
4907 { "is-enabled", MORE, 2, enable_unit }
4917 left = argc - optind;
4920 /* Special rule: no arguments means "list-units" */
4923 if (streq(argv[optind], "help")) {
4928 for (i = 0; i < ELEMENTSOF(verbs); i++)
4929 if (streq(argv[optind], verbs[i].verb))
4932 if (i >= ELEMENTSOF(verbs)) {
4933 log_error("Unknown operation %s", argv[optind]);
4938 switch (verbs[i].argc_cmp) {
4941 if (left != verbs[i].argc) {
4942 log_error("Invalid number of arguments.");
4949 if (left < verbs[i].argc) {
4950 log_error("Too few arguments.");
4957 if (left > verbs[i].argc) {
4958 log_error("Too many arguments.");
4965 assert_not_reached("Unknown comparison operator.");
4968 /* Require a bus connection for all operations but
4970 if (!streq(verbs[i].verb, "enable") &&
4971 !streq(verbs[i].verb, "disable") &&
4973 log_error("Failed to get D-Bus connection: %s", error->message);
4977 return verbs[i].dispatch(bus, argv + optind, left);
4980 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
4982 struct msghdr msghdr;
4984 union sockaddr_union sockaddr;
4985 struct shutdownd_command c;
4993 strncpy(c.wall_message, message, sizeof(c.wall_message));
4995 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4999 sockaddr.sa.sa_family = AF_UNIX;
5000 sockaddr.un.sun_path[0] = 0;
5001 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
5004 iovec.iov_base = (char*) &c;
5005 iovec.iov_len = sizeof(c);
5008 msghdr.msg_name = &sockaddr;
5009 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
5011 msghdr.msg_iov = &iovec;
5012 msghdr.msg_iovlen = 1;
5014 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5015 close_nointr_nofail(fd);
5019 close_nointr_nofail(fd);
5023 static int reload_with_fallback(DBusConnection *bus) {
5026 /* First, try systemd via D-Bus. */
5027 if (daemon_reload(bus, NULL, 0) > 0)
5031 /* Nothing else worked, so let's try signals */
5032 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5034 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5035 log_error("kill() failed: %m");
5042 static int start_with_fallback(DBusConnection *bus) {
5045 /* First, try systemd via D-Bus. */
5046 if (start_unit(bus, NULL, 0) >= 0)
5050 /* Hmm, talking to systemd via D-Bus didn't work. Then
5051 * let's try to talk to Upstart via D-Bus. */
5052 if (talk_upstart() > 0)
5055 /* Nothing else worked, so let's try
5057 if (talk_initctl() > 0)
5060 log_error("Failed to talk to init daemon.");
5064 warn_wall(arg_action);
5068 static int halt_main(DBusConnection *bus) {
5071 if (geteuid() != 0) {
5072 log_error("Must be root.");
5078 char date[FORMAT_TIMESTAMP_MAX];
5080 m = strv_join(arg_wall, " ");
5081 r = send_shutdownd(arg_when,
5082 arg_action == ACTION_HALT ? 'H' :
5083 arg_action == ACTION_POWEROFF ? 'P' :
5090 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5092 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5093 format_timestamp(date, sizeof(date), arg_when));
5098 if (!arg_dry && !arg_immediate)
5099 return start_with_fallback(bus);
5102 if (sd_booted() > 0)
5103 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5104 else if ((r = utmp_put_shutdown(0)) < 0)
5105 log_warning("Failed to write utmp record: %s", strerror(-r));
5114 /* Make sure C-A-D is handled by the kernel from this
5116 reboot(RB_ENABLE_CAD);
5118 switch (arg_action) {
5121 log_info("Halting.");
5122 reboot(RB_HALT_SYSTEM);
5125 case ACTION_POWEROFF:
5126 log_info("Powering off.");
5127 reboot(RB_POWER_OFF);
5131 log_info("Rebooting.");
5132 reboot(RB_AUTOBOOT);
5136 assert_not_reached("Unknown halt action.");
5139 /* We should never reach this. */
5143 static int runlevel_main(void) {
5144 int r, runlevel, previous;
5146 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5147 printf("unknown\n");
5152 previous <= 0 ? 'N' : previous,
5153 runlevel <= 0 ? 'N' : runlevel);
5158 int main(int argc, char*argv[]) {
5159 int r, retval = EXIT_FAILURE;
5160 DBusConnection *bus = NULL;
5163 dbus_error_init(&error);
5165 log_parse_environment();
5168 if ((r = parse_argv(argc, argv)) < 0)
5171 retval = EXIT_SUCCESS;
5175 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5176 * let's shortcut this */
5177 if (arg_action == ACTION_RUNLEVEL) {
5178 r = runlevel_main();
5179 retval = r < 0 ? EXIT_FAILURE : r;
5183 bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5185 switch (arg_action) {
5187 case ACTION_SYSTEMCTL:
5188 r = systemctl_main(bus, argc, argv, &error);
5192 case ACTION_POWEROFF:
5197 case ACTION_RUNLEVEL2:
5198 case ACTION_RUNLEVEL3:
5199 case ACTION_RUNLEVEL4:
5200 case ACTION_RUNLEVEL5:
5202 case ACTION_EMERGENCY:
5203 case ACTION_DEFAULT:
5204 r = start_with_fallback(bus);
5209 r = reload_with_fallback(bus);
5212 case ACTION_CANCEL_SHUTDOWN:
5213 r = send_shutdownd(0, 0, false, NULL);
5216 case ACTION_INVALID:
5217 case ACTION_RUNLEVEL:
5219 assert_not_reached("Unknown action");
5222 retval = r < 0 ? EXIT_FAILURE : r;
5227 dbus_connection_flush(bus);
5228 dbus_connection_close(bus);
5229 dbus_connection_unref(bus);
5232 dbus_error_free(&error);
5236 strv_free(arg_property);