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 usec_t arg_when = 0;
96 ACTION_CANCEL_SHUTDOWN,
98 } arg_action = ACTION_SYSTEMCTL;
105 static bool private_bus = false;
107 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
109 static bool on_tty(void) {
112 if (_unlikely_(t < 0))
113 t = isatty(STDOUT_FILENO) > 0;
118 static const char *ansi_highlight(bool b) {
123 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
126 static const char *ansi_highlight_green(bool b) {
131 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
134 static bool error_is_no_service(const DBusError *error) {
137 if (!dbus_error_is_set(error))
140 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
143 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
146 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
149 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
152 if (!dbus_error_is_set(error))
155 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
156 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
157 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
158 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
159 return EXIT_NOPERMISSION;
161 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
162 return EXIT_NOTINSTALLED;
164 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
165 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
166 return EXIT_NOTIMPLEMENTED;
168 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
169 return EXIT_NOTCONFIGURED;
177 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
182 if (dbus_message_iter_get_arg_type(iter) != type)
185 dbus_message_iter_get_basic(iter, data);
187 if (!dbus_message_iter_next(iter) != !next)
193 static void warn_wall(enum action action) {
194 static const char *table[_ACTION_MAX] = {
195 [ACTION_HALT] = "The system is going down for system halt NOW!",
196 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
197 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
198 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
199 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
200 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
209 if (!(p = strv_join(arg_wall, " "))) {
210 log_error("Failed to join strings.");
226 utmp_wall(table[action]);
231 const char *description;
232 const char *load_state;
233 const char *active_state;
234 const char *sub_state;
235 const char *following;
236 const char *unit_path;
238 const char *job_type;
239 const char *job_path;
242 static int compare_unit_info(const void *a, const void *b) {
244 const struct unit_info *u = a, *v = b;
246 d1 = strrchr(u->id, '.');
247 d2 = strrchr(v->id, '.');
252 if ((r = strcasecmp(d1, d2)) != 0)
256 return strcasecmp(u->id, v->id);
259 static bool output_show_job(const struct unit_info *u) {
262 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
263 streq(dot+1, arg_type))) &&
264 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0);
267 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
268 unsigned active_len, sub_len, job_len, n_shown = 0;
269 const struct unit_info *u;
271 active_len = sizeof("ACTIVE")-1;
272 sub_len = sizeof("SUB")-1;
273 job_len = sizeof("JOB")-1;
275 for (u = unit_infos; u < unit_infos + c; u++) {
276 if (!output_show_job(u))
279 active_len = MAX(active_len, strlen(u->active_state));
280 sub_len = MAX(sub_len, strlen(u->sub_state));
282 job_len = MAX(job_len, strlen(u->job_type));
286 printf("%-25s %-6s %-*s %-*s %-*s", "UNIT", "LOAD",
287 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
288 if (columns() >= 80+12 || arg_full)
289 printf(" %s\n", "DESCRIPTION");
294 for (u = unit_infos; u < unit_infos + c; u++) {
297 const char *on_loaded, *off_loaded;
298 const char *on_active, *off_active;
300 if (!output_show_job(u))
305 if (!streq(u->load_state, "loaded") &&
306 !streq(u->load_state, "banned")) {
307 on_loaded = ansi_highlight(true);
308 off_loaded = ansi_highlight(false);
310 on_loaded = off_loaded = "";
312 if (streq(u->active_state, "failed")) {
313 on_active = ansi_highlight(true);
314 off_active = ansi_highlight(false);
316 on_active = off_active = "";
318 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
320 printf("%-25s %s%-6s%s %s%-*s %-*s%s%n",
322 on_loaded, u->load_state, off_loaded,
323 on_active, active_len, u->active_state,
324 sub_len, u->sub_state, off_active,
329 a -= strlen(on_loaded) + strlen(off_loaded);
330 a -= strlen(on_active) + strlen(off_active);
333 printf(" %-*s", job_len, u->job_type);
337 if (a + b + 1 < columns()) {
339 printf(" %-*s", job_len, "");
342 printf(" %s", u->description);
344 printf(" %.*s", columns() - a - b - 1, u->description);
351 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
352 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
353 "SUB = The low-level unit activation state, values depend on unit type.\n"
354 "JOB = Pending job for the unit.\n");
357 printf("\n%u units listed.\n", n_shown);
359 printf("\n%u units listed. Pass --all to see inactive units, too.\n", n_shown);
363 static int list_units(DBusConnection *bus, char **args, unsigned n) {
364 DBusMessage *m = NULL, *reply = NULL;
367 DBusMessageIter iter, sub, sub2;
368 unsigned c = 0, n_units = 0;
369 struct unit_info *unit_infos = NULL;
371 dbus_error_init(&error);
375 if (!(m = dbus_message_new_method_call(
376 "org.freedesktop.systemd1",
377 "/org/freedesktop/systemd1",
378 "org.freedesktop.systemd1.Manager",
380 log_error("Could not allocate message.");
384 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
385 log_error("Failed to issue method call: %s", bus_error_message(&error));
390 if (!dbus_message_iter_init(reply, &iter) ||
391 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
392 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
393 log_error("Failed to parse reply.");
398 dbus_message_iter_recurse(&iter, &sub);
400 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
403 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
404 log_error("Failed to parse reply.");
412 n_units = MAX(2*c, 16);
413 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
416 log_error("Failed to allocate unit array.");
426 dbus_message_iter_recurse(&sub, &sub2);
428 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
429 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
430 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
431 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
432 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
433 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
434 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
435 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
436 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
437 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
438 log_error("Failed to parse reply.");
443 dbus_message_iter_next(&sub);
447 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
448 output_units_list(unit_infos, c);
454 dbus_message_unref(m);
457 dbus_message_unref(reply);
461 dbus_error_free(&error);
466 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
467 static const char * const colors[] = {
468 "Requires", "[color=\"black\"]",
469 "RequiresOverridable", "[color=\"black\"]",
470 "Requisite", "[color=\"darkblue\"]",
471 "RequisiteOverridable", "[color=\"darkblue\"]",
472 "Wants", "[color=\"darkgrey\"]",
473 "Conflicts", "[color=\"red\"]",
474 "ConflictedBy", "[color=\"red\"]",
475 "After", "[color=\"green\"]"
478 const char *c = NULL;
485 for (i = 0; i < ELEMENTSOF(colors); i += 2)
486 if (streq(colors[i], prop)) {
494 if (arg_dot != DOT_ALL)
495 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
498 switch (dbus_message_iter_get_arg_type(iter)) {
500 case DBUS_TYPE_ARRAY:
502 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
505 dbus_message_iter_recurse(iter, &sub);
507 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
510 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
511 dbus_message_iter_get_basic(&sub, &s);
512 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
514 dbus_message_iter_next(&sub);
524 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
525 DBusMessage *m = NULL, *reply = NULL;
526 const char *interface = "org.freedesktop.systemd1.Unit";
529 DBusMessageIter iter, sub, sub2, sub3;
534 dbus_error_init(&error);
536 if (!(m = dbus_message_new_method_call(
537 "org.freedesktop.systemd1",
539 "org.freedesktop.DBus.Properties",
541 log_error("Could not allocate message.");
546 if (!dbus_message_append_args(m,
547 DBUS_TYPE_STRING, &interface,
548 DBUS_TYPE_INVALID)) {
549 log_error("Could not append arguments to message.");
554 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
555 log_error("Failed to issue method call: %s", bus_error_message(&error));
560 if (!dbus_message_iter_init(reply, &iter) ||
561 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
562 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
563 log_error("Failed to parse reply.");
568 dbus_message_iter_recurse(&iter, &sub);
570 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
573 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
574 log_error("Failed to parse reply.");
579 dbus_message_iter_recurse(&sub, &sub2);
581 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
582 log_error("Failed to parse reply.");
587 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
588 log_error("Failed to parse reply.");
593 dbus_message_iter_recurse(&sub2, &sub3);
595 if (dot_one_property(name, prop, &sub3)) {
596 log_error("Failed to parse reply.");
601 dbus_message_iter_next(&sub);
608 dbus_message_unref(m);
611 dbus_message_unref(reply);
613 dbus_error_free(&error);
618 static int dot(DBusConnection *bus, char **args, unsigned n) {
619 DBusMessage *m = NULL, *reply = NULL;
622 DBusMessageIter iter, sub, sub2;
624 dbus_error_init(&error);
628 if (!(m = dbus_message_new_method_call(
629 "org.freedesktop.systemd1",
630 "/org/freedesktop/systemd1",
631 "org.freedesktop.systemd1.Manager",
633 log_error("Could not allocate message.");
637 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
638 log_error("Failed to issue method call: %s", bus_error_message(&error));
643 if (!dbus_message_iter_init(reply, &iter) ||
644 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
645 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
646 log_error("Failed to parse reply.");
651 printf("digraph systemd {\n");
653 dbus_message_iter_recurse(&iter, &sub);
654 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
655 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
657 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
658 log_error("Failed to parse reply.");
663 dbus_message_iter_recurse(&sub, &sub2);
665 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
666 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
667 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
668 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
669 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
670 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
671 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
672 log_error("Failed to parse reply.");
677 if ((r = dot_one(bus, id, unit_path)) < 0)
680 /* printf("\t\"%s\";\n", id); */
681 dbus_message_iter_next(&sub);
686 log_info(" Color legend: black = Requires\n"
687 " dark blue = Requisite\n"
688 " dark grey = Wants\n"
692 if (isatty(fileno(stdout)))
693 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
694 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
700 dbus_message_unref(m);
703 dbus_message_unref(reply);
705 dbus_error_free(&error);
710 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
711 DBusMessage *m = NULL, *reply = NULL;
714 DBusMessageIter iter, sub, sub2;
717 dbus_error_init(&error);
721 if (!(m = dbus_message_new_method_call(
722 "org.freedesktop.systemd1",
723 "/org/freedesktop/systemd1",
724 "org.freedesktop.systemd1.Manager",
726 log_error("Could not allocate message.");
730 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
731 log_error("Failed to issue method call: %s", bus_error_message(&error));
736 if (!dbus_message_iter_init(reply, &iter) ||
737 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
738 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
739 log_error("Failed to parse reply.");
744 dbus_message_iter_recurse(&iter, &sub);
746 if (isatty(STDOUT_FILENO))
747 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
749 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
750 const char *name, *type, *state, *job_path, *unit_path;
754 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
755 log_error("Failed to parse reply.");
760 dbus_message_iter_recurse(&sub, &sub2);
762 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
763 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
764 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
765 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
766 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
767 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
768 log_error("Failed to parse reply.");
773 e = arg_full ? NULL : ellipsize(name, 25, 33);
774 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
779 dbus_message_iter_next(&sub);
782 if (isatty(STDOUT_FILENO))
783 printf("\n%u jobs listed.\n", k);
789 dbus_message_unref(m);
792 dbus_message_unref(reply);
794 dbus_error_free(&error);
799 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
800 DBusMessage *m = NULL, *reply = NULL;
805 dbus_error_init(&error);
810 for (i = 1; i < n; i++) {
812 if (!(m = dbus_message_new_method_call(
813 "org.freedesktop.systemd1",
814 "/org/freedesktop/systemd1",
815 "org.freedesktop.systemd1.Manager",
817 log_error("Could not allocate message.");
822 if (!dbus_message_append_args(m,
823 DBUS_TYPE_STRING, &args[i],
824 DBUS_TYPE_INVALID)) {
825 log_error("Could not append arguments to message.");
830 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
831 log_error("Failed to issue method call: %s", bus_error_message(&error));
836 dbus_message_unref(m);
837 dbus_message_unref(reply);
846 dbus_message_unref(m);
849 dbus_message_unref(reply);
851 dbus_error_free(&error);
856 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
857 DBusMessage *m = NULL, *reply = NULL;
862 dbus_error_init(&error);
868 return daemon_reload(bus, args, n);
870 for (i = 1; i < n; i++) {
874 if (!(m = dbus_message_new_method_call(
875 "org.freedesktop.systemd1",
876 "/org/freedesktop/systemd1",
877 "org.freedesktop.systemd1.Manager",
879 log_error("Could not allocate message.");
884 if ((r = safe_atou(args[i], &id)) < 0) {
885 log_error("Failed to parse job id: %s", strerror(-r));
889 assert_cc(sizeof(uint32_t) == sizeof(id));
890 if (!dbus_message_append_args(m,
891 DBUS_TYPE_UINT32, &id,
892 DBUS_TYPE_INVALID)) {
893 log_error("Could not append arguments to message.");
898 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
899 log_error("Failed to issue method call: %s", bus_error_message(&error));
904 if (!dbus_message_get_args(reply, &error,
905 DBUS_TYPE_OBJECT_PATH, &path,
906 DBUS_TYPE_INVALID)) {
907 log_error("Failed to parse reply: %s", bus_error_message(&error));
912 dbus_message_unref(m);
913 if (!(m = dbus_message_new_method_call(
914 "org.freedesktop.systemd1",
916 "org.freedesktop.systemd1.Job",
918 log_error("Could not allocate message.");
923 dbus_message_unref(reply);
924 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
925 log_error("Failed to issue method call: %s", bus_error_message(&error));
930 dbus_message_unref(m);
931 dbus_message_unref(reply);
939 dbus_message_unref(m);
942 dbus_message_unref(reply);
944 dbus_error_free(&error);
949 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
950 DBusMessage *m = NULL, *reply = NULL;
951 dbus_bool_t b = FALSE;
952 DBusMessageIter iter, sub;
954 *interface = "org.freedesktop.systemd1.Unit",
955 *property = "NeedDaemonReload",
958 /* We ignore all errors here, since this is used to show a warning only */
960 if (!(m = dbus_message_new_method_call(
961 "org.freedesktop.systemd1",
962 "/org/freedesktop/systemd1",
963 "org.freedesktop.systemd1.Manager",
967 if (!dbus_message_append_args(m,
968 DBUS_TYPE_STRING, &unit,
972 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
975 if (!dbus_message_get_args(reply, NULL,
976 DBUS_TYPE_OBJECT_PATH, &path,
980 dbus_message_unref(m);
981 if (!(m = dbus_message_new_method_call(
982 "org.freedesktop.systemd1",
984 "org.freedesktop.DBus.Properties",
988 if (!dbus_message_append_args(m,
989 DBUS_TYPE_STRING, &interface,
990 DBUS_TYPE_STRING, &property,
991 DBUS_TYPE_INVALID)) {
995 dbus_message_unref(reply);
996 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
999 if (!dbus_message_iter_init(reply, &iter) ||
1000 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1003 dbus_message_iter_recurse(&iter, &sub);
1005 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1008 dbus_message_iter_get_basic(&sub, &b);
1012 dbus_message_unref(m);
1015 dbus_message_unref(reply);
1020 typedef struct WaitData {
1025 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1033 dbus_error_init(&error);
1035 log_debug("Got D-Bus request: %s.%s() on %s",
1036 dbus_message_get_interface(message),
1037 dbus_message_get_member(message),
1038 dbus_message_get_path(message));
1040 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1041 log_error("Warning! D-Bus connection terminated.");
1042 dbus_connection_close(connection);
1044 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1047 dbus_bool_t success = true;
1049 if (!dbus_message_get_args(message, &error,
1050 DBUS_TYPE_UINT32, &id,
1051 DBUS_TYPE_OBJECT_PATH, &path,
1052 DBUS_TYPE_BOOLEAN, &success,
1054 log_error("Failed to parse message: %s", bus_error_message(&error));
1058 if ((p = set_remove(d->set, (char*) path)))
1066 dbus_error_free(&error);
1067 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1070 static int enable_wait_for_jobs(DBusConnection *bus) {
1078 dbus_error_init(&error);
1079 dbus_bus_add_match(bus,
1081 "sender='org.freedesktop.systemd1',"
1082 "interface='org.freedesktop.systemd1.Manager',"
1083 "member='JobRemoved',"
1084 "path='/org/freedesktop/systemd1'",
1087 if (dbus_error_is_set(&error)) {
1088 log_error("Failed to add match: %s", bus_error_message(&error));
1089 dbus_error_free(&error);
1093 /* This is slightly dirty, since we don't undo the match registrations. */
1097 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1108 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1109 log_error("Failed to add filter.");
1114 while (!set_isempty(s) &&
1115 dbus_connection_read_write_dispatch(bus, -1))
1118 if (!arg_quiet && d.failed)
1119 log_error("Job failed, see system logs for details.");
1121 r = d.failed ? -EIO : 0;
1124 /* This is slightly dirty, since we don't undo the filter registration. */
1129 static int start_unit_one(
1130 DBusConnection *bus,
1137 DBusMessage *m = NULL, *reply = NULL;
1146 assert(arg_no_block || s);
1148 if (!(m = dbus_message_new_method_call(
1149 "org.freedesktop.systemd1",
1150 "/org/freedesktop/systemd1",
1151 "org.freedesktop.systemd1.Manager",
1153 log_error("Could not allocate message.");
1158 if (!dbus_message_append_args(m,
1159 DBUS_TYPE_STRING, &name,
1160 DBUS_TYPE_STRING, &mode,
1161 DBUS_TYPE_INVALID)) {
1162 log_error("Could not append arguments to message.");
1167 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1169 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1170 /* There's always a fallback possible for
1171 * legacy actions. */
1176 log_error("Failed to issue method call: %s", bus_error_message(error));
1181 if (!dbus_message_get_args(reply, error,
1182 DBUS_TYPE_OBJECT_PATH, &path,
1183 DBUS_TYPE_INVALID)) {
1184 log_error("Failed to parse reply: %s", bus_error_message(error));
1189 if (need_daemon_reload(bus, name))
1190 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1191 arg_session ? "--session" : "--system");
1193 if (!arg_no_block) {
1196 if (!(p = strdup(path))) {
1197 log_error("Failed to duplicate path.");
1202 if ((r = set_put(s, p)) < 0) {
1204 log_error("Failed to add path to set.");
1213 dbus_message_unref(m);
1216 dbus_message_unref(reply);
1221 static enum action verb_to_action(const char *verb) {
1222 if (streq(verb, "halt"))
1224 else if (streq(verb, "poweroff"))
1225 return ACTION_POWEROFF;
1226 else if (streq(verb, "reboot"))
1227 return ACTION_REBOOT;
1228 else if (streq(verb, "kexec"))
1229 return ACTION_KEXEC;
1230 else if (streq(verb, "rescue"))
1231 return ACTION_RESCUE;
1232 else if (streq(verb, "emergency"))
1233 return ACTION_EMERGENCY;
1234 else if (streq(verb, "default"))
1235 return ACTION_DEFAULT;
1236 else if (streq(verb, "exit"))
1239 return ACTION_INVALID;
1242 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1244 static const char * const table[_ACTION_MAX] = {
1245 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1246 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1247 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1248 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1249 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1250 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1251 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1252 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1253 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1254 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1255 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1256 [ACTION_EXIT] = SPECIAL_EXIT_TARGET
1261 const char *method, *mode, *one_name;
1265 dbus_error_init(&error);
1269 if (arg_action == ACTION_SYSTEMCTL) {
1271 streq(args[0], "stop") ? "StopUnit" :
1272 streq(args[0], "reload") ? "ReloadUnit" :
1273 streq(args[0], "restart") ? "RestartUnit" :
1274 streq(args[0], "try-restart") ||
1275 streq(args[0], "condrestart") ? "TryRestartUnit" :
1276 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1277 streq(args[0], "reload-or-try-restart") ||
1278 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1282 (streq(args[0], "isolate") ||
1283 streq(args[0], "rescue") ||
1284 streq(args[0], "emergency")) ? "isolate" :
1288 one_name = table[verb_to_action(args[0])];
1291 assert(arg_action < ELEMENTSOF(table));
1292 assert(table[arg_action]);
1294 method = "StartUnit";
1296 mode = (arg_action == ACTION_EMERGENCY ||
1297 arg_action == ACTION_RESCUE ||
1298 arg_action == ACTION_RUNLEVEL2 ||
1299 arg_action == ACTION_RUNLEVEL3 ||
1300 arg_action == ACTION_RUNLEVEL4 ||
1301 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1303 one_name = table[arg_action];
1306 if (!arg_no_block) {
1307 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1308 log_error("Could not watch jobs: %s", strerror(-ret));
1312 if (!(s = set_new(string_hash_func, string_compare_func))) {
1313 log_error("Failed to allocate set.");
1320 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1323 for (i = 1; i < n; i++)
1324 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1325 ret = translate_bus_error_to_exit_status(r, &error);
1326 dbus_error_free(&error);
1331 if ((r = wait_for_jobs(bus, s)) < 0) {
1340 dbus_error_free(&error);
1345 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1352 (streq(args[0], "halt") ||
1353 streq(args[0], "poweroff") ||
1354 streq(args[0], "reboot") ||
1355 streq(args[0], "kexec") ||
1356 streq(args[0], "exit")))
1357 return daemon_reload(bus, args, n);
1359 r = start_unit(bus, args, n);
1362 warn_wall(verb_to_action(args[0]));
1367 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1368 DBusMessage *m = NULL, *reply = NULL;
1370 *interface = "org.freedesktop.systemd1.Unit",
1371 *property = "ActiveState";
1372 int r = 3; /* According to LSB: "program is not running" */
1379 dbus_error_init(&error);
1381 for (i = 1; i < n; i++) {
1382 const char *path = NULL;
1384 DBusMessageIter iter, sub;
1386 if (!(m = dbus_message_new_method_call(
1387 "org.freedesktop.systemd1",
1388 "/org/freedesktop/systemd1",
1389 "org.freedesktop.systemd1.Manager",
1391 log_error("Could not allocate message.");
1396 if (!dbus_message_append_args(m,
1397 DBUS_TYPE_STRING, &args[i],
1398 DBUS_TYPE_INVALID)) {
1399 log_error("Could not append arguments to message.");
1404 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1406 /* Hmm, cannot figure out anything about this unit... */
1410 dbus_error_free(&error);
1414 if (!dbus_message_get_args(reply, &error,
1415 DBUS_TYPE_OBJECT_PATH, &path,
1416 DBUS_TYPE_INVALID)) {
1417 log_error("Failed to parse reply: %s", bus_error_message(&error));
1422 dbus_message_unref(m);
1423 if (!(m = dbus_message_new_method_call(
1424 "org.freedesktop.systemd1",
1426 "org.freedesktop.DBus.Properties",
1428 log_error("Could not allocate message.");
1433 if (!dbus_message_append_args(m,
1434 DBUS_TYPE_STRING, &interface,
1435 DBUS_TYPE_STRING, &property,
1436 DBUS_TYPE_INVALID)) {
1437 log_error("Could not append arguments to message.");
1442 dbus_message_unref(reply);
1443 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1444 log_error("Failed to issue method call: %s", bus_error_message(&error));
1449 if (!dbus_message_iter_init(reply, &iter) ||
1450 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1451 log_error("Failed to parse reply.");
1456 dbus_message_iter_recurse(&iter, &sub);
1458 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1459 log_error("Failed to parse reply.");
1464 dbus_message_iter_get_basic(&sub, &state);
1469 if (streq(state, "active") || streq(state, "reloading"))
1472 dbus_message_unref(m);
1473 dbus_message_unref(reply);
1479 dbus_message_unref(m);
1482 dbus_message_unref(reply);
1484 dbus_error_free(&error);
1489 typedef struct ExecStatusInfo {
1495 usec_t start_timestamp;
1496 usec_t exit_timestamp;
1501 LIST_FIELDS(struct ExecStatusInfo, exec);
1504 static void exec_status_info_free(ExecStatusInfo *i) {
1512 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1513 uint64_t start_timestamp, exit_timestamp;
1514 DBusMessageIter sub2, sub3;
1518 int32_t code, status;
1524 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1527 dbus_message_iter_recurse(sub, &sub2);
1529 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1532 if (!(i->path = strdup(path)))
1535 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1536 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1540 dbus_message_iter_recurse(&sub2, &sub3);
1541 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1542 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1543 dbus_message_iter_next(&sub3);
1548 if (!(i->argv = new0(char*, n+1)))
1552 dbus_message_iter_recurse(&sub2, &sub3);
1553 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1556 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1557 dbus_message_iter_get_basic(&sub3, &s);
1558 dbus_message_iter_next(&sub3);
1560 if (!(i->argv[n++] = strdup(s)))
1564 if (!dbus_message_iter_next(&sub2) ||
1565 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1566 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1567 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1568 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1569 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1570 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1574 i->start_timestamp = (usec_t) start_timestamp;
1575 i->exit_timestamp = (usec_t) exit_timestamp;
1576 i->pid = (pid_t) pid;
1583 typedef struct UnitStatusInfo {
1585 const char *load_state;
1586 const char *active_state;
1587 const char *sub_state;
1589 const char *description;
1590 const char *following;
1593 const char *default_control_group;
1595 usec_t inactive_exit_timestamp;
1596 usec_t active_enter_timestamp;
1597 usec_t active_exit_timestamp;
1598 usec_t inactive_enter_timestamp;
1600 bool need_daemon_reload;
1605 const char *status_text;
1607 #ifdef HAVE_SYSV_COMPAT
1611 usec_t start_timestamp;
1612 usec_t exit_timestamp;
1614 int exit_code, exit_status;
1617 unsigned n_accepted;
1618 unsigned n_connections;
1622 const char *sysfs_path;
1624 /* Mount, Automount */
1630 LIST_HEAD(ExecStatusInfo, exec);
1633 static void print_status_info(UnitStatusInfo *i) {
1635 const char *on, *off, *ss;
1637 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1638 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1642 /* This shows pretty information about a unit. See
1643 * print_property() for a low-level property printer */
1645 printf("%s", strna(i->id));
1647 if (i->description && !streq_ptr(i->id, i->description))
1648 printf(" - %s", i->description);
1653 printf("\t Follow: unit currently follows state of %s\n", i->following);
1655 if (streq_ptr(i->load_state, "failed") ||
1656 streq_ptr(i->load_state, "banned")) {
1657 on = ansi_highlight(true);
1658 off = ansi_highlight(false);
1663 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1665 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1667 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1669 if (streq_ptr(i->active_state, "failed")) {
1670 on = ansi_highlight(true);
1671 off = ansi_highlight(false);
1672 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1673 on = ansi_highlight_green(true);
1674 off = ansi_highlight_green(false);
1679 printf("\t Active: %s%s (%s)%s",
1681 strna(i->active_state),
1685 printf("\t Active: %s%s%s",
1687 strna(i->active_state),
1690 timestamp = (streq_ptr(i->active_state, "active") ||
1691 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1692 (streq_ptr(i->active_state, "inactive") ||
1693 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1694 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1695 i->active_exit_timestamp;
1697 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1698 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1701 printf(" since %s; %s\n", s2, s1);
1703 printf(" since %s\n", s2);
1708 printf("\t Device: %s\n", i->sysfs_path);
1710 printf("\t Where: %s\n", i->where);
1712 printf("\t What: %s\n", i->what);
1715 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1717 LIST_FOREACH(exec, p, i->exec) {
1720 /* Only show exited processes here */
1724 t = strv_join(p->argv, " ");
1725 printf("\t Process: %u (%s, code=%s, ", p->pid, strna(t), sigchld_code_to_string(p->code));
1728 if (p->code == CLD_EXITED) {
1731 printf("status=%i", p->status);
1733 #ifdef HAVE_SYSV_COMPAT
1734 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1736 if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1741 printf("signal=%s", signal_to_string(p->status));
1744 if (i->main_pid == p->pid &&
1745 i->start_timestamp == p->start_timestamp &&
1746 i->exit_timestamp == p->start_timestamp)
1747 /* Let's not show this twice */
1750 if (p->pid == i->control_pid)
1754 if (i->main_pid > 0 || i->control_pid > 0) {
1757 if (i->main_pid > 0) {
1758 printf("Main PID: %u", (unsigned) i->main_pid);
1762 get_process_name(i->main_pid, &t);
1767 } else if (i->exit_code > 0) {
1768 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1770 if (i->exit_code == CLD_EXITED) {
1773 printf("status=%i", i->exit_status);
1775 #ifdef HAVE_SYSV_COMPAT
1776 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1778 if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
1783 printf("signal=%s", signal_to_string(i->exit_status));
1788 if (i->main_pid > 0 && i->control_pid > 0)
1791 if (i->control_pid > 0) {
1794 printf(" Control: %u", (unsigned) i->control_pid);
1796 get_process_name(i->control_pid, &t);
1807 printf("\t Status: \"%s\"\n", i->status_text);
1809 if (i->default_control_group) {
1812 printf("\t CGroup: %s\n", i->default_control_group);
1814 if ((c = columns()) > 18)
1819 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
1822 if (i->need_daemon_reload)
1823 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1824 ansi_highlight(true),
1825 ansi_highlight(false),
1826 arg_session ? "--session" : "--system");
1829 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1831 switch (dbus_message_iter_get_arg_type(iter)) {
1833 case DBUS_TYPE_STRING: {
1836 dbus_message_iter_get_basic(iter, &s);
1839 if (streq(name, "Id"))
1841 else if (streq(name, "LoadState"))
1843 else if (streq(name, "ActiveState"))
1844 i->active_state = s;
1845 else if (streq(name, "SubState"))
1847 else if (streq(name, "Description"))
1849 else if (streq(name, "FragmentPath"))
1851 #ifdef HAVE_SYSV_COMPAT
1852 else if (streq(name, "SysVPath")) {
1857 else if (streq(name, "DefaultControlGroup"))
1858 i->default_control_group = s;
1859 else if (streq(name, "StatusText"))
1861 else if (streq(name, "SysFSPath"))
1863 else if (streq(name, "Where"))
1865 else if (streq(name, "What"))
1867 else if (streq(name, "Following"))
1874 case DBUS_TYPE_BOOLEAN: {
1877 dbus_message_iter_get_basic(iter, &b);
1879 if (streq(name, "Accept"))
1881 else if (streq(name, "NeedDaemonReload"))
1882 i->need_daemon_reload = b;
1887 case DBUS_TYPE_UINT32: {
1890 dbus_message_iter_get_basic(iter, &u);
1892 if (streq(name, "MainPID")) {
1894 i->main_pid = (pid_t) u;
1897 } else if (streq(name, "ControlPID"))
1898 i->control_pid = (pid_t) u;
1899 else if (streq(name, "ExecMainPID")) {
1901 i->main_pid = (pid_t) u;
1902 } else if (streq(name, "NAccepted"))
1904 else if (streq(name, "NConnections"))
1905 i->n_connections = u;
1910 case DBUS_TYPE_INT32: {
1913 dbus_message_iter_get_basic(iter, &j);
1915 if (streq(name, "ExecMainCode"))
1916 i->exit_code = (int) j;
1917 else if (streq(name, "ExecMainStatus"))
1918 i->exit_status = (int) j;
1923 case DBUS_TYPE_UINT64: {
1926 dbus_message_iter_get_basic(iter, &u);
1928 if (streq(name, "ExecMainStartTimestamp"))
1929 i->start_timestamp = (usec_t) u;
1930 else if (streq(name, "ExecMainExitTimestamp"))
1931 i->exit_timestamp = (usec_t) u;
1932 else if (streq(name, "ActiveEnterTimestamp"))
1933 i->active_enter_timestamp = (usec_t) u;
1934 else if (streq(name, "InactiveEnterTimestamp"))
1935 i->inactive_enter_timestamp = (usec_t) u;
1936 else if (streq(name, "InactiveExitTimestamp"))
1937 i->inactive_exit_timestamp = (usec_t) u;
1938 else if (streq(name, "ActiveExitTimestamp"))
1939 i->active_exit_timestamp = (usec_t) u;
1944 case DBUS_TYPE_ARRAY: {
1946 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
1947 startswith(name, "Exec")) {
1948 DBusMessageIter sub;
1950 dbus_message_iter_recurse(iter, &sub);
1951 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1952 ExecStatusInfo *info;
1955 if (!(info = new0(ExecStatusInfo, 1)))
1958 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
1963 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
1965 dbus_message_iter_next(&sub);
1976 static int print_property(const char *name, DBusMessageIter *iter) {
1980 /* This is a low-level property printer, see
1981 * print_status_info() for the nicer output */
1983 if (arg_property && !strv_find(arg_property, name))
1986 switch (dbus_message_iter_get_arg_type(iter)) {
1988 case DBUS_TYPE_STRING: {
1990 dbus_message_iter_get_basic(iter, &s);
1992 if (arg_all || s[0])
1993 printf("%s=%s\n", name, s);
1998 case DBUS_TYPE_BOOLEAN: {
2000 dbus_message_iter_get_basic(iter, &b);
2001 printf("%s=%s\n", name, yes_no(b));
2006 case DBUS_TYPE_UINT64: {
2008 dbus_message_iter_get_basic(iter, &u);
2010 /* Yes, heuristics! But we can change this check
2011 * should it turn out to not be sufficient */
2013 if (strstr(name, "Timestamp")) {
2014 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
2016 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
2017 printf("%s=%s\n", name, strempty(t));
2018 } else if (strstr(name, "USec")) {
2019 char timespan[FORMAT_TIMESPAN_MAX];
2021 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
2023 printf("%s=%llu\n", name, (unsigned long long) u);
2028 case DBUS_TYPE_UINT32: {
2030 dbus_message_iter_get_basic(iter, &u);
2032 if (strstr(name, "UMask") || strstr(name, "Mode"))
2033 printf("%s=%04o\n", name, u);
2035 printf("%s=%u\n", name, (unsigned) u);
2040 case DBUS_TYPE_INT32: {
2042 dbus_message_iter_get_basic(iter, &i);
2044 printf("%s=%i\n", name, (int) i);
2048 case DBUS_TYPE_DOUBLE: {
2050 dbus_message_iter_get_basic(iter, &d);
2052 printf("%s=%g\n", name, d);
2056 case DBUS_TYPE_STRUCT: {
2057 DBusMessageIter sub;
2058 dbus_message_iter_recurse(iter, &sub);
2060 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2063 dbus_message_iter_get_basic(&sub, &u);
2066 printf("%s=%u\n", name, (unsigned) u);
2068 printf("%s=\n", name);
2071 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2074 dbus_message_iter_get_basic(&sub, &s);
2076 if (arg_all || s[0])
2077 printf("%s=%s\n", name, s);
2085 case DBUS_TYPE_ARRAY:
2087 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2088 DBusMessageIter sub;
2091 dbus_message_iter_recurse(iter, &sub);
2093 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2094 printf("%s=", name);
2096 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2099 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2100 dbus_message_iter_get_basic(&sub, &s);
2101 printf("%s%s", space ? " " : "", s);
2104 dbus_message_iter_next(&sub);
2112 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2113 DBusMessageIter sub;
2115 dbus_message_iter_recurse(iter, &sub);
2117 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2118 printf("%s=", name);
2120 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2123 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2124 dbus_message_iter_get_basic(&sub, &u);
2127 dbus_message_iter_next(&sub);
2135 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2136 DBusMessageIter sub, sub2;
2138 dbus_message_iter_recurse(iter, &sub);
2139 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2140 const char *type, *path;
2142 dbus_message_iter_recurse(&sub, &sub2);
2144 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2145 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2146 printf("%s=%s\n", type, path);
2148 dbus_message_iter_next(&sub);
2153 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2154 DBusMessageIter sub, sub2;
2156 dbus_message_iter_recurse(iter, &sub);
2157 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2159 uint64_t value, next_elapse;
2161 dbus_message_iter_recurse(&sub, &sub2);
2163 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2164 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2165 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2166 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2168 printf("%s={ value=%s ; next_elapse=%s }\n",
2170 format_timespan(timespan1, sizeof(timespan1), value),
2171 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2174 dbus_message_iter_next(&sub);
2179 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2180 DBusMessageIter sub;
2182 dbus_message_iter_recurse(iter, &sub);
2183 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2184 ExecStatusInfo info;
2187 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2188 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2191 t = strv_join(info.argv, " ");
2193 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2197 yes_no(info.ignore),
2198 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2199 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2200 (unsigned) info. pid,
2201 sigchld_code_to_string(info.code),
2203 info.code == CLD_EXITED ? "" : "/",
2204 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2210 strv_free(info.argv);
2212 dbus_message_iter_next(&sub);
2222 printf("%s=[unprintable]\n", name);
2227 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2228 DBusMessage *m = NULL, *reply = NULL;
2229 const char *interface = "";
2232 DBusMessageIter iter, sub, sub2, sub3;
2233 UnitStatusInfo info;
2241 dbus_error_init(&error);
2243 if (!(m = dbus_message_new_method_call(
2244 "org.freedesktop.systemd1",
2246 "org.freedesktop.DBus.Properties",
2248 log_error("Could not allocate message.");
2253 if (!dbus_message_append_args(m,
2254 DBUS_TYPE_STRING, &interface,
2255 DBUS_TYPE_INVALID)) {
2256 log_error("Could not append arguments to message.");
2261 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2262 log_error("Failed to issue method call: %s", bus_error_message(&error));
2267 if (!dbus_message_iter_init(reply, &iter) ||
2268 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2269 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2270 log_error("Failed to parse reply.");
2275 dbus_message_iter_recurse(&iter, &sub);
2282 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2285 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2286 log_error("Failed to parse reply.");
2291 dbus_message_iter_recurse(&sub, &sub2);
2293 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2294 log_error("Failed to parse reply.");
2299 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2300 log_error("Failed to parse reply.");
2305 dbus_message_iter_recurse(&sub2, &sub3);
2307 if (show_properties)
2308 r = print_property(name, &sub3);
2310 r = status_property(name, &sub3, &info);
2313 log_error("Failed to parse reply.");
2318 dbus_message_iter_next(&sub);
2323 if (!show_properties)
2324 print_status_info(&info);
2326 if (!streq_ptr(info.active_state, "active") &&
2327 !streq_ptr(info.active_state, "reloading"))
2328 /* According to LSB: "program not running" */
2331 while ((p = info.exec)) {
2332 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2333 exec_status_info_free(p);
2338 dbus_message_unref(m);
2341 dbus_message_unref(reply);
2343 dbus_error_free(&error);
2348 static int show(DBusConnection *bus, char **args, unsigned n) {
2349 DBusMessage *m = NULL, *reply = NULL;
2353 bool show_properties, new_line = false;
2358 dbus_error_init(&error);
2360 show_properties = !streq(args[0], "status");
2362 if (show_properties && n <= 1) {
2363 /* If not argument is specified inspect the manager
2366 ret = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2370 for (i = 1; i < n; i++) {
2371 const char *path = NULL;
2374 if (safe_atou32(args[i], &id) < 0) {
2376 /* Interpret as unit name */
2378 if (!(m = dbus_message_new_method_call(
2379 "org.freedesktop.systemd1",
2380 "/org/freedesktop/systemd1",
2381 "org.freedesktop.systemd1.Manager",
2383 log_error("Could not allocate message.");
2388 if (!dbus_message_append_args(m,
2389 DBUS_TYPE_STRING, &args[i],
2390 DBUS_TYPE_INVALID)) {
2391 log_error("Could not append arguments to message.");
2396 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2398 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2399 log_error("Failed to issue method call: %s", bus_error_message(&error));
2404 dbus_error_free(&error);
2406 dbus_message_unref(m);
2407 if (!(m = dbus_message_new_method_call(
2408 "org.freedesktop.systemd1",
2409 "/org/freedesktop/systemd1",
2410 "org.freedesktop.systemd1.Manager",
2412 log_error("Could not allocate message.");
2417 if (!dbus_message_append_args(m,
2418 DBUS_TYPE_STRING, &args[i],
2419 DBUS_TYPE_INVALID)) {
2420 log_error("Could not append arguments to message.");
2425 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2426 log_error("Failed to issue method call: %s", bus_error_message(&error));
2428 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2429 ret = 4; /* According to LSB: "program or service status is unknown" */
2436 } else if (show_properties) {
2438 /* Interpret as job id */
2440 if (!(m = dbus_message_new_method_call(
2441 "org.freedesktop.systemd1",
2442 "/org/freedesktop/systemd1",
2443 "org.freedesktop.systemd1.Manager",
2445 log_error("Could not allocate message.");
2450 if (!dbus_message_append_args(m,
2451 DBUS_TYPE_UINT32, &id,
2452 DBUS_TYPE_INVALID)) {
2453 log_error("Could not append arguments to message.");
2458 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2459 log_error("Failed to issue method call: %s", bus_error_message(&error));
2465 /* Interpret as PID */
2467 if (!(m = dbus_message_new_method_call(
2468 "org.freedesktop.systemd1",
2469 "/org/freedesktop/systemd1",
2470 "org.freedesktop.systemd1.Manager",
2472 log_error("Could not allocate message.");
2477 if (!dbus_message_append_args(m,
2478 DBUS_TYPE_UINT32, &id,
2479 DBUS_TYPE_INVALID)) {
2480 log_error("Could not append arguments to message.");
2485 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2486 log_error("Failed to issue method call: %s", bus_error_message(&error));
2492 if (!dbus_message_get_args(reply, &error,
2493 DBUS_TYPE_OBJECT_PATH, &path,
2494 DBUS_TYPE_INVALID)) {
2495 log_error("Failed to parse reply: %s", bus_error_message(&error));
2500 if ((r = show_one(bus, path, show_properties, &new_line)) != 0)
2503 dbus_message_unref(m);
2504 dbus_message_unref(reply);
2510 dbus_message_unref(m);
2513 dbus_message_unref(reply);
2515 dbus_error_free(&error);
2520 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2522 DBusMessage *m = NULL, *reply = NULL;
2527 dbus_error_init(&error);
2529 log_debug("Got D-Bus request: %s.%s() on %s",
2530 dbus_message_get_interface(message),
2531 dbus_message_get_member(message),
2532 dbus_message_get_path(message));
2534 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2535 log_error("Warning! D-Bus connection terminated.");
2536 dbus_connection_close(connection);
2538 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2539 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2540 const char *id, *path;
2542 if (!dbus_message_get_args(message, &error,
2543 DBUS_TYPE_STRING, &id,
2544 DBUS_TYPE_OBJECT_PATH, &path,
2546 log_error("Failed to parse message: %s", bus_error_message(&error));
2547 else if (streq(dbus_message_get_member(message), "UnitNew"))
2548 printf("Unit %s added.\n", id);
2550 printf("Unit %s removed.\n", id);
2552 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2553 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2557 if (!dbus_message_get_args(message, &error,
2558 DBUS_TYPE_UINT32, &id,
2559 DBUS_TYPE_OBJECT_PATH, &path,
2561 log_error("Failed to parse message: %s", bus_error_message(&error));
2562 else if (streq(dbus_message_get_member(message), "JobNew"))
2563 printf("Job %u added.\n", id);
2565 printf("Job %u removed.\n", id);
2568 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2570 const char *path, *interface, *property = "Id";
2571 DBusMessageIter iter, sub;
2573 path = dbus_message_get_path(message);
2575 if (!dbus_message_get_args(message, &error,
2576 DBUS_TYPE_STRING, &interface,
2577 DBUS_TYPE_INVALID)) {
2578 log_error("Failed to parse message: %s", bus_error_message(&error));
2582 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2583 !streq(interface, "org.freedesktop.systemd1.Unit"))
2586 if (!(m = dbus_message_new_method_call(
2587 "org.freedesktop.systemd1",
2589 "org.freedesktop.DBus.Properties",
2591 log_error("Could not allocate message.");
2595 if (!dbus_message_append_args(m,
2596 DBUS_TYPE_STRING, &interface,
2597 DBUS_TYPE_STRING, &property,
2598 DBUS_TYPE_INVALID)) {
2599 log_error("Could not append arguments to message.");
2603 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2604 log_error("Failed to issue method call: %s", bus_error_message(&error));
2608 if (!dbus_message_iter_init(reply, &iter) ||
2609 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2610 log_error("Failed to parse reply.");
2614 dbus_message_iter_recurse(&iter, &sub);
2616 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2619 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2620 log_error("Failed to parse reply.");
2624 dbus_message_iter_get_basic(&sub, &id);
2625 printf("Unit %s changed.\n", id);
2629 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2630 log_error("Failed to parse reply.");
2634 dbus_message_iter_get_basic(&sub, &id);
2635 printf("Job %u changed.\n", id);
2641 dbus_message_unref(m);
2644 dbus_message_unref(reply);
2646 dbus_error_free(&error);
2647 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2651 dbus_message_unref(m);
2654 dbus_message_unref(reply);
2656 dbus_error_free(&error);
2657 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2660 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2661 DBusMessage *m = NULL, *reply = NULL;
2665 dbus_error_init(&error);
2668 dbus_bus_add_match(bus,
2670 "sender='org.freedesktop.systemd1',"
2671 "interface='org.freedesktop.systemd1.Manager',"
2672 "path='/org/freedesktop/systemd1'",
2675 if (dbus_error_is_set(&error)) {
2676 log_error("Failed to add match: %s", bus_error_message(&error));
2681 dbus_bus_add_match(bus,
2683 "sender='org.freedesktop.systemd1',"
2684 "interface='org.freedesktop.DBus.Properties',"
2685 "member='PropertiesChanged'",
2688 if (dbus_error_is_set(&error)) {
2689 log_error("Failed to add match: %s", bus_error_message(&error));
2695 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2696 log_error("Failed to add filter.");
2701 if (!(m = dbus_message_new_method_call(
2702 "org.freedesktop.systemd1",
2703 "/org/freedesktop/systemd1",
2704 "org.freedesktop.systemd1.Manager",
2706 log_error("Could not allocate message.");
2711 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2712 log_error("Failed to issue method call: %s", bus_error_message(&error));
2717 while (dbus_connection_read_write_dispatch(bus, -1))
2724 /* This is slightly dirty, since we don't undo the filter or the matches. */
2727 dbus_message_unref(m);
2730 dbus_message_unref(reply);
2732 dbus_error_free(&error);
2737 static int dump(DBusConnection *bus, char **args, unsigned n) {
2738 DBusMessage *m = NULL, *reply = NULL;
2743 dbus_error_init(&error);
2745 if (!(m = dbus_message_new_method_call(
2746 "org.freedesktop.systemd1",
2747 "/org/freedesktop/systemd1",
2748 "org.freedesktop.systemd1.Manager",
2750 log_error("Could not allocate message.");
2754 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2755 log_error("Failed to issue method call: %s", bus_error_message(&error));
2760 if (!dbus_message_get_args(reply, &error,
2761 DBUS_TYPE_STRING, &text,
2762 DBUS_TYPE_INVALID)) {
2763 log_error("Failed to parse reply: %s", bus_error_message(&error));
2768 fputs(text, stdout);
2774 dbus_message_unref(m);
2777 dbus_message_unref(reply);
2779 dbus_error_free(&error);
2784 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2785 DBusMessage *m = NULL, *reply = NULL;
2788 const char *name = "", *path, *id;
2789 dbus_bool_t cleanup = FALSE;
2790 DBusMessageIter iter, sub;
2792 *interface = "org.freedesktop.systemd1.Unit",
2795 dbus_error_init(&error);
2797 if (!(m = dbus_message_new_method_call(
2798 "org.freedesktop.systemd1",
2799 "/org/freedesktop/systemd1",
2800 "org.freedesktop.systemd1.Manager",
2801 "CreateSnapshot"))) {
2802 log_error("Could not allocate message.");
2809 if (!dbus_message_append_args(m,
2810 DBUS_TYPE_STRING, &name,
2811 DBUS_TYPE_BOOLEAN, &cleanup,
2812 DBUS_TYPE_INVALID)) {
2813 log_error("Could not append arguments to message.");
2818 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2819 log_error("Failed to issue method call: %s", bus_error_message(&error));
2824 if (!dbus_message_get_args(reply, &error,
2825 DBUS_TYPE_OBJECT_PATH, &path,
2826 DBUS_TYPE_INVALID)) {
2827 log_error("Failed to parse reply: %s", bus_error_message(&error));
2832 dbus_message_unref(m);
2833 if (!(m = dbus_message_new_method_call(
2834 "org.freedesktop.systemd1",
2836 "org.freedesktop.DBus.Properties",
2838 log_error("Could not allocate message.");
2842 if (!dbus_message_append_args(m,
2843 DBUS_TYPE_STRING, &interface,
2844 DBUS_TYPE_STRING, &property,
2845 DBUS_TYPE_INVALID)) {
2846 log_error("Could not append arguments to message.");
2851 dbus_message_unref(reply);
2852 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2853 log_error("Failed to issue method call: %s", bus_error_message(&error));
2858 if (!dbus_message_iter_init(reply, &iter) ||
2859 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2860 log_error("Failed to parse reply.");
2865 dbus_message_iter_recurse(&iter, &sub);
2867 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2868 log_error("Failed to parse reply.");
2873 dbus_message_iter_get_basic(&sub, &id);
2881 dbus_message_unref(m);
2884 dbus_message_unref(reply);
2886 dbus_error_free(&error);
2891 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2892 DBusMessage *m = NULL, *reply = NULL;
2900 dbus_error_init(&error);
2902 for (i = 1; i < n; i++) {
2903 const char *path = NULL;
2905 if (!(m = dbus_message_new_method_call(
2906 "org.freedesktop.systemd1",
2907 "/org/freedesktop/systemd1",
2908 "org.freedesktop.systemd1.Manager",
2910 log_error("Could not allocate message.");
2915 if (!dbus_message_append_args(m,
2916 DBUS_TYPE_STRING, &args[i],
2917 DBUS_TYPE_INVALID)) {
2918 log_error("Could not append arguments to message.");
2923 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2924 log_error("Failed to issue method call: %s", bus_error_message(&error));
2929 if (!dbus_message_get_args(reply, &error,
2930 DBUS_TYPE_OBJECT_PATH, &path,
2931 DBUS_TYPE_INVALID)) {
2932 log_error("Failed to parse reply: %s", bus_error_message(&error));
2937 dbus_message_unref(m);
2938 if (!(m = dbus_message_new_method_call(
2939 "org.freedesktop.systemd1",
2941 "org.freedesktop.systemd1.Snapshot",
2943 log_error("Could not allocate message.");
2948 dbus_message_unref(reply);
2949 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2950 log_error("Failed to issue method call: %s", bus_error_message(&error));
2955 dbus_message_unref(m);
2956 dbus_message_unref(reply);
2964 dbus_message_unref(m);
2967 dbus_message_unref(reply);
2969 dbus_error_free(&error);
2974 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2975 DBusMessage *m = NULL, *reply = NULL;
2980 dbus_error_init(&error);
2982 if (arg_action == ACTION_RELOAD)
2984 else if (arg_action == ACTION_REEXEC)
2985 method = "Reexecute";
2987 assert(arg_action == ACTION_SYSTEMCTL);
2990 streq(args[0], "clear-jobs") ||
2991 streq(args[0], "cancel") ? "ClearJobs" :
2992 streq(args[0], "daemon-reexec") ? "Reexecute" :
2993 streq(args[0], "reset-failed") ? "ResetFailed" :
2994 streq(args[0], "halt") ? "Halt" :
2995 streq(args[0], "poweroff") ? "PowerOff" :
2996 streq(args[0], "reboot") ? "Reboot" :
2997 streq(args[0], "kexec") ? "KExec" :
2998 streq(args[0], "exit") ? "Exit" :
2999 /* "daemon-reload" */ "Reload";
3002 if (!(m = dbus_message_new_method_call(
3003 "org.freedesktop.systemd1",
3004 "/org/freedesktop/systemd1",
3005 "org.freedesktop.systemd1.Manager",
3007 log_error("Could not allocate message.");
3011 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3013 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3014 /* There's always a fallback possible for
3015 * legacy actions. */
3020 log_error("Failed to issue method call: %s", bus_error_message(&error));
3029 dbus_message_unref(m);
3032 dbus_message_unref(reply);
3034 dbus_error_free(&error);
3039 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3040 DBusMessage *m = NULL, *reply = NULL;
3046 dbus_error_init(&error);
3049 return daemon_reload(bus, args, n);
3051 for (i = 1; i < n; i++) {
3053 if (!(m = dbus_message_new_method_call(
3054 "org.freedesktop.systemd1",
3055 "/org/freedesktop/systemd1",
3056 "org.freedesktop.systemd1.Manager",
3057 "ResetFailedUnit"))) {
3058 log_error("Could not allocate message.");
3063 if (!dbus_message_append_args(m,
3064 DBUS_TYPE_STRING, args + i,
3065 DBUS_TYPE_INVALID)) {
3066 log_error("Could not append arguments to message.");
3071 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3072 log_error("Failed to issue method call: %s", bus_error_message(&error));
3077 dbus_message_unref(m);
3078 dbus_message_unref(reply);
3086 dbus_message_unref(m);
3089 dbus_message_unref(reply);
3091 dbus_error_free(&error);
3096 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3097 DBusMessage *m = NULL, *reply = NULL;
3099 DBusMessageIter iter, sub, sub2;
3102 *interface = "org.freedesktop.systemd1.Manager",
3103 *property = "Environment";
3105 dbus_error_init(&error);
3107 if (!(m = dbus_message_new_method_call(
3108 "org.freedesktop.systemd1",
3109 "/org/freedesktop/systemd1",
3110 "org.freedesktop.DBus.Properties",
3112 log_error("Could not allocate message.");
3116 if (!dbus_message_append_args(m,
3117 DBUS_TYPE_STRING, &interface,
3118 DBUS_TYPE_STRING, &property,
3119 DBUS_TYPE_INVALID)) {
3120 log_error("Could not append arguments to message.");
3125 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3126 log_error("Failed to issue method call: %s", bus_error_message(&error));
3131 if (!dbus_message_iter_init(reply, &iter) ||
3132 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3133 log_error("Failed to parse reply.");
3138 dbus_message_iter_recurse(&iter, &sub);
3140 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3141 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3142 log_error("Failed to parse reply.");
3147 dbus_message_iter_recurse(&sub, &sub2);
3149 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3152 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3153 log_error("Failed to parse reply.");
3158 dbus_message_iter_get_basic(&sub2, &text);
3159 printf("%s\n", text);
3161 dbus_message_iter_next(&sub2);
3168 dbus_message_unref(m);
3171 dbus_message_unref(reply);
3173 dbus_error_free(&error);
3178 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3179 DBusMessage *m = NULL, *reply = NULL;
3183 DBusMessageIter iter, sub;
3186 dbus_error_init(&error);
3188 method = streq(args[0], "set-environment")
3190 : "UnsetEnvironment";
3192 if (!(m = dbus_message_new_method_call(
3193 "org.freedesktop.systemd1",
3194 "/org/freedesktop/systemd1",
3195 "org.freedesktop.systemd1.Manager",
3198 log_error("Could not allocate message.");
3202 dbus_message_iter_init_append(m, &iter);
3204 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3205 log_error("Could not append arguments to message.");
3210 for (i = 1; i < n; i++)
3211 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3212 log_error("Could not append arguments to message.");
3217 if (!dbus_message_iter_close_container(&iter, &sub)) {
3218 log_error("Could not append arguments to message.");
3223 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3224 log_error("Failed to issue method call: %s", bus_error_message(&error));
3233 dbus_message_unref(m);
3236 dbus_message_unref(reply);
3238 dbus_error_free(&error);
3251 static Hashmap *will_install = NULL, *have_installed = NULL;
3252 static Set *remove_symlinks_to = NULL;
3253 static unsigned n_symlinks = 0;
3255 static void install_info_free(InstallInfo *i) {
3260 strv_free(i->aliases);
3261 strv_free(i->wanted_by);
3265 static void install_info_hashmap_free(Hashmap *m) {
3268 while ((i = hashmap_steal_first(m)))
3269 install_info_free(i);
3274 static int install_info_add(const char *name) {
3278 assert(will_install);
3280 if (!unit_name_is_valid_no_type(name, true)) {
3281 log_warning("Unit name %s is not a valid unit name.", name);
3285 if (hashmap_get(have_installed, name) ||
3286 hashmap_get(will_install, name))
3289 if (!(i = new0(InstallInfo, 1))) {
3294 if (!(i->name = strdup(name))) {
3299 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3306 install_info_free(i);
3311 static int config_parse_also(
3312 const char *filename,
3314 const char *section,
3328 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3332 if (!(n = strndup(w, l)))
3335 if ((r = install_info_add(n)) < 0) {
3336 log_warning("Cannot install unit %s: %s", n, strerror(-r));
3347 static int mark_symlink_for_removal(const char *p) {
3352 assert(path_is_absolute(p));
3354 if (!remove_symlinks_to)
3357 if (!(n = strdup(p)))
3360 path_kill_slashes(n);
3362 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3364 return r == -EEXIST ? 0 : r;
3370 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3379 if (!(d = fdopendir(fd))) {
3380 close_nointr_nofail(fd);
3386 while ((de = readdir(d))) {
3387 bool is_dir = false, is_link = false;
3389 if (ignore_file(de->d_name))
3392 if (de->d_type == DT_LNK)
3394 else if (de->d_type == DT_DIR)
3396 else if (de->d_type == DT_UNKNOWN) {
3399 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3400 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3407 is_link = S_ISLNK(st.st_mode);
3408 is_dir = S_ISDIR(st.st_mode);
3416 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3417 log_error("Failed to open %s/%s: %m", root, de->d_name);
3424 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3425 log_error("Failed to allocate directory string.");
3426 close_nointr_nofail(nfd);
3431 /* This will close nfd, regardless whether it succeeds or not */
3432 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3438 } else if (is_link) {
3442 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3443 log_error("Failed to allocate symlink string.");
3448 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3449 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3457 if ((c = canonicalize_file_name(dest))) {
3458 /* This might fail if the destination
3459 * is already removed */
3465 path_kill_slashes(dest);
3466 if (set_get(remove_symlinks_to, dest)) {
3469 log_info("rm '%s'", p);
3471 if (unlink(p) < 0) {
3472 log_error("Cannot unlink symlink %s: %m", p);
3477 rmdir_parents(p, config_path);
3478 path_kill_slashes(p);
3480 if (!set_get(remove_symlinks_to, p)) {
3482 if ((r = mark_symlink_for_removal(p)) < 0) {
3501 static int remove_marked_symlinks(const char *config_path) {
3505 assert(config_path);
3507 if (set_size(remove_symlinks_to) <= 0)
3510 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3517 if ((cfd = dup(fd)) < 0) {
3522 /* This takes possession of cfd and closes it */
3523 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3529 close_nointr_nofail(fd);
3534 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3541 if (streq(verb, "enable")) {
3544 mkdir_parents(new_path, 0755);
3546 if (symlink(old_path, new_path) >= 0) {
3549 log_info("ln -s '%s' '%s'", old_path, new_path);
3554 if (errno != EEXIST) {
3555 log_error("Cannot link %s to %s: %m", old_path, new_path);
3559 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3561 if (errno == EINVAL) {
3562 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3566 log_error("readlink() failed: %s", strerror(-r));
3570 if (streq(dest, old_path)) {
3576 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3585 log_info("ln -s '%s' '%s'", old_path, new_path);
3587 if (symlink(old_path, new_path) >= 0)
3590 log_error("Cannot link %s to %s: %m", old_path, new_path);
3593 } else if (streq(verb, "disable")) {
3596 if ((r = mark_symlink_for_removal(old_path)) < 0)
3599 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3600 if (errno == ENOENT)
3603 if (errno == EINVAL) {
3604 log_warning("File %s not a symlink, ignoring.", old_path);
3608 log_error("readlink() failed: %s", strerror(-r));
3612 if (!streq(dest, old_path)) {
3613 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3620 if ((r = mark_symlink_for_removal(new_path)) < 0)
3624 log_info("rm '%s'", new_path);
3626 if (unlink(new_path) >= 0)
3629 log_error("Cannot unlink %s: %m", new_path);
3632 } else if (streq(verb, "is-enabled")) {
3635 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3637 if (errno == ENOENT || errno == EINVAL)
3640 log_error("readlink() failed: %s", strerror(-r));
3644 if (streq(dest, old_path)) {
3652 assert_not_reached("Unknown action.");
3655 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3657 char *alias_path = NULL;
3662 assert(config_path);
3664 STRV_FOREACH(s, i->aliases) {
3667 if (!(alias_path = path_make_absolute(*s, config_path))) {
3668 log_error("Out of memory");
3673 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3676 if (streq(verb, "disable"))
3677 rmdir_parents(alias_path, config_path);
3687 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3689 char *alias_path = NULL;
3694 assert(config_path);
3696 STRV_FOREACH(s, i->wanted_by) {
3697 if (!unit_name_is_valid_no_type(*s, true)) {
3698 log_error("Invalid name %s.", *s);
3706 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3707 log_error("Out of memory");
3712 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3715 if (streq(verb, "disable"))
3716 rmdir_parents(alias_path, config_path);
3727 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3729 const ConfigItem items[] = {
3730 { "Alias", config_parse_strv, &i->aliases, "Install" },
3731 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3732 { "Also", config_parse_also, NULL, "Install" },
3734 { NULL, NULL, NULL, NULL }
3738 char *filename = NULL;
3745 STRV_FOREACH(p, paths->unit_path) {
3748 if (!(filename = path_make_absolute(i->name, *p))) {
3749 log_error("Out of memory");
3753 /* Ensure that we don't follow symlinks */
3754 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3755 if ((f = fdopen(fd, "re")))
3758 if (errno == ELOOP) {
3759 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3764 if (errno != ENOENT) {
3765 log_error("Failed to open %s: %m", filename);
3775 log_error("Couldn't find %s.", i->name);
3781 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3786 n_symlinks += strv_length(i->aliases);
3787 n_symlinks += strv_length(i->wanted_by);
3791 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3794 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3797 if ((r = mark_symlink_for_removal(filename)) < 0)
3800 if ((r = remove_marked_symlinks(config_path)) < 0)
3806 static char *get_config_path(void) {
3808 if (arg_session && arg_global)
3809 return strdup(SESSION_CONFIG_UNIT_PATH);
3814 if (session_config_home(&p) < 0)
3820 return strdup(SYSTEM_CONFIG_UNIT_PATH);
3823 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3827 char *config_path = NULL;
3830 const char *verb = args[0];
3832 dbus_error_init(&error);
3835 if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3836 log_error("Failed to determine lookup paths: %s", strerror(-r));
3840 if (!(config_path = get_config_path())) {
3841 log_error("Failed to determine config path");
3846 will_install = hashmap_new(string_hash_func, string_compare_func);
3847 have_installed = hashmap_new(string_hash_func, string_compare_func);
3849 if (!will_install || !have_installed) {
3850 log_error("Failed to allocate unit sets.");
3855 if (!arg_defaults && streq(verb, "disable"))
3856 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3857 log_error("Failed to allocate symlink sets.");
3862 for (j = 1; j < n; j++)
3863 if ((r = install_info_add(args[j])) < 0) {
3864 log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
3868 while ((i = hashmap_first(will_install))) {
3871 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3873 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3881 /* In test mode and found something */
3887 if (streq(verb, "is-enabled"))
3888 r = r > 0 ? 0 : -ENOENT;
3890 if (n_symlinks <= 0)
3891 log_warning("Unit files contain no applicable installation information. Ignoring.");
3894 /* Don't try to reload anything if the user asked us to not do this */
3896 /* Don't try to reload anything when updating a unit globally */
3898 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3899 (arg_session || sd_booted() > 0) &&
3900 /* Don't try to reload anything if we are running in a chroot environment */
3901 (arg_session || running_in_chroot() <= 0) ) {
3904 if ((q = daemon_reload(bus, args, n)) < 0)
3910 install_info_hashmap_free(will_install);
3911 install_info_hashmap_free(have_installed);
3913 set_free_free(remove_symlinks_to);
3915 lookup_paths_free(&paths);
3922 static int systemctl_help(void) {
3924 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3925 "Send control commands to or query the systemd manager.\n\n"
3926 " -h --help Show this help\n"
3927 " --version Show package version\n"
3928 " -t --type=TYPE List only units of a particular type\n"
3929 " -p --property=NAME Show only properties by this name\n"
3930 " -a --all Show all units/properties, including dead/empty ones\n"
3931 " --full Don't ellipsize unit names on output\n"
3932 " --fail When queueing a new job, fail if conflicting jobs are\n"
3934 " -q --quiet Suppress output\n"
3935 " --no-block Do not wait until operation finished\n"
3936 " --system Connect to system bus\n"
3937 " --session Connect to session bus\n"
3938 " --order When generating graph for dot, show only order\n"
3939 " --require When generating graph for dot, show only requirement\n"
3940 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3941 " --global Enable/disable unit files globally\n"
3942 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3944 " -f --force When enabling unit files, override existing symlinks\n"
3945 " When shutting down, execute action immediately\n"
3946 " --defaults When disabling unit files, remove default symlinks only\n\n"
3948 " list-units List units\n"
3949 " start [NAME...] Start (activate) one or more units\n"
3950 " stop [NAME...] Stop (deactivate) one or more units\n"
3951 " reload [NAME...] Reload one or more units\n"
3952 " restart [NAME...] Start or restart one or more units\n"
3953 " try-restart [NAME...] Restart one or more units if active\n"
3954 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3955 " otherwise start or restart\n"
3956 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3957 " otherwise restart if active\n"
3958 " isolate [NAME] Start one unit and stop all others\n"
3959 " is-active [NAME...] Check whether units are active\n"
3960 " status [NAME...|PID...] Show runtime status of one or more units\n"
3961 " show [NAME...|JOB...] Show properties of one or more\n"
3962 " units/jobs or the manager\n"
3963 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
3965 " enable [NAME...] Enable one or more unit files\n"
3966 " disable [NAME...] Disable one or more unit files\n"
3967 " is-enabled [NAME...] Check whether unit files are enabled\n"
3968 " load [NAME...] Load one or more units\n"
3969 " list-jobs List jobs\n"
3970 " cancel [JOB...] Cancel all, one, or more jobs\n"
3971 " monitor Monitor unit/job changes\n"
3972 " dump Dump server status\n"
3973 " dot Dump dependency graph for dot(1)\n"
3974 " snapshot [NAME] Create a snapshot\n"
3975 " delete [NAME...] Remove one or more snapshots\n"
3976 " daemon-reload Reload systemd manager configuration\n"
3977 " daemon-reexec Reexecute systemd manager\n"
3978 " show-environment Dump environment\n"
3979 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3980 " unset-environment [NAME...] Unset one or more environment variables\n"
3981 " default Enter system default mode\n"
3982 " rescue Enter system rescue mode\n"
3983 " emergency Enter system emergency mode\n"
3984 " halt Shut down and halt the system\n"
3985 " poweroff Shut down and power-off the system\n"
3986 " reboot Shut down and reboot the system\n"
3987 " kexec Shut down and reboot the system with kexec\n"
3988 " exit Ask for session termination\n",
3989 program_invocation_short_name);
3994 static int halt_help(void) {
3996 printf("%s [OPTIONS...]\n\n"
3997 "%s the system.\n\n"
3998 " --help Show this help\n"
3999 " --halt Halt the machine\n"
4000 " -p --poweroff Switch off the machine\n"
4001 " --reboot Reboot the machine\n"
4002 " -f --force Force immediate halt/power-off/reboot\n"
4003 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4004 " -d --no-wtmp Don't write wtmp record\n"
4005 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4006 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4007 program_invocation_short_name,
4008 arg_action == ACTION_REBOOT ? "Reboot" :
4009 arg_action == ACTION_POWEROFF ? "Power off" :
4015 static int shutdown_help(void) {
4017 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4018 "Shut down the system.\n\n"
4019 " --help Show this help\n"
4020 " -H --halt Halt the machine\n"
4021 " -P --poweroff Power-off the machine\n"
4022 " -r --reboot Reboot the machine\n"
4023 " -h Equivalent to --poweroff, overriden by --halt\n"
4024 " -k Don't halt/power-off/reboot, just send warnings\n"
4025 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4026 " -c Cancel a pending shutdown\n",
4027 program_invocation_short_name);
4032 static int telinit_help(void) {
4034 printf("%s [OPTIONS...] {COMMAND}\n\n"
4035 "Send control commands to the init daemon.\n\n"
4036 " --help Show this help\n"
4037 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4039 " 0 Power-off the machine\n"
4040 " 6 Reboot the machine\n"
4041 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4042 " 1, s, S Enter rescue mode\n"
4043 " q, Q Reload init daemon configuration\n"
4044 " u, U Reexecute init daemon\n",
4045 program_invocation_short_name);
4050 static int runlevel_help(void) {
4052 printf("%s [OPTIONS...]\n\n"
4053 "Prints the previous and current runlevel of the init system.\n\n"
4054 " --help Show this help\n",
4055 program_invocation_short_name);
4060 static int systemctl_parse_argv(int argc, char *argv[]) {
4077 static const struct option options[] = {
4078 { "help", no_argument, NULL, 'h' },
4079 { "version", no_argument, NULL, ARG_VERSION },
4080 { "type", required_argument, NULL, 't' },
4081 { "property", required_argument, NULL, 'p' },
4082 { "all", no_argument, NULL, 'a' },
4083 { "full", no_argument, NULL, ARG_FULL },
4084 { "fail", no_argument, NULL, ARG_FAIL },
4085 { "session", no_argument, NULL, ARG_SESSION },
4086 { "system", no_argument, NULL, ARG_SYSTEM },
4087 { "global", no_argument, NULL, ARG_GLOBAL },
4088 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4089 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4090 { "quiet", no_argument, NULL, 'q' },
4091 { "order", no_argument, NULL, ARG_ORDER },
4092 { "require", no_argument, NULL, ARG_REQUIRE },
4093 { "force", no_argument, NULL, 'f' },
4094 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4095 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4096 { NULL, 0, NULL, 0 }
4104 while ((c = getopt_long(argc, argv, "ht:p:aqf", options, NULL)) >= 0) {
4113 puts(PACKAGE_STRING);
4115 puts(SYSTEMD_FEATURES);
4125 if (!(l = strv_append(arg_property, optarg)))
4128 strv_free(arg_property);
4131 /* If the user asked for a particular
4132 * property, show it to him, even if it is
4151 arg_session = false;
4155 arg_no_block = true;
4163 arg_dot = DOT_ORDER;
4167 arg_dot = DOT_REQUIRE;
4183 arg_no_reload = true;
4192 arg_defaults = true;
4199 log_error("Unknown option code %c", c);
4207 static int halt_parse_argv(int argc, char *argv[]) {
4216 static const struct option options[] = {
4217 { "help", no_argument, NULL, ARG_HELP },
4218 { "halt", no_argument, NULL, ARG_HALT },
4219 { "poweroff", no_argument, NULL, 'p' },
4220 { "reboot", no_argument, NULL, ARG_REBOOT },
4221 { "force", no_argument, NULL, 'f' },
4222 { "wtmp-only", no_argument, NULL, 'w' },
4223 { "no-wtmp", no_argument, NULL, 'd' },
4224 { "no-sync", no_argument, NULL, 'n' },
4225 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4226 { NULL, 0, NULL, 0 }
4234 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4235 if (runlevel == '0' || runlevel == '6')
4236 arg_immediate = true;
4238 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4246 arg_action = ACTION_HALT;
4250 if (arg_action != ACTION_REBOOT)
4251 arg_action = ACTION_POWEROFF;
4255 arg_action = ACTION_REBOOT;
4259 arg_immediate = true;
4280 /* Compatibility nops */
4287 log_error("Unknown option code %c", c);
4292 if (optind < argc) {
4293 log_error("Too many arguments.");
4300 static int parse_time_spec(const char *t, usec_t *_u) {
4304 if (streq(t, "now"))
4306 else if (t[0] == '+') {
4309 if (safe_atou64(t + 1, &u) < 0)
4312 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4321 hour = strtol(t, &e, 10);
4322 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4325 minute = strtol(e+1, &e, 10);
4326 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4329 n = now(CLOCK_REALTIME);
4330 s = (time_t) (n / USEC_PER_SEC);
4333 assert_se(localtime_r(&s, &tm));
4335 tm.tm_hour = (int) hour;
4336 tm.tm_min = (int) minute;
4339 assert_se(s = mktime(&tm));
4341 *_u = (usec_t) s * USEC_PER_SEC;
4344 *_u += USEC_PER_DAY;
4350 static int shutdown_parse_argv(int argc, char *argv[]) {
4357 static const struct option options[] = {
4358 { "help", no_argument, NULL, ARG_HELP },
4359 { "halt", no_argument, NULL, 'H' },
4360 { "poweroff", no_argument, NULL, 'P' },
4361 { "reboot", no_argument, NULL, 'r' },
4362 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4363 { NULL, 0, NULL, 0 }
4371 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4379 arg_action = ACTION_HALT;
4383 arg_action = ACTION_POWEROFF;
4387 arg_action = ACTION_REBOOT;
4391 if (arg_action != ACTION_HALT)
4392 arg_action = ACTION_POWEROFF;
4405 /* Compatibility nops */
4409 arg_action = ACTION_CANCEL_SHUTDOWN;
4416 log_error("Unknown option code %c", c);
4421 if (argc > optind) {
4422 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4423 log_error("Failed to parse time specification: %s", argv[optind]);
4427 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4429 /* We skip the time argument */
4430 if (argc > optind + 1)
4431 arg_wall = argv + optind + 1;
4438 static int telinit_parse_argv(int argc, char *argv[]) {
4445 static const struct option options[] = {
4446 { "help", no_argument, NULL, ARG_HELP },
4447 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4448 { NULL, 0, NULL, 0 }
4451 static const struct {
4455 { '0', ACTION_POWEROFF },
4456 { '6', ACTION_REBOOT },
4457 { '1', ACTION_RESCUE },
4458 { '2', ACTION_RUNLEVEL2 },
4459 { '3', ACTION_RUNLEVEL3 },
4460 { '4', ACTION_RUNLEVEL4 },
4461 { '5', ACTION_RUNLEVEL5 },
4462 { 's', ACTION_RESCUE },
4463 { 'S', ACTION_RESCUE },
4464 { 'q', ACTION_RELOAD },
4465 { 'Q', ACTION_RELOAD },
4466 { 'u', ACTION_REEXEC },
4467 { 'U', ACTION_REEXEC }
4476 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4491 log_error("Unknown option code %c", c);
4496 if (optind >= argc) {
4501 if (optind + 1 < argc) {
4502 log_error("Too many arguments.");
4506 if (strlen(argv[optind]) != 1) {
4507 log_error("Expected single character argument.");
4511 for (i = 0; i < ELEMENTSOF(table); i++)
4512 if (table[i].from == argv[optind][0])
4515 if (i >= ELEMENTSOF(table)) {
4516 log_error("Unknown command %s.", argv[optind]);
4520 arg_action = table[i].to;
4527 static int runlevel_parse_argv(int argc, char *argv[]) {
4533 static const struct option options[] = {
4534 { "help", no_argument, NULL, ARG_HELP },
4535 { NULL, 0, NULL, 0 }
4543 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4554 log_error("Unknown option code %c", c);
4559 if (optind < argc) {
4560 log_error("Too many arguments.");
4567 static int parse_argv(int argc, char *argv[]) {
4571 if (program_invocation_short_name) {
4573 if (strstr(program_invocation_short_name, "halt")) {
4574 arg_action = ACTION_HALT;
4575 return halt_parse_argv(argc, argv);
4576 } else if (strstr(program_invocation_short_name, "poweroff")) {
4577 arg_action = ACTION_POWEROFF;
4578 return halt_parse_argv(argc, argv);
4579 } else if (strstr(program_invocation_short_name, "reboot")) {
4580 arg_action = ACTION_REBOOT;
4581 return halt_parse_argv(argc, argv);
4582 } else if (strstr(program_invocation_short_name, "shutdown")) {
4583 arg_action = ACTION_POWEROFF;
4584 return shutdown_parse_argv(argc, argv);
4585 } else if (strstr(program_invocation_short_name, "init")) {
4587 if (sd_booted() > 0) {
4588 arg_action = ACTION_INVALID;
4589 return telinit_parse_argv(argc, argv);
4591 /* Hmm, so some other init system is
4592 * running, we need to forward this
4593 * request to it. For now we simply
4594 * guess that it is Upstart. */
4596 execv("/lib/upstart/telinit", argv);
4598 log_error("Couldn't find an alternative telinit implementation to spawn.");
4602 } else if (strstr(program_invocation_short_name, "runlevel")) {
4603 arg_action = ACTION_RUNLEVEL;
4604 return runlevel_parse_argv(argc, argv);
4608 arg_action = ACTION_SYSTEMCTL;
4609 return systemctl_parse_argv(argc, argv);
4612 static int action_to_runlevel(void) {
4614 static const char table[_ACTION_MAX] = {
4615 [ACTION_HALT] = '0',
4616 [ACTION_POWEROFF] = '0',
4617 [ACTION_REBOOT] = '6',
4618 [ACTION_RUNLEVEL2] = '2',
4619 [ACTION_RUNLEVEL3] = '3',
4620 [ACTION_RUNLEVEL4] = '4',
4621 [ACTION_RUNLEVEL5] = '5',
4622 [ACTION_RESCUE] = '1'
4625 assert(arg_action < _ACTION_MAX);
4627 return table[arg_action];
4630 static int talk_upstart(void) {
4631 DBusMessage *m = NULL, *reply = NULL;
4633 int previous, rl, r;
4635 env1_buf[] = "RUNLEVEL=X",
4636 env2_buf[] = "PREVLEVEL=X";
4637 char *env1 = env1_buf, *env2 = env2_buf;
4638 const char *emit = "runlevel";
4639 dbus_bool_t b_false = FALSE;
4640 DBusMessageIter iter, sub;
4641 DBusConnection *bus;
4643 dbus_error_init(&error);
4645 if (!(rl = action_to_runlevel()))
4648 if (utmp_get_runlevel(&previous, NULL) < 0)
4651 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4652 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4657 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4662 if ((r = bus_check_peercred(bus)) < 0) {
4663 log_error("Failed to verify owner of bus.");
4667 if (!(m = dbus_message_new_method_call(
4668 "com.ubuntu.Upstart",
4669 "/com/ubuntu/Upstart",
4670 "com.ubuntu.Upstart0_6",
4673 log_error("Could not allocate message.");
4678 dbus_message_iter_init_append(m, &iter);
4680 env1_buf[sizeof(env1_buf)-2] = rl;
4681 env2_buf[sizeof(env2_buf)-2] = previous;
4683 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4684 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4685 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4686 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4687 !dbus_message_iter_close_container(&iter, &sub) ||
4688 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4689 log_error("Could not append arguments to message.");
4694 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4696 if (error_is_no_service(&error)) {
4701 log_error("Failed to issue method call: %s", bus_error_message(&error));
4710 dbus_message_unref(m);
4713 dbus_message_unref(reply);
4716 dbus_connection_flush(bus);
4717 dbus_connection_close(bus);
4718 dbus_connection_unref(bus);
4721 dbus_error_free(&error);
4726 static int talk_initctl(void) {
4727 struct init_request request;
4731 if (!(rl = action_to_runlevel()))
4735 request.magic = INIT_MAGIC;
4736 request.sleeptime = 0;
4737 request.cmd = INIT_CMD_RUNLVL;
4738 request.runlevel = rl;
4740 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4742 if (errno == ENOENT)
4745 log_error("Failed to open "INIT_FIFO": %m");
4750 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4751 close_nointr_nofail(fd);
4754 log_error("Failed to write to "INIT_FIFO": %m");
4755 return errno ? -errno : -EIO;
4761 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4763 static const struct {
4771 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4773 { "list-units", LESS, 1, list_units },
4774 { "list-jobs", EQUAL, 1, list_jobs },
4775 { "clear-jobs", EQUAL, 1, daemon_reload },
4776 { "load", MORE, 2, load_unit },
4777 { "cancel", MORE, 2, cancel_job },
4778 { "start", MORE, 2, start_unit },
4779 { "stop", MORE, 2, start_unit },
4780 { "reload", MORE, 2, start_unit },
4781 { "restart", MORE, 2, start_unit },
4782 { "try-restart", MORE, 2, start_unit },
4783 { "reload-or-restart", MORE, 2, start_unit },
4784 { "reload-or-try-restart", MORE, 2, start_unit },
4785 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4786 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4787 { "isolate", EQUAL, 2, start_unit },
4788 { "is-active", MORE, 2, check_unit },
4789 { "check", MORE, 2, check_unit },
4790 { "show", MORE, 1, show },
4791 { "status", MORE, 2, show },
4792 { "monitor", EQUAL, 1, monitor },
4793 { "dump", EQUAL, 1, dump },
4794 { "dot", EQUAL, 1, dot },
4795 { "snapshot", LESS, 2, snapshot },
4796 { "delete", MORE, 2, delete_snapshot },
4797 { "daemon-reload", EQUAL, 1, daemon_reload },
4798 { "daemon-reexec", EQUAL, 1, daemon_reload },
4799 { "show-environment", EQUAL, 1, show_enviroment },
4800 { "set-environment", MORE, 2, set_environment },
4801 { "unset-environment", MORE, 2, set_environment },
4802 { "halt", EQUAL, 1, start_special },
4803 { "poweroff", EQUAL, 1, start_special },
4804 { "reboot", EQUAL, 1, start_special },
4805 { "kexec", EQUAL, 1, start_special },
4806 { "default", EQUAL, 1, start_special },
4807 { "rescue", EQUAL, 1, start_special },
4808 { "emergency", EQUAL, 1, start_special },
4809 { "exit", EQUAL, 1, start_special },
4810 { "reset-failed", MORE, 1, reset_failed },
4811 { "enable", MORE, 2, enable_unit },
4812 { "disable", MORE, 2, enable_unit },
4813 { "is-enabled", MORE, 2, enable_unit }
4823 left = argc - optind;
4826 /* Special rule: no arguments means "list-units" */
4829 if (streq(argv[optind], "help")) {
4834 for (i = 0; i < ELEMENTSOF(verbs); i++)
4835 if (streq(argv[optind], verbs[i].verb))
4838 if (i >= ELEMENTSOF(verbs)) {
4839 log_error("Unknown operation %s", argv[optind]);
4844 switch (verbs[i].argc_cmp) {
4847 if (left != verbs[i].argc) {
4848 log_error("Invalid number of arguments.");
4855 if (left < verbs[i].argc) {
4856 log_error("Too few arguments.");
4863 if (left > verbs[i].argc) {
4864 log_error("Too many arguments.");
4871 assert_not_reached("Unknown comparison operator.");
4874 /* Require a bus connection for all operations but
4876 if (!streq(verbs[i].verb, "enable") &&
4877 !streq(verbs[i].verb, "disable") &&
4879 log_error("Failed to get D-Bus connection: %s", error->message);
4883 return verbs[i].dispatch(bus, argv + optind, left);
4886 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
4888 struct msghdr msghdr;
4890 union sockaddr_union sockaddr;
4891 struct shutdownd_command c;
4899 strncpy(c.wall_message, message, sizeof(c.wall_message));
4901 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4905 sockaddr.sa.sa_family = AF_UNIX;
4906 sockaddr.un.sun_path[0] = 0;
4907 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
4910 iovec.iov_base = (char*) &c;
4911 iovec.iov_len = sizeof(c);
4914 msghdr.msg_name = &sockaddr;
4915 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
4917 msghdr.msg_iov = &iovec;
4918 msghdr.msg_iovlen = 1;
4920 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
4921 close_nointr_nofail(fd);
4925 close_nointr_nofail(fd);
4929 static int reload_with_fallback(DBusConnection *bus) {
4932 /* First, try systemd via D-Bus. */
4933 if (daemon_reload(bus, NULL, 0) > 0)
4937 /* Nothing else worked, so let's try signals */
4938 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
4940 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
4941 log_error("kill() failed: %m");
4948 static int start_with_fallback(DBusConnection *bus) {
4951 /* First, try systemd via D-Bus. */
4952 if (start_unit(bus, NULL, 0) >= 0)
4956 /* Hmm, talking to systemd via D-Bus didn't work. Then
4957 * let's try to talk to Upstart via D-Bus. */
4958 if (talk_upstart() > 0)
4961 /* Nothing else worked, so let's try
4963 if (talk_initctl() > 0)
4966 log_error("Failed to talk to init daemon.");
4970 warn_wall(arg_action);
4974 static int halt_main(DBusConnection *bus) {
4977 if (geteuid() != 0) {
4978 log_error("Must be root.");
4984 char date[FORMAT_TIMESTAMP_MAX];
4986 m = strv_join(arg_wall, " ");
4987 r = send_shutdownd(arg_when,
4988 arg_action == ACTION_HALT ? 'H' :
4989 arg_action == ACTION_POWEROFF ? 'P' :
4996 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
4998 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
4999 format_timestamp(date, sizeof(date), arg_when));
5004 if (!arg_dry && !arg_immediate)
5005 return start_with_fallback(bus);
5008 if (sd_booted() > 0)
5009 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5010 else if ((r = utmp_put_shutdown(0)) < 0)
5011 log_warning("Failed to write utmp record: %s", strerror(-r));
5020 /* Make sure C-A-D is handled by the kernel from this
5022 reboot(RB_ENABLE_CAD);
5024 switch (arg_action) {
5027 log_info("Halting.");
5028 reboot(RB_HALT_SYSTEM);
5031 case ACTION_POWEROFF:
5032 log_info("Powering off.");
5033 reboot(RB_POWER_OFF);
5037 log_info("Rebooting.");
5038 reboot(RB_AUTOBOOT);
5042 assert_not_reached("Unknown halt action.");
5045 /* We should never reach this. */
5049 static int runlevel_main(void) {
5050 int r, runlevel, previous;
5052 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5053 printf("unknown\n");
5058 previous <= 0 ? 'N' : previous,
5059 runlevel <= 0 ? 'N' : runlevel);
5064 int main(int argc, char*argv[]) {
5065 int r, retval = EXIT_FAILURE;
5066 DBusConnection *bus = NULL;
5069 dbus_error_init(&error);
5071 log_parse_environment();
5074 if ((r = parse_argv(argc, argv)) < 0)
5077 retval = EXIT_SUCCESS;
5081 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5082 * let's shortcut this */
5083 if (arg_action == ACTION_RUNLEVEL) {
5084 r = runlevel_main();
5085 retval = r < 0 ? EXIT_FAILURE : r;
5089 bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5091 switch (arg_action) {
5093 case ACTION_SYSTEMCTL:
5094 r = systemctl_main(bus, argc, argv, &error);
5098 case ACTION_POWEROFF:
5103 case ACTION_RUNLEVEL2:
5104 case ACTION_RUNLEVEL3:
5105 case ACTION_RUNLEVEL4:
5106 case ACTION_RUNLEVEL5:
5108 case ACTION_EMERGENCY:
5109 case ACTION_DEFAULT:
5110 r = start_with_fallback(bus);
5115 r = reload_with_fallback(bus);
5118 case ACTION_CANCEL_SHUTDOWN:
5119 r = send_shutdownd(0, 0, false, NULL);
5122 case ACTION_INVALID:
5123 case ACTION_RUNLEVEL:
5125 assert_not_reached("Unknown action");
5128 retval = r < 0 ? EXIT_FAILURE : r;
5133 dbus_connection_flush(bus);
5134 dbus_connection_close(bus);
5135 dbus_connection_unref(bus);
5138 dbus_error_free(&error);
5142 strv_free(arg_property);