1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <sys/reboot.h>
28 #include <sys/ioctl.h>
32 #include <sys/socket.h>
35 #include <sys/prctl.h>
37 #include <dbus/dbus.h>
43 #include "utmp-wtmp.h"
47 #include "dbus-common.h"
48 #include "cgroup-show.h"
49 #include "cgroup-util.h"
51 #include "path-lookup.h"
52 #include "conf-parser.h"
53 #include "sd-daemon.h"
54 #include "shutdownd.h"
55 #include "exit-status.h"
56 #include "bus-errors.h"
58 #include "unit-name.h"
60 static const char *arg_type = NULL;
61 static char **arg_property = NULL;
62 static bool arg_all = false;
63 static const char *arg_job_mode = "replace";
64 static bool arg_user = false;
65 static bool arg_global = false;
66 static bool arg_immediate = false;
67 static bool arg_no_block = false;
68 static bool arg_no_pager = false;
69 static bool arg_no_wtmp = false;
70 static bool arg_no_sync = false;
71 static bool arg_no_wall = false;
72 static bool arg_no_reload = false;
73 static bool arg_dry = false;
74 static bool arg_quiet = false;
75 static bool arg_full = false;
76 static bool arg_force = false;
77 static bool arg_defaults = false;
78 static bool arg_ask_password = false;
79 static bool arg_failed = false;
80 static char **arg_wall = NULL;
81 static const char *arg_kill_who = NULL;
82 static const char *arg_kill_mode = NULL;
83 static const char *arg_root = NULL;
84 static int arg_signal = SIGTERM;
85 static usec_t arg_when = 0;
104 ACTION_CANCEL_SHUTDOWN,
106 } arg_action = ACTION_SYSTEMCTL;
112 static enum transport {
116 } arg_transport = TRANSPORT_NORMAL;
117 static const char *arg_host = NULL;
119 static bool private_bus = false;
121 static pid_t pager_pid = 0;
122 static pid_t agent_pid = 0;
124 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
125 static void pager_open(void);
127 static bool on_tty(void) {
130 /* Note that this is invoked relatively early, before we start
131 * the pager. That means the value we return reflects whether
132 * we originally were started on a tty, not if we currently
133 * are. But this is intended, since we want colour and so on
134 * when run in our own pager. */
136 if (_unlikely_(t < 0))
137 t = isatty(STDOUT_FILENO) > 0;
142 static void spawn_ask_password_agent(void) {
148 /* We check STDIN here, not STDOUT, since this is about input,
150 if (!isatty(STDIN_FILENO))
153 if (!arg_ask_password)
161 /* Spawns a temporary TTY agent, making sure it goes away when
164 if ((agent_pid = fork()) < 0)
167 if (agent_pid == 0) {
171 bool stdout_is_tty, stderr_is_tty;
173 /* Make sure the agent goes away when the parent dies */
174 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
177 /* Check whether our parent died before we were able
178 * to set the death signal */
179 if (getppid() != parent)
182 /* Don't leak fds to the agent */
183 close_all_fds(NULL, 0);
185 stdout_is_tty = isatty(STDOUT_FILENO);
186 stderr_is_tty = isatty(STDERR_FILENO);
188 if (!stdout_is_tty || !stderr_is_tty) {
189 /* Detach from stdout/stderr. and reopen
190 * /dev/tty for them. This is important to
191 * ensure that when systemctl is started via
192 * popen() or a similar call that expects to
193 * read EOF we actually do generate EOF and
194 * not delay this indefinitely by because we
195 * keep an unused copy of stdin around. */
196 if ((fd = open("/dev/tty", O_WRONLY)) < 0) {
197 log_error("Failed to open /dev/tty: %m");
202 dup2(fd, STDOUT_FILENO);
205 dup2(fd, STDERR_FILENO);
211 execl(SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, "--watch", NULL);
213 log_error("Unable to execute agent: %m");
218 static const char *ansi_highlight(bool b) {
223 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
226 static const char *ansi_highlight_green(bool b) {
231 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
234 static bool error_is_no_service(const DBusError *error) {
237 if (!dbus_error_is_set(error))
240 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
243 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
246 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
249 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
252 if (!dbus_error_is_set(error))
255 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
256 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
257 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
258 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
259 return EXIT_NOPERMISSION;
261 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
262 return EXIT_NOTINSTALLED;
264 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
265 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
266 return EXIT_NOTIMPLEMENTED;
268 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
269 return EXIT_NOTCONFIGURED;
277 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
282 if (dbus_message_iter_get_arg_type(iter) != type)
285 dbus_message_iter_get_basic(iter, data);
287 if (!dbus_message_iter_next(iter) != !next)
293 static void warn_wall(enum action action) {
294 static const char *table[_ACTION_MAX] = {
295 [ACTION_HALT] = "The system is going down for system halt NOW!",
296 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
297 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
298 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
299 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
300 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
309 if (!(p = strv_join(arg_wall, " "))) {
310 log_error("Failed to join strings.");
326 utmp_wall(table[action], NULL);
331 const char *description;
332 const char *load_state;
333 const char *active_state;
334 const char *sub_state;
335 const char *following;
336 const char *unit_path;
338 const char *job_type;
339 const char *job_path;
342 static int compare_unit_info(const void *a, const void *b) {
344 const struct unit_info *u = a, *v = b;
346 d1 = strrchr(u->id, '.');
347 d2 = strrchr(v->id, '.');
352 if ((r = strcasecmp(d1, d2)) != 0)
356 return strcasecmp(u->id, v->id);
359 static bool output_show_unit(const struct unit_info *u) {
363 return streq(u->active_state, "failed");
365 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
366 streq(dot+1, arg_type))) &&
367 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0);
370 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
371 unsigned active_len, sub_len, job_len, n_shown = 0;
372 const struct unit_info *u;
374 active_len = sizeof("ACTIVE")-1;
375 sub_len = sizeof("SUB")-1;
376 job_len = sizeof("JOB")-1;
378 for (u = unit_infos; u < unit_infos + c; u++) {
379 if (!output_show_unit(u))
382 active_len = MAX(active_len, strlen(u->active_state));
383 sub_len = MAX(sub_len, strlen(u->sub_state));
385 job_len = MAX(job_len, strlen(u->job_type));
389 printf("%-25s %-6s %-*s %-*s %-*s", "UNIT", "LOAD",
390 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
391 if (columns() >= 80+12 || arg_full || !arg_no_pager)
392 printf(" %s\n", "DESCRIPTION");
397 for (u = unit_infos; u < unit_infos + c; u++) {
400 const char *on_loaded, *off_loaded;
401 const char *on_active, *off_active;
403 if (!output_show_unit(u))
408 if (!streq(u->load_state, "loaded") &&
409 !streq(u->load_state, "banned")) {
410 on_loaded = ansi_highlight(true);
411 off_loaded = ansi_highlight(false);
413 on_loaded = off_loaded = "";
415 if (streq(u->active_state, "failed")) {
416 on_active = ansi_highlight(true);
417 off_active = ansi_highlight(false);
419 on_active = off_active = "";
421 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
423 printf("%-25s %s%-6s%s %s%-*s %-*s%s%n",
425 on_loaded, u->load_state, off_loaded,
426 on_active, active_len, u->active_state,
427 sub_len, u->sub_state, off_active,
432 a -= strlen(on_loaded) + strlen(off_loaded);
433 a -= strlen(on_active) + strlen(off_active);
436 printf(" %-*s", job_len, u->job_type);
440 if (a + b + 1 < columns()) {
442 printf(" %-*s", job_len, "");
444 if (arg_full || !arg_no_pager)
445 printf(" %s", u->description);
447 printf(" %.*s", columns() - a - b - 1, u->description);
454 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
455 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
456 "SUB = The low-level unit activation state, values depend on unit type.\n"
457 "JOB = Pending job for the unit.\n");
460 printf("\n%u units listed.\n", n_shown);
462 printf("\n%u units listed. Pass --all to see inactive units, too.\n", n_shown);
466 static int list_units(DBusConnection *bus, char **args, unsigned n) {
467 DBusMessage *m = NULL, *reply = NULL;
470 DBusMessageIter iter, sub, sub2;
471 unsigned c = 0, n_units = 0;
472 struct unit_info *unit_infos = NULL;
474 dbus_error_init(&error);
480 if (!(m = dbus_message_new_method_call(
481 "org.freedesktop.systemd1",
482 "/org/freedesktop/systemd1",
483 "org.freedesktop.systemd1.Manager",
485 log_error("Could not allocate message.");
489 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
490 log_error("Failed to issue method call: %s", bus_error_message(&error));
495 if (!dbus_message_iter_init(reply, &iter) ||
496 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
497 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
498 log_error("Failed to parse reply.");
503 dbus_message_iter_recurse(&iter, &sub);
505 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
508 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
509 log_error("Failed to parse reply.");
517 n_units = MAX(2*c, 16);
518 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
521 log_error("Failed to allocate unit array.");
531 dbus_message_iter_recurse(&sub, &sub2);
533 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
534 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
535 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
536 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
537 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
538 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
539 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
540 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
541 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
542 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
543 log_error("Failed to parse reply.");
548 dbus_message_iter_next(&sub);
553 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
554 output_units_list(unit_infos, c);
561 dbus_message_unref(m);
564 dbus_message_unref(reply);
568 dbus_error_free(&error);
573 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
574 static const char * const colors[] = {
575 "Requires", "[color=\"black\"]",
576 "RequiresOverridable", "[color=\"black\"]",
577 "Requisite", "[color=\"darkblue\"]",
578 "RequisiteOverridable", "[color=\"darkblue\"]",
579 "Wants", "[color=\"darkgrey\"]",
580 "Conflicts", "[color=\"red\"]",
581 "ConflictedBy", "[color=\"red\"]",
582 "After", "[color=\"green\"]"
585 const char *c = NULL;
592 for (i = 0; i < ELEMENTSOF(colors); i += 2)
593 if (streq(colors[i], prop)) {
601 if (arg_dot != DOT_ALL)
602 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
605 switch (dbus_message_iter_get_arg_type(iter)) {
607 case DBUS_TYPE_ARRAY:
609 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
612 dbus_message_iter_recurse(iter, &sub);
614 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
617 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
618 dbus_message_iter_get_basic(&sub, &s);
619 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
621 dbus_message_iter_next(&sub);
631 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
632 DBusMessage *m = NULL, *reply = NULL;
633 const char *interface = "org.freedesktop.systemd1.Unit";
636 DBusMessageIter iter, sub, sub2, sub3;
641 dbus_error_init(&error);
643 if (!(m = dbus_message_new_method_call(
644 "org.freedesktop.systemd1",
646 "org.freedesktop.DBus.Properties",
648 log_error("Could not allocate message.");
653 if (!dbus_message_append_args(m,
654 DBUS_TYPE_STRING, &interface,
655 DBUS_TYPE_INVALID)) {
656 log_error("Could not append arguments to message.");
661 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
662 log_error("Failed to issue method call: %s", bus_error_message(&error));
667 if (!dbus_message_iter_init(reply, &iter) ||
668 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
669 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
670 log_error("Failed to parse reply.");
675 dbus_message_iter_recurse(&iter, &sub);
677 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
680 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
681 log_error("Failed to parse reply.");
686 dbus_message_iter_recurse(&sub, &sub2);
688 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
689 log_error("Failed to parse reply.");
694 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
695 log_error("Failed to parse reply.");
700 dbus_message_iter_recurse(&sub2, &sub3);
702 if (dot_one_property(name, prop, &sub3)) {
703 log_error("Failed to parse reply.");
708 dbus_message_iter_next(&sub);
715 dbus_message_unref(m);
718 dbus_message_unref(reply);
720 dbus_error_free(&error);
725 static int dot(DBusConnection *bus, char **args, unsigned n) {
726 DBusMessage *m = NULL, *reply = NULL;
729 DBusMessageIter iter, sub, sub2;
731 dbus_error_init(&error);
735 if (!(m = dbus_message_new_method_call(
736 "org.freedesktop.systemd1",
737 "/org/freedesktop/systemd1",
738 "org.freedesktop.systemd1.Manager",
740 log_error("Could not allocate message.");
744 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
745 log_error("Failed to issue method call: %s", bus_error_message(&error));
750 if (!dbus_message_iter_init(reply, &iter) ||
751 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
752 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
753 log_error("Failed to parse reply.");
758 printf("digraph systemd {\n");
760 dbus_message_iter_recurse(&iter, &sub);
761 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
762 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
764 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
765 log_error("Failed to parse reply.");
770 dbus_message_iter_recurse(&sub, &sub2);
772 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
773 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
774 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
775 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
776 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
777 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
778 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
779 log_error("Failed to parse reply.");
784 if ((r = dot_one(bus, id, unit_path)) < 0)
787 /* printf("\t\"%s\";\n", id); */
788 dbus_message_iter_next(&sub);
793 log_info(" Color legend: black = Requires\n"
794 " dark blue = Requisite\n"
795 " dark grey = Wants\n"
799 if (isatty(fileno(stdout)))
800 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
801 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
807 dbus_message_unref(m);
810 dbus_message_unref(reply);
812 dbus_error_free(&error);
817 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
818 DBusMessage *m = NULL, *reply = NULL;
821 DBusMessageIter iter, sub, sub2;
824 dbus_error_init(&error);
830 if (!(m = dbus_message_new_method_call(
831 "org.freedesktop.systemd1",
832 "/org/freedesktop/systemd1",
833 "org.freedesktop.systemd1.Manager",
835 log_error("Could not allocate message.");
839 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
840 log_error("Failed to issue method call: %s", bus_error_message(&error));
845 if (!dbus_message_iter_init(reply, &iter) ||
846 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
847 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
848 log_error("Failed to parse reply.");
853 dbus_message_iter_recurse(&iter, &sub);
855 if (isatty(STDOUT_FILENO))
856 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
858 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
859 const char *name, *type, *state, *job_path, *unit_path;
863 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
864 log_error("Failed to parse reply.");
869 dbus_message_iter_recurse(&sub, &sub2);
871 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
872 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
873 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
874 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
875 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
876 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
877 log_error("Failed to parse reply.");
882 e = arg_full ? NULL : ellipsize(name, 25, 33);
883 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
888 dbus_message_iter_next(&sub);
891 if (isatty(STDOUT_FILENO))
892 printf("\n%u jobs listed.\n", k);
898 dbus_message_unref(m);
901 dbus_message_unref(reply);
903 dbus_error_free(&error);
908 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
909 DBusMessage *m = NULL, *reply = NULL;
914 dbus_error_init(&error);
919 for (i = 1; i < n; i++) {
921 if (!(m = dbus_message_new_method_call(
922 "org.freedesktop.systemd1",
923 "/org/freedesktop/systemd1",
924 "org.freedesktop.systemd1.Manager",
926 log_error("Could not allocate message.");
931 if (!dbus_message_append_args(m,
932 DBUS_TYPE_STRING, &args[i],
933 DBUS_TYPE_INVALID)) {
934 log_error("Could not append arguments to message.");
939 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
940 log_error("Failed to issue method call: %s", bus_error_message(&error));
945 dbus_message_unref(m);
946 dbus_message_unref(reply);
955 dbus_message_unref(m);
958 dbus_message_unref(reply);
960 dbus_error_free(&error);
965 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
966 DBusMessage *m = NULL, *reply = NULL;
971 dbus_error_init(&error);
977 return daemon_reload(bus, args, n);
979 for (i = 1; i < n; i++) {
983 if (!(m = dbus_message_new_method_call(
984 "org.freedesktop.systemd1",
985 "/org/freedesktop/systemd1",
986 "org.freedesktop.systemd1.Manager",
988 log_error("Could not allocate message.");
993 if ((r = safe_atou(args[i], &id)) < 0) {
994 log_error("Failed to parse job id: %s", strerror(-r));
998 assert_cc(sizeof(uint32_t) == sizeof(id));
999 if (!dbus_message_append_args(m,
1000 DBUS_TYPE_UINT32, &id,
1001 DBUS_TYPE_INVALID)) {
1002 log_error("Could not append arguments to message.");
1007 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1008 log_error("Failed to issue method call: %s", bus_error_message(&error));
1013 if (!dbus_message_get_args(reply, &error,
1014 DBUS_TYPE_OBJECT_PATH, &path,
1015 DBUS_TYPE_INVALID)) {
1016 log_error("Failed to parse reply: %s", bus_error_message(&error));
1021 dbus_message_unref(m);
1022 if (!(m = dbus_message_new_method_call(
1023 "org.freedesktop.systemd1",
1025 "org.freedesktop.systemd1.Job",
1027 log_error("Could not allocate message.");
1032 dbus_message_unref(reply);
1033 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1034 log_error("Failed to issue method call: %s", bus_error_message(&error));
1039 dbus_message_unref(m);
1040 dbus_message_unref(reply);
1048 dbus_message_unref(m);
1051 dbus_message_unref(reply);
1053 dbus_error_free(&error);
1058 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1059 DBusMessage *m = NULL, *reply = NULL;
1060 dbus_bool_t b = FALSE;
1061 DBusMessageIter iter, sub;
1063 *interface = "org.freedesktop.systemd1.Unit",
1064 *property = "NeedDaemonReload",
1067 /* We ignore all errors here, since this is used to show a warning only */
1069 if (!(m = dbus_message_new_method_call(
1070 "org.freedesktop.systemd1",
1071 "/org/freedesktop/systemd1",
1072 "org.freedesktop.systemd1.Manager",
1076 if (!dbus_message_append_args(m,
1077 DBUS_TYPE_STRING, &unit,
1081 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1084 if (!dbus_message_get_args(reply, NULL,
1085 DBUS_TYPE_OBJECT_PATH, &path,
1089 dbus_message_unref(m);
1090 if (!(m = dbus_message_new_method_call(
1091 "org.freedesktop.systemd1",
1093 "org.freedesktop.DBus.Properties",
1097 if (!dbus_message_append_args(m,
1098 DBUS_TYPE_STRING, &interface,
1099 DBUS_TYPE_STRING, &property,
1100 DBUS_TYPE_INVALID)) {
1104 dbus_message_unref(reply);
1105 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1108 if (!dbus_message_iter_init(reply, &iter) ||
1109 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1112 dbus_message_iter_recurse(&iter, &sub);
1114 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1117 dbus_message_iter_get_basic(&sub, &b);
1121 dbus_message_unref(m);
1124 dbus_message_unref(reply);
1129 typedef struct WaitData {
1134 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1142 dbus_error_init(&error);
1144 log_debug("Got D-Bus request: %s.%s() on %s",
1145 dbus_message_get_interface(message),
1146 dbus_message_get_member(message),
1147 dbus_message_get_path(message));
1149 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1150 log_error("Warning! D-Bus connection terminated.");
1151 dbus_connection_close(connection);
1153 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1155 const char *path, *result;
1156 dbus_bool_t success = true;
1158 if (dbus_message_get_args(message, &error,
1159 DBUS_TYPE_UINT32, &id,
1160 DBUS_TYPE_OBJECT_PATH, &path,
1161 DBUS_TYPE_STRING, &result,
1162 DBUS_TYPE_INVALID)) {
1165 if ((p = set_remove(d->set, (char*) path)))
1169 d->result = strdup(result);
1174 dbus_error_free(&error);
1176 if (dbus_message_get_args(message, &error,
1177 DBUS_TYPE_UINT32, &id,
1178 DBUS_TYPE_OBJECT_PATH, &path,
1179 DBUS_TYPE_BOOLEAN, &success,
1180 DBUS_TYPE_INVALID)) {
1183 /* Compatibility with older systemd versions <
1184 * 19 during upgrades. This should be dropped
1187 if ((p = set_remove(d->set, (char*) path)))
1191 d->result = strdup("failed");
1197 log_error("Failed to parse message: %s", bus_error_message(&error));
1201 dbus_error_free(&error);
1202 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1205 static int enable_wait_for_jobs(DBusConnection *bus) {
1213 dbus_error_init(&error);
1214 dbus_bus_add_match(bus,
1216 "sender='org.freedesktop.systemd1',"
1217 "interface='org.freedesktop.systemd1.Manager',"
1218 "member='JobRemoved',"
1219 "path='/org/freedesktop/systemd1'",
1222 if (dbus_error_is_set(&error)) {
1223 log_error("Failed to add match: %s", bus_error_message(&error));
1224 dbus_error_free(&error);
1228 /* This is slightly dirty, since we don't undo the match registrations. */
1232 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1242 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1243 log_error("Failed to add filter.");
1248 while (!set_isempty(s) &&
1249 dbus_connection_read_write_dispatch(bus, -1))
1252 if (!arg_quiet && d.result) {
1253 if (streq(d.result, "timeout"))
1254 log_error("Job timed out.");
1255 else if (streq(d.result, "canceled"))
1256 log_error("Job canceled.");
1257 else if (streq(d.result, "dependency"))
1258 log_error("A dependency job failed. See system logs for details.");
1259 else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
1260 log_error("Job failed. See system logs and 'systemctl status' for details.");
1263 if (streq_ptr(d.result, "timeout"))
1265 else if (streq_ptr(d.result, "canceled"))
1267 else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
1275 /* This is slightly dirty, since we don't undo the filter registration. */
1280 static int start_unit_one(
1281 DBusConnection *bus,
1288 DBusMessage *m = NULL, *reply = NULL;
1297 assert(arg_no_block || s);
1299 if (!(m = dbus_message_new_method_call(
1300 "org.freedesktop.systemd1",
1301 "/org/freedesktop/systemd1",
1302 "org.freedesktop.systemd1.Manager",
1304 log_error("Could not allocate message.");
1309 if (!dbus_message_append_args(m,
1310 DBUS_TYPE_STRING, &name,
1311 DBUS_TYPE_STRING, &mode,
1312 DBUS_TYPE_INVALID)) {
1313 log_error("Could not append arguments to message.");
1318 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1320 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1321 /* There's always a fallback possible for
1322 * legacy actions. */
1327 log_error("Failed to issue method call: %s", bus_error_message(error));
1332 if (!dbus_message_get_args(reply, error,
1333 DBUS_TYPE_OBJECT_PATH, &path,
1334 DBUS_TYPE_INVALID)) {
1335 log_error("Failed to parse reply: %s", bus_error_message(error));
1340 if (need_daemon_reload(bus, name))
1341 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1342 arg_user ? "--user" : "--system");
1344 if (!arg_no_block) {
1347 if (!(p = strdup(path))) {
1348 log_error("Failed to duplicate path.");
1353 if ((r = set_put(s, p)) < 0) {
1355 log_error("Failed to add path to set.");
1364 dbus_message_unref(m);
1367 dbus_message_unref(reply);
1372 static enum action verb_to_action(const char *verb) {
1373 if (streq(verb, "halt"))
1375 else if (streq(verb, "poweroff"))
1376 return ACTION_POWEROFF;
1377 else if (streq(verb, "reboot"))
1378 return ACTION_REBOOT;
1379 else if (streq(verb, "kexec"))
1380 return ACTION_KEXEC;
1381 else if (streq(verb, "rescue"))
1382 return ACTION_RESCUE;
1383 else if (streq(verb, "emergency"))
1384 return ACTION_EMERGENCY;
1385 else if (streq(verb, "default"))
1386 return ACTION_DEFAULT;
1387 else if (streq(verb, "exit"))
1390 return ACTION_INVALID;
1393 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1395 static const char * const table[_ACTION_MAX] = {
1396 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1397 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1398 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1399 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1400 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1401 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1402 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1403 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1404 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1405 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1406 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1407 [ACTION_EXIT] = SPECIAL_EXIT_TARGET
1412 const char *method, *mode, *one_name;
1416 dbus_error_init(&error);
1420 spawn_ask_password_agent();
1422 if (arg_action == ACTION_SYSTEMCTL) {
1424 streq(args[0], "stop") ||
1425 streq(args[0], "condstop") ? "StopUnit" :
1426 streq(args[0], "reload") ? "ReloadUnit" :
1427 streq(args[0], "restart") ? "RestartUnit" :
1429 streq(args[0], "try-restart") ||
1430 streq(args[0], "condrestart") ? "TryRestartUnit" :
1432 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1434 streq(args[0], "reload-or-try-restart") ||
1435 streq(args[0], "condreload") ||
1437 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1441 (streq(args[0], "isolate") ||
1442 streq(args[0], "rescue") ||
1443 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1445 one_name = table[verb_to_action(args[0])];
1448 assert(arg_action < ELEMENTSOF(table));
1449 assert(table[arg_action]);
1451 method = "StartUnit";
1453 mode = (arg_action == ACTION_EMERGENCY ||
1454 arg_action == ACTION_RESCUE ||
1455 arg_action == ACTION_RUNLEVEL2 ||
1456 arg_action == ACTION_RUNLEVEL3 ||
1457 arg_action == ACTION_RUNLEVEL4 ||
1458 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1460 one_name = table[arg_action];
1463 if (!arg_no_block) {
1464 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1465 log_error("Could not watch jobs: %s", strerror(-ret));
1469 if (!(s = set_new(string_hash_func, string_compare_func))) {
1470 log_error("Failed to allocate set.");
1477 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1480 for (i = 1; i < n; i++)
1481 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1482 ret = translate_bus_error_to_exit_status(r, &error);
1483 dbus_error_free(&error);
1488 if ((r = wait_for_jobs(bus, s)) < 0) {
1497 dbus_error_free(&error);
1502 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1509 (streq(args[0], "halt") ||
1510 streq(args[0], "poweroff") ||
1511 streq(args[0], "reboot") ||
1512 streq(args[0], "kexec") ||
1513 streq(args[0], "exit")))
1514 return daemon_reload(bus, args, n);
1516 r = start_unit(bus, args, n);
1519 warn_wall(verb_to_action(args[0]));
1524 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1525 DBusMessage *m = NULL, *reply = NULL;
1527 *interface = "org.freedesktop.systemd1.Unit",
1528 *property = "ActiveState";
1529 int r = 3; /* According to LSB: "program is not running" */
1536 dbus_error_init(&error);
1538 for (i = 1; i < n; i++) {
1539 const char *path = NULL;
1541 DBusMessageIter iter, sub;
1543 if (!(m = dbus_message_new_method_call(
1544 "org.freedesktop.systemd1",
1545 "/org/freedesktop/systemd1",
1546 "org.freedesktop.systemd1.Manager",
1548 log_error("Could not allocate message.");
1553 if (!dbus_message_append_args(m,
1554 DBUS_TYPE_STRING, &args[i],
1555 DBUS_TYPE_INVALID)) {
1556 log_error("Could not append arguments to message.");
1561 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1563 /* Hmm, cannot figure out anything about this unit... */
1567 dbus_error_free(&error);
1568 dbus_message_unref(m);
1573 if (!dbus_message_get_args(reply, &error,
1574 DBUS_TYPE_OBJECT_PATH, &path,
1575 DBUS_TYPE_INVALID)) {
1576 log_error("Failed to parse reply: %s", bus_error_message(&error));
1581 dbus_message_unref(m);
1582 if (!(m = dbus_message_new_method_call(
1583 "org.freedesktop.systemd1",
1585 "org.freedesktop.DBus.Properties",
1587 log_error("Could not allocate message.");
1592 if (!dbus_message_append_args(m,
1593 DBUS_TYPE_STRING, &interface,
1594 DBUS_TYPE_STRING, &property,
1595 DBUS_TYPE_INVALID)) {
1596 log_error("Could not append arguments to message.");
1601 dbus_message_unref(reply);
1602 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1603 log_error("Failed to issue method call: %s", bus_error_message(&error));
1608 if (!dbus_message_iter_init(reply, &iter) ||
1609 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1610 log_error("Failed to parse reply.");
1615 dbus_message_iter_recurse(&iter, &sub);
1617 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1618 log_error("Failed to parse reply.");
1623 dbus_message_iter_get_basic(&sub, &state);
1628 if (streq(state, "active") || streq(state, "reloading"))
1631 dbus_message_unref(m);
1632 dbus_message_unref(reply);
1638 dbus_message_unref(m);
1641 dbus_message_unref(reply);
1643 dbus_error_free(&error);
1648 static int kill_unit(DBusConnection *bus, char **args, unsigned n) {
1649 DBusMessage *m = NULL, *reply = NULL;
1657 dbus_error_init(&error);
1660 arg_kill_who = "all";
1663 arg_kill_mode = streq(arg_kill_who, "all") ? "control-group" : "process";
1665 for (i = 1; i < n; i++) {
1667 if (!(m = dbus_message_new_method_call(
1668 "org.freedesktop.systemd1",
1669 "/org/freedesktop/systemd1",
1670 "org.freedesktop.systemd1.Manager",
1672 log_error("Could not allocate message.");
1677 if (!dbus_message_append_args(m,
1678 DBUS_TYPE_STRING, &args[i],
1679 DBUS_TYPE_STRING, &arg_kill_who,
1680 DBUS_TYPE_STRING, &arg_kill_mode,
1681 DBUS_TYPE_INT32, &arg_signal,
1682 DBUS_TYPE_INVALID)) {
1683 log_error("Could not append arguments to message.");
1688 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1689 log_error("Failed to issue method call: %s", bus_error_message(&error));
1690 dbus_error_free(&error);
1694 dbus_message_unref(m);
1697 dbus_message_unref(reply);
1703 dbus_message_unref(m);
1706 dbus_message_unref(reply);
1708 dbus_error_free(&error);
1713 typedef struct ExecStatusInfo {
1721 usec_t start_timestamp;
1722 usec_t exit_timestamp;
1727 LIST_FIELDS(struct ExecStatusInfo, exec);
1730 static void exec_status_info_free(ExecStatusInfo *i) {
1739 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1740 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
1741 DBusMessageIter sub2, sub3;
1745 int32_t code, status;
1751 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1754 dbus_message_iter_recurse(sub, &sub2);
1756 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1759 if (!(i->path = strdup(path)))
1762 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1763 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1767 dbus_message_iter_recurse(&sub2, &sub3);
1768 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1769 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1770 dbus_message_iter_next(&sub3);
1775 if (!(i->argv = new0(char*, n+1)))
1779 dbus_message_iter_recurse(&sub2, &sub3);
1780 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1783 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1784 dbus_message_iter_get_basic(&sub3, &s);
1785 dbus_message_iter_next(&sub3);
1787 if (!(i->argv[n++] = strdup(s)))
1791 if (!dbus_message_iter_next(&sub2) ||
1792 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1793 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1794 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
1795 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1796 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
1797 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1798 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1799 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1803 i->start_timestamp = (usec_t) start_timestamp;
1804 i->exit_timestamp = (usec_t) exit_timestamp;
1805 i->pid = (pid_t) pid;
1812 typedef struct UnitStatusInfo {
1814 const char *load_state;
1815 const char *active_state;
1816 const char *sub_state;
1818 const char *description;
1819 const char *following;
1822 const char *default_control_group;
1824 usec_t inactive_exit_timestamp;
1825 usec_t active_enter_timestamp;
1826 usec_t active_exit_timestamp;
1827 usec_t inactive_enter_timestamp;
1829 bool need_daemon_reload;
1834 const char *status_text;
1836 #ifdef HAVE_SYSV_COMPAT
1840 usec_t start_timestamp;
1841 usec_t exit_timestamp;
1843 int exit_code, exit_status;
1845 usec_t condition_timestamp;
1846 bool condition_result;
1849 unsigned n_accepted;
1850 unsigned n_connections;
1854 const char *sysfs_path;
1856 /* Mount, Automount */
1862 LIST_HEAD(ExecStatusInfo, exec);
1865 static void print_status_info(UnitStatusInfo *i) {
1867 const char *on, *off, *ss;
1869 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1870 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1874 /* This shows pretty information about a unit. See
1875 * print_property() for a low-level property printer */
1877 printf("%s", strna(i->id));
1879 if (i->description && !streq_ptr(i->id, i->description))
1880 printf(" - %s", i->description);
1885 printf("\t Follow: unit currently follows state of %s\n", i->following);
1887 if (streq_ptr(i->load_state, "failed") ||
1888 streq_ptr(i->load_state, "banned")) {
1889 on = ansi_highlight(true);
1890 off = ansi_highlight(false);
1895 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1897 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1899 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1901 if (streq_ptr(i->active_state, "failed")) {
1902 on = ansi_highlight(true);
1903 off = ansi_highlight(false);
1904 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1905 on = ansi_highlight_green(true);
1906 off = ansi_highlight_green(false);
1911 printf("\t Active: %s%s (%s)%s",
1913 strna(i->active_state),
1917 printf("\t Active: %s%s%s",
1919 strna(i->active_state),
1922 timestamp = (streq_ptr(i->active_state, "active") ||
1923 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1924 (streq_ptr(i->active_state, "inactive") ||
1925 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1926 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1927 i->active_exit_timestamp;
1929 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1930 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1933 printf(" since %s; %s\n", s2, s1);
1935 printf(" since %s\n", s2);
1939 if (!i->condition_result && i->condition_timestamp > 0) {
1940 s1 = format_timestamp_pretty(since1, sizeof(since1), i->condition_timestamp);
1941 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
1944 printf("\t start condition failed at %s; %s\n", s2, s1);
1946 printf("\t start condition failed at %s\n", s2);
1950 printf("\t Device: %s\n", i->sysfs_path);
1952 printf("\t Where: %s\n", i->where);
1954 printf("\t What: %s\n", i->what);
1957 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1959 LIST_FOREACH(exec, p, i->exec) {
1963 /* Only show exited processes here */
1967 t = strv_join(p->argv, " ");
1968 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
1971 #ifdef HAVE_SYSV_COMPAT
1973 good = is_clean_exit_lsb(p->code, p->status);
1976 good = is_clean_exit(p->code, p->status);
1979 on = ansi_highlight(true);
1980 off = ansi_highlight(false);
1984 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
1986 if (p->code == CLD_EXITED) {
1989 printf("status=%i", p->status);
1991 #ifdef HAVE_SYSV_COMPAT
1992 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1994 if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1999 printf("signal=%s", signal_to_string(p->status));
2001 printf(")%s\n", off);
2005 if (i->main_pid == p->pid &&
2006 i->start_timestamp == p->start_timestamp &&
2007 i->exit_timestamp == p->start_timestamp)
2008 /* Let's not show this twice */
2011 if (p->pid == i->control_pid)
2015 if (i->main_pid > 0 || i->control_pid > 0) {
2018 if (i->main_pid > 0) {
2019 printf("Main PID: %u", (unsigned) i->main_pid);
2023 get_process_name(i->main_pid, &t);
2028 } else if (i->exit_code > 0) {
2029 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2031 if (i->exit_code == CLD_EXITED) {
2034 printf("status=%i", i->exit_status);
2036 #ifdef HAVE_SYSV_COMPAT
2037 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
2039 if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
2044 printf("signal=%s", signal_to_string(i->exit_status));
2049 if (i->main_pid > 0 && i->control_pid > 0)
2052 if (i->control_pid > 0) {
2055 printf(" Control: %u", (unsigned) i->control_pid);
2057 get_process_name(i->control_pid, &t);
2068 printf("\t Status: \"%s\"\n", i->status_text);
2070 if (i->default_control_group) {
2073 printf("\t CGroup: %s\n", i->default_control_group);
2075 if (arg_transport != TRANSPORT_SSH) {
2076 if ((c = columns()) > 18)
2081 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
2085 if (i->need_daemon_reload)
2086 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2087 ansi_highlight(true),
2088 ansi_highlight(false),
2089 arg_user ? "--user" : "--system");
2092 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2094 switch (dbus_message_iter_get_arg_type(iter)) {
2096 case DBUS_TYPE_STRING: {
2099 dbus_message_iter_get_basic(iter, &s);
2102 if (streq(name, "Id"))
2104 else if (streq(name, "LoadState"))
2106 else if (streq(name, "ActiveState"))
2107 i->active_state = s;
2108 else if (streq(name, "SubState"))
2110 else if (streq(name, "Description"))
2112 else if (streq(name, "FragmentPath"))
2114 #ifdef HAVE_SYSV_COMPAT
2115 else if (streq(name, "SysVPath")) {
2120 else if (streq(name, "DefaultControlGroup"))
2121 i->default_control_group = s;
2122 else if (streq(name, "StatusText"))
2124 else if (streq(name, "SysFSPath"))
2126 else if (streq(name, "Where"))
2128 else if (streq(name, "What"))
2130 else if (streq(name, "Following"))
2137 case DBUS_TYPE_BOOLEAN: {
2140 dbus_message_iter_get_basic(iter, &b);
2142 if (streq(name, "Accept"))
2144 else if (streq(name, "NeedDaemonReload"))
2145 i->need_daemon_reload = b;
2146 else if (streq(name, "ConditionResult"))
2147 i->condition_result = b;
2152 case DBUS_TYPE_UINT32: {
2155 dbus_message_iter_get_basic(iter, &u);
2157 if (streq(name, "MainPID")) {
2159 i->main_pid = (pid_t) u;
2162 } else if (streq(name, "ControlPID"))
2163 i->control_pid = (pid_t) u;
2164 else if (streq(name, "ExecMainPID")) {
2166 i->main_pid = (pid_t) u;
2167 } else if (streq(name, "NAccepted"))
2169 else if (streq(name, "NConnections"))
2170 i->n_connections = u;
2175 case DBUS_TYPE_INT32: {
2178 dbus_message_iter_get_basic(iter, &j);
2180 if (streq(name, "ExecMainCode"))
2181 i->exit_code = (int) j;
2182 else if (streq(name, "ExecMainStatus"))
2183 i->exit_status = (int) j;
2188 case DBUS_TYPE_UINT64: {
2191 dbus_message_iter_get_basic(iter, &u);
2193 if (streq(name, "ExecMainStartTimestamp"))
2194 i->start_timestamp = (usec_t) u;
2195 else if (streq(name, "ExecMainExitTimestamp"))
2196 i->exit_timestamp = (usec_t) u;
2197 else if (streq(name, "ActiveEnterTimestamp"))
2198 i->active_enter_timestamp = (usec_t) u;
2199 else if (streq(name, "InactiveEnterTimestamp"))
2200 i->inactive_enter_timestamp = (usec_t) u;
2201 else if (streq(name, "InactiveExitTimestamp"))
2202 i->inactive_exit_timestamp = (usec_t) u;
2203 else if (streq(name, "ActiveExitTimestamp"))
2204 i->active_exit_timestamp = (usec_t) u;
2205 else if (streq(name, "ConditionTimestamp"))
2206 i->condition_timestamp = (usec_t) u;
2211 case DBUS_TYPE_ARRAY: {
2213 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2214 startswith(name, "Exec")) {
2215 DBusMessageIter sub;
2217 dbus_message_iter_recurse(iter, &sub);
2218 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2219 ExecStatusInfo *info;
2222 if (!(info = new0(ExecStatusInfo, 1)))
2225 if (!(info->name = strdup(name))) {
2230 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2235 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2237 dbus_message_iter_next(&sub);
2248 static int print_property(const char *name, DBusMessageIter *iter) {
2252 /* This is a low-level property printer, see
2253 * print_status_info() for the nicer output */
2255 if (arg_property && !strv_find(arg_property, name))
2258 switch (dbus_message_iter_get_arg_type(iter)) {
2260 case DBUS_TYPE_STRING: {
2262 dbus_message_iter_get_basic(iter, &s);
2264 if (arg_all || s[0])
2265 printf("%s=%s\n", name, s);
2270 case DBUS_TYPE_BOOLEAN: {
2272 dbus_message_iter_get_basic(iter, &b);
2273 printf("%s=%s\n", name, yes_no(b));
2278 case DBUS_TYPE_UINT64: {
2280 dbus_message_iter_get_basic(iter, &u);
2282 /* Yes, heuristics! But we can change this check
2283 * should it turn out to not be sufficient */
2285 if (endswith(name, "Timestamp")) {
2286 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
2288 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
2289 printf("%s=%s\n", name, strempty(t));
2290 } else if (strstr(name, "USec")) {
2291 char timespan[FORMAT_TIMESPAN_MAX];
2293 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
2295 printf("%s=%llu\n", name, (unsigned long long) u);
2300 case DBUS_TYPE_UINT32: {
2302 dbus_message_iter_get_basic(iter, &u);
2304 if (strstr(name, "UMask") || strstr(name, "Mode"))
2305 printf("%s=%04o\n", name, u);
2307 printf("%s=%u\n", name, (unsigned) u);
2312 case DBUS_TYPE_INT32: {
2314 dbus_message_iter_get_basic(iter, &i);
2316 printf("%s=%i\n", name, (int) i);
2320 case DBUS_TYPE_DOUBLE: {
2322 dbus_message_iter_get_basic(iter, &d);
2324 printf("%s=%g\n", name, d);
2328 case DBUS_TYPE_STRUCT: {
2329 DBusMessageIter sub;
2330 dbus_message_iter_recurse(iter, &sub);
2332 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2335 dbus_message_iter_get_basic(&sub, &u);
2338 printf("%s=%u\n", name, (unsigned) u);
2340 printf("%s=\n", name);
2343 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2346 dbus_message_iter_get_basic(&sub, &s);
2348 if (arg_all || s[0])
2349 printf("%s=%s\n", name, s);
2357 case DBUS_TYPE_ARRAY:
2359 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2360 DBusMessageIter sub;
2363 dbus_message_iter_recurse(iter, &sub);
2365 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2366 printf("%s=", name);
2368 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2371 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2372 dbus_message_iter_get_basic(&sub, &s);
2373 printf("%s%s", space ? " " : "", s);
2376 dbus_message_iter_next(&sub);
2384 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2385 DBusMessageIter sub;
2387 dbus_message_iter_recurse(iter, &sub);
2389 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2390 printf("%s=", name);
2392 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2395 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2396 dbus_message_iter_get_basic(&sub, &u);
2399 dbus_message_iter_next(&sub);
2407 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
2408 DBusMessageIter sub, sub2;
2410 dbus_message_iter_recurse(iter, &sub);
2411 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2415 dbus_message_iter_recurse(&sub, &sub2);
2417 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
2418 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
2419 printf("EnvironmentFile=%s (ignore=%s)\n", path, yes_no(ignore));
2421 dbus_message_iter_next(&sub);
2426 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2427 DBusMessageIter sub, sub2;
2429 dbus_message_iter_recurse(iter, &sub);
2430 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2431 const char *type, *path;
2433 dbus_message_iter_recurse(&sub, &sub2);
2435 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2436 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2437 printf("%s=%s\n", type, path);
2439 dbus_message_iter_next(&sub);
2444 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2445 DBusMessageIter sub, sub2;
2447 dbus_message_iter_recurse(iter, &sub);
2448 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2450 uint64_t value, next_elapse;
2452 dbus_message_iter_recurse(&sub, &sub2);
2454 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2455 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2456 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2457 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2459 printf("%s={ value=%s ; next_elapse=%s }\n",
2461 format_timespan(timespan1, sizeof(timespan1), value),
2462 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2465 dbus_message_iter_next(&sub);
2470 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2471 DBusMessageIter sub;
2473 dbus_message_iter_recurse(iter, &sub);
2474 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2475 ExecStatusInfo info;
2478 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2479 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2482 t = strv_join(info.argv, " ");
2484 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2488 yes_no(info.ignore),
2489 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2490 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2491 (unsigned) info. pid,
2492 sigchld_code_to_string(info.code),
2494 info.code == CLD_EXITED ? "" : "/",
2495 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2501 strv_free(info.argv);
2503 dbus_message_iter_next(&sub);
2513 printf("%s=[unprintable]\n", name);
2518 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2519 DBusMessage *m = NULL, *reply = NULL;
2520 const char *interface = "";
2523 DBusMessageIter iter, sub, sub2, sub3;
2524 UnitStatusInfo info;
2532 dbus_error_init(&error);
2534 if (!(m = dbus_message_new_method_call(
2535 "org.freedesktop.systemd1",
2537 "org.freedesktop.DBus.Properties",
2539 log_error("Could not allocate message.");
2544 if (!dbus_message_append_args(m,
2545 DBUS_TYPE_STRING, &interface,
2546 DBUS_TYPE_INVALID)) {
2547 log_error("Could not append arguments to message.");
2552 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2553 log_error("Failed to issue method call: %s", bus_error_message(&error));
2558 if (!dbus_message_iter_init(reply, &iter) ||
2559 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2560 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2561 log_error("Failed to parse reply.");
2566 dbus_message_iter_recurse(&iter, &sub);
2573 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2576 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2577 log_error("Failed to parse reply.");
2582 dbus_message_iter_recurse(&sub, &sub2);
2584 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2585 log_error("Failed to parse reply.");
2590 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2591 log_error("Failed to parse reply.");
2596 dbus_message_iter_recurse(&sub2, &sub3);
2598 if (show_properties)
2599 r = print_property(name, &sub3);
2601 r = status_property(name, &sub3, &info);
2604 log_error("Failed to parse reply.");
2609 dbus_message_iter_next(&sub);
2614 if (!show_properties)
2615 print_status_info(&info);
2617 if (!streq_ptr(info.active_state, "active") &&
2618 !streq_ptr(info.active_state, "reloading") &&
2619 streq(verb, "status"))
2620 /* According to LSB: "program not running" */
2623 while ((p = info.exec)) {
2624 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2625 exec_status_info_free(p);
2630 dbus_message_unref(m);
2633 dbus_message_unref(reply);
2635 dbus_error_free(&error);
2640 static int show(DBusConnection *bus, char **args, unsigned n) {
2641 DBusMessage *m = NULL, *reply = NULL;
2645 bool show_properties, new_line = false;
2650 dbus_error_init(&error);
2652 show_properties = !streq(args[0], "status");
2654 if (show_properties)
2657 if (show_properties && n <= 1) {
2658 /* If not argument is specified inspect the manager
2661 ret = show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2665 for (i = 1; i < n; i++) {
2666 const char *path = NULL;
2669 if (safe_atou32(args[i], &id) < 0) {
2671 /* Interpret as unit name */
2673 if (!(m = dbus_message_new_method_call(
2674 "org.freedesktop.systemd1",
2675 "/org/freedesktop/systemd1",
2676 "org.freedesktop.systemd1.Manager",
2678 log_error("Could not allocate message.");
2683 if (!dbus_message_append_args(m,
2684 DBUS_TYPE_STRING, &args[i],
2685 DBUS_TYPE_INVALID)) {
2686 log_error("Could not append arguments to message.");
2691 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2693 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2694 log_error("Failed to issue method call: %s", bus_error_message(&error));
2699 dbus_error_free(&error);
2701 dbus_message_unref(m);
2702 if (!(m = dbus_message_new_method_call(
2703 "org.freedesktop.systemd1",
2704 "/org/freedesktop/systemd1",
2705 "org.freedesktop.systemd1.Manager",
2707 log_error("Could not allocate message.");
2712 if (!dbus_message_append_args(m,
2713 DBUS_TYPE_STRING, &args[i],
2714 DBUS_TYPE_INVALID)) {
2715 log_error("Could not append arguments to message.");
2720 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2721 log_error("Failed to issue method call: %s", bus_error_message(&error));
2723 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2724 ret = 4; /* According to LSB: "program or service status is unknown" */
2731 } else if (show_properties) {
2733 /* Interpret as job id */
2735 if (!(m = dbus_message_new_method_call(
2736 "org.freedesktop.systemd1",
2737 "/org/freedesktop/systemd1",
2738 "org.freedesktop.systemd1.Manager",
2740 log_error("Could not allocate message.");
2745 if (!dbus_message_append_args(m,
2746 DBUS_TYPE_UINT32, &id,
2747 DBUS_TYPE_INVALID)) {
2748 log_error("Could not append arguments to message.");
2753 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2754 log_error("Failed to issue method call: %s", bus_error_message(&error));
2760 /* Interpret as PID */
2762 if (!(m = dbus_message_new_method_call(
2763 "org.freedesktop.systemd1",
2764 "/org/freedesktop/systemd1",
2765 "org.freedesktop.systemd1.Manager",
2767 log_error("Could not allocate message.");
2772 if (!dbus_message_append_args(m,
2773 DBUS_TYPE_UINT32, &id,
2774 DBUS_TYPE_INVALID)) {
2775 log_error("Could not append arguments to message.");
2780 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2781 log_error("Failed to issue method call: %s", bus_error_message(&error));
2787 if (!dbus_message_get_args(reply, &error,
2788 DBUS_TYPE_OBJECT_PATH, &path,
2789 DBUS_TYPE_INVALID)) {
2790 log_error("Failed to parse reply: %s", bus_error_message(&error));
2795 if ((r = show_one(args[0], bus, path, show_properties, &new_line)) != 0)
2798 dbus_message_unref(m);
2799 dbus_message_unref(reply);
2805 dbus_message_unref(m);
2808 dbus_message_unref(reply);
2810 dbus_error_free(&error);
2815 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2817 DBusMessage *m = NULL, *reply = NULL;
2822 dbus_error_init(&error);
2824 log_debug("Got D-Bus request: %s.%s() on %s",
2825 dbus_message_get_interface(message),
2826 dbus_message_get_member(message),
2827 dbus_message_get_path(message));
2829 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2830 log_error("Warning! D-Bus connection terminated.");
2831 dbus_connection_close(connection);
2833 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2834 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2835 const char *id, *path;
2837 if (!dbus_message_get_args(message, &error,
2838 DBUS_TYPE_STRING, &id,
2839 DBUS_TYPE_OBJECT_PATH, &path,
2841 log_error("Failed to parse message: %s", bus_error_message(&error));
2842 else if (streq(dbus_message_get_member(message), "UnitNew"))
2843 printf("Unit %s added.\n", id);
2845 printf("Unit %s removed.\n", id);
2847 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew")) {
2851 if (!dbus_message_get_args(message, &error,
2852 DBUS_TYPE_UINT32, &id,
2853 DBUS_TYPE_OBJECT_PATH, &path,
2855 log_error("Failed to parse message: %s", bus_error_message(&error));
2857 printf("Job %u added.\n", id);
2860 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2862 const char *path, *result;
2864 if (!dbus_message_get_args(message, &error,
2865 DBUS_TYPE_UINT32, &id,
2866 DBUS_TYPE_OBJECT_PATH, &path,
2867 DBUS_TYPE_STRING, &result,
2869 log_error("Failed to parse message: %s", bus_error_message(&error));
2871 printf("Job %u removed (result=%s).\n", id, result);
2874 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2876 const char *path, *interface, *property = "Id";
2877 DBusMessageIter iter, sub;
2879 path = dbus_message_get_path(message);
2881 if (!dbus_message_get_args(message, &error,
2882 DBUS_TYPE_STRING, &interface,
2883 DBUS_TYPE_INVALID)) {
2884 log_error("Failed to parse message: %s", bus_error_message(&error));
2888 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2889 !streq(interface, "org.freedesktop.systemd1.Unit"))
2892 if (!(m = dbus_message_new_method_call(
2893 "org.freedesktop.systemd1",
2895 "org.freedesktop.DBus.Properties",
2897 log_error("Could not allocate message.");
2901 if (!dbus_message_append_args(m,
2902 DBUS_TYPE_STRING, &interface,
2903 DBUS_TYPE_STRING, &property,
2904 DBUS_TYPE_INVALID)) {
2905 log_error("Could not append arguments to message.");
2909 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2910 log_error("Failed to issue method call: %s", bus_error_message(&error));
2914 if (!dbus_message_iter_init(reply, &iter) ||
2915 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2916 log_error("Failed to parse reply.");
2920 dbus_message_iter_recurse(&iter, &sub);
2922 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2925 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2926 log_error("Failed to parse reply.");
2930 dbus_message_iter_get_basic(&sub, &id);
2931 printf("Unit %s changed.\n", id);
2935 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2936 log_error("Failed to parse reply.");
2940 dbus_message_iter_get_basic(&sub, &id);
2941 printf("Job %u changed.\n", id);
2947 dbus_message_unref(m);
2950 dbus_message_unref(reply);
2952 dbus_error_free(&error);
2953 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2957 dbus_message_unref(m);
2960 dbus_message_unref(reply);
2962 dbus_error_free(&error);
2963 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2966 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2967 DBusMessage *m = NULL, *reply = NULL;
2971 dbus_error_init(&error);
2974 dbus_bus_add_match(bus,
2976 "sender='org.freedesktop.systemd1',"
2977 "interface='org.freedesktop.systemd1.Manager',"
2978 "path='/org/freedesktop/systemd1'",
2981 if (dbus_error_is_set(&error)) {
2982 log_error("Failed to add match: %s", bus_error_message(&error));
2987 dbus_bus_add_match(bus,
2989 "sender='org.freedesktop.systemd1',"
2990 "interface='org.freedesktop.DBus.Properties',"
2991 "member='PropertiesChanged'",
2994 if (dbus_error_is_set(&error)) {
2995 log_error("Failed to add match: %s", bus_error_message(&error));
3001 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
3002 log_error("Failed to add filter.");
3007 if (!(m = dbus_message_new_method_call(
3008 "org.freedesktop.systemd1",
3009 "/org/freedesktop/systemd1",
3010 "org.freedesktop.systemd1.Manager",
3012 log_error("Could not allocate message.");
3017 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3018 log_error("Failed to issue method call: %s", bus_error_message(&error));
3023 while (dbus_connection_read_write_dispatch(bus, -1))
3030 /* This is slightly dirty, since we don't undo the filter or the matches. */
3033 dbus_message_unref(m);
3036 dbus_message_unref(reply);
3038 dbus_error_free(&error);
3043 static int dump(DBusConnection *bus, char **args, unsigned n) {
3044 DBusMessage *m = NULL, *reply = NULL;
3049 dbus_error_init(&error);
3053 if (!(m = dbus_message_new_method_call(
3054 "org.freedesktop.systemd1",
3055 "/org/freedesktop/systemd1",
3056 "org.freedesktop.systemd1.Manager",
3058 log_error("Could not allocate message.");
3062 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3063 log_error("Failed to issue method call: %s", bus_error_message(&error));
3068 if (!dbus_message_get_args(reply, &error,
3069 DBUS_TYPE_STRING, &text,
3070 DBUS_TYPE_INVALID)) {
3071 log_error("Failed to parse reply: %s", bus_error_message(&error));
3076 fputs(text, stdout);
3082 dbus_message_unref(m);
3085 dbus_message_unref(reply);
3087 dbus_error_free(&error);
3092 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
3093 DBusMessage *m = NULL, *reply = NULL;
3096 const char *name = "", *path, *id;
3097 dbus_bool_t cleanup = FALSE;
3098 DBusMessageIter iter, sub;
3100 *interface = "org.freedesktop.systemd1.Unit",
3103 dbus_error_init(&error);
3105 if (!(m = dbus_message_new_method_call(
3106 "org.freedesktop.systemd1",
3107 "/org/freedesktop/systemd1",
3108 "org.freedesktop.systemd1.Manager",
3109 "CreateSnapshot"))) {
3110 log_error("Could not allocate message.");
3117 if (!dbus_message_append_args(m,
3118 DBUS_TYPE_STRING, &name,
3119 DBUS_TYPE_BOOLEAN, &cleanup,
3120 DBUS_TYPE_INVALID)) {
3121 log_error("Could not append arguments to message.");
3126 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3127 log_error("Failed to issue method call: %s", bus_error_message(&error));
3132 if (!dbus_message_get_args(reply, &error,
3133 DBUS_TYPE_OBJECT_PATH, &path,
3134 DBUS_TYPE_INVALID)) {
3135 log_error("Failed to parse reply: %s", bus_error_message(&error));
3140 dbus_message_unref(m);
3141 if (!(m = dbus_message_new_method_call(
3142 "org.freedesktop.systemd1",
3144 "org.freedesktop.DBus.Properties",
3146 log_error("Could not allocate message.");
3150 if (!dbus_message_append_args(m,
3151 DBUS_TYPE_STRING, &interface,
3152 DBUS_TYPE_STRING, &property,
3153 DBUS_TYPE_INVALID)) {
3154 log_error("Could not append arguments to message.");
3159 dbus_message_unref(reply);
3160 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3161 log_error("Failed to issue method call: %s", bus_error_message(&error));
3166 if (!dbus_message_iter_init(reply, &iter) ||
3167 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3168 log_error("Failed to parse reply.");
3173 dbus_message_iter_recurse(&iter, &sub);
3175 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3176 log_error("Failed to parse reply.");
3181 dbus_message_iter_get_basic(&sub, &id);
3189 dbus_message_unref(m);
3192 dbus_message_unref(reply);
3194 dbus_error_free(&error);
3199 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
3200 DBusMessage *m = NULL, *reply = NULL;
3208 dbus_error_init(&error);
3210 for (i = 1; i < n; i++) {
3211 const char *path = NULL;
3213 if (!(m = dbus_message_new_method_call(
3214 "org.freedesktop.systemd1",
3215 "/org/freedesktop/systemd1",
3216 "org.freedesktop.systemd1.Manager",
3218 log_error("Could not allocate message.");
3223 if (!dbus_message_append_args(m,
3224 DBUS_TYPE_STRING, &args[i],
3225 DBUS_TYPE_INVALID)) {
3226 log_error("Could not append arguments to message.");
3231 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3232 log_error("Failed to issue method call: %s", bus_error_message(&error));
3237 if (!dbus_message_get_args(reply, &error,
3238 DBUS_TYPE_OBJECT_PATH, &path,
3239 DBUS_TYPE_INVALID)) {
3240 log_error("Failed to parse reply: %s", bus_error_message(&error));
3245 dbus_message_unref(m);
3246 if (!(m = dbus_message_new_method_call(
3247 "org.freedesktop.systemd1",
3249 "org.freedesktop.systemd1.Snapshot",
3251 log_error("Could not allocate message.");
3256 dbus_message_unref(reply);
3257 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3258 log_error("Failed to issue method call: %s", bus_error_message(&error));
3263 dbus_message_unref(m);
3264 dbus_message_unref(reply);
3272 dbus_message_unref(m);
3275 dbus_message_unref(reply);
3277 dbus_error_free(&error);
3282 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
3283 DBusMessage *m = NULL, *reply = NULL;
3288 dbus_error_init(&error);
3290 if (arg_action == ACTION_RELOAD)
3292 else if (arg_action == ACTION_REEXEC)
3293 method = "Reexecute";
3295 assert(arg_action == ACTION_SYSTEMCTL);
3298 streq(args[0], "clear-jobs") ||
3299 streq(args[0], "cancel") ? "ClearJobs" :
3300 streq(args[0], "daemon-reexec") ? "Reexecute" :
3301 streq(args[0], "reset-failed") ? "ResetFailed" :
3302 streq(args[0], "halt") ? "Halt" :
3303 streq(args[0], "poweroff") ? "PowerOff" :
3304 streq(args[0], "reboot") ? "Reboot" :
3305 streq(args[0], "kexec") ? "KExec" :
3306 streq(args[0], "exit") ? "Exit" :
3307 /* "daemon-reload" */ "Reload";
3310 if (!(m = dbus_message_new_method_call(
3311 "org.freedesktop.systemd1",
3312 "/org/freedesktop/systemd1",
3313 "org.freedesktop.systemd1.Manager",
3315 log_error("Could not allocate message.");
3319 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3321 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3322 /* There's always a fallback possible for
3323 * legacy actions. */
3328 if (streq(method, "Reexecute") && dbus_error_has_name(&error, DBUS_ERROR_NO_REPLY)) {
3329 /* On reexecution, we expect a disconnect, not
3335 log_error("Failed to issue method call: %s", bus_error_message(&error));
3344 dbus_message_unref(m);
3347 dbus_message_unref(reply);
3349 dbus_error_free(&error);
3354 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3355 DBusMessage *m = NULL, *reply = NULL;
3361 dbus_error_init(&error);
3364 return daemon_reload(bus, args, n);
3366 for (i = 1; i < n; i++) {
3368 if (!(m = dbus_message_new_method_call(
3369 "org.freedesktop.systemd1",
3370 "/org/freedesktop/systemd1",
3371 "org.freedesktop.systemd1.Manager",
3372 "ResetFailedUnit"))) {
3373 log_error("Could not allocate message.");
3378 if (!dbus_message_append_args(m,
3379 DBUS_TYPE_STRING, args + i,
3380 DBUS_TYPE_INVALID)) {
3381 log_error("Could not append arguments to message.");
3386 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3387 log_error("Failed to issue method call: %s", bus_error_message(&error));
3392 dbus_message_unref(m);
3393 dbus_message_unref(reply);
3401 dbus_message_unref(m);
3404 dbus_message_unref(reply);
3406 dbus_error_free(&error);
3411 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3412 DBusMessage *m = NULL, *reply = NULL;
3414 DBusMessageIter iter, sub, sub2;
3417 *interface = "org.freedesktop.systemd1.Manager",
3418 *property = "Environment";
3420 dbus_error_init(&error);
3424 if (!(m = dbus_message_new_method_call(
3425 "org.freedesktop.systemd1",
3426 "/org/freedesktop/systemd1",
3427 "org.freedesktop.DBus.Properties",
3429 log_error("Could not allocate message.");
3433 if (!dbus_message_append_args(m,
3434 DBUS_TYPE_STRING, &interface,
3435 DBUS_TYPE_STRING, &property,
3436 DBUS_TYPE_INVALID)) {
3437 log_error("Could not append arguments to message.");
3442 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3443 log_error("Failed to issue method call: %s", bus_error_message(&error));
3448 if (!dbus_message_iter_init(reply, &iter) ||
3449 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3450 log_error("Failed to parse reply.");
3455 dbus_message_iter_recurse(&iter, &sub);
3457 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3458 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3459 log_error("Failed to parse reply.");
3464 dbus_message_iter_recurse(&sub, &sub2);
3466 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3469 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3470 log_error("Failed to parse reply.");
3475 dbus_message_iter_get_basic(&sub2, &text);
3476 printf("%s\n", text);
3478 dbus_message_iter_next(&sub2);
3485 dbus_message_unref(m);
3488 dbus_message_unref(reply);
3490 dbus_error_free(&error);
3495 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3496 DBusMessage *m = NULL, *reply = NULL;
3500 DBusMessageIter iter, sub;
3503 dbus_error_init(&error);
3505 method = streq(args[0], "set-environment")
3507 : "UnsetEnvironment";
3509 if (!(m = dbus_message_new_method_call(
3510 "org.freedesktop.systemd1",
3511 "/org/freedesktop/systemd1",
3512 "org.freedesktop.systemd1.Manager",
3515 log_error("Could not allocate message.");
3519 dbus_message_iter_init_append(m, &iter);
3521 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3522 log_error("Could not append arguments to message.");
3527 for (i = 1; i < n; i++)
3528 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3529 log_error("Could not append arguments to message.");
3534 if (!dbus_message_iter_close_container(&iter, &sub)) {
3535 log_error("Could not append arguments to message.");
3540 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3541 log_error("Failed to issue method call: %s", bus_error_message(&error));
3550 dbus_message_unref(m);
3553 dbus_message_unref(reply);
3555 dbus_error_free(&error);
3568 static Hashmap *will_install = NULL, *have_installed = NULL;
3569 static Set *remove_symlinks_to = NULL;
3570 static unsigned n_symlinks = 0;
3572 static void install_info_free(InstallInfo *i) {
3577 strv_free(i->aliases);
3578 strv_free(i->wanted_by);
3582 static void install_info_hashmap_free(Hashmap *m) {
3585 while ((i = hashmap_steal_first(m)))
3586 install_info_free(i);
3591 static int install_info_add(const char *name) {
3595 assert(will_install);
3597 if (!unit_name_is_valid_no_type(name, true)) {
3598 log_warning("Unit name %s is not a valid unit name.", name);
3602 if (hashmap_get(have_installed, name) ||
3603 hashmap_get(will_install, name))
3606 if (!(i = new0(InstallInfo, 1))) {
3611 if (!(i->name = strdup(name))) {
3616 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3623 install_info_free(i);
3628 static int config_parse_also(
3629 const char *filename,
3631 const char *section,
3646 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3650 if (!(n = strndup(w, l)))
3653 if ((r = install_info_add(n)) < 0) {
3654 log_warning("Cannot install unit %s: %s", n, strerror(-r));
3665 static int mark_symlink_for_removal(const char *p) {
3670 assert(path_is_absolute(p));
3672 if (!remove_symlinks_to)
3675 if (!(n = strdup(p)))
3678 path_kill_slashes(n);
3680 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3682 return r == -EEXIST ? 0 : r;
3688 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3697 if (!(d = fdopendir(fd))) {
3698 close_nointr_nofail(fd);
3704 while ((de = readdir(d))) {
3705 bool is_dir = false, is_link = false;
3707 if (ignore_file(de->d_name))
3710 if (de->d_type == DT_LNK)
3712 else if (de->d_type == DT_DIR)
3714 else if (de->d_type == DT_UNKNOWN) {
3717 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3718 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3725 is_link = S_ISLNK(st.st_mode);
3726 is_dir = S_ISDIR(st.st_mode);
3734 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3735 log_error("Failed to open %s/%s: %m", root, de->d_name);
3742 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3743 log_error("Failed to allocate directory string.");
3744 close_nointr_nofail(nfd);
3749 /* This will close nfd, regardless whether it succeeds or not */
3750 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3756 } else if (is_link) {
3760 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3761 log_error("Failed to allocate symlink string.");
3766 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3767 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3775 if ((c = canonicalize_file_name(dest))) {
3776 /* This might fail if the destination
3777 * is already removed */
3783 path_kill_slashes(dest);
3784 if (set_get(remove_symlinks_to, dest)) {
3787 log_info("rm '%s'", p);
3789 if (unlink(p) < 0) {
3790 log_error("Cannot unlink symlink %s: %m", p);
3795 rmdir_parents(p, config_path);
3796 path_kill_slashes(p);
3798 if (!set_get(remove_symlinks_to, p)) {
3800 if ((r = mark_symlink_for_removal(p)) < 0) {
3819 static int remove_marked_symlinks(const char *config_path) {
3823 assert(config_path);
3825 if (set_size(remove_symlinks_to) <= 0)
3828 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3835 if ((cfd = dup(fd)) < 0) {
3840 /* This takes possession of cfd and closes it */
3841 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3847 close_nointr_nofail(fd);
3852 static int create_symlink(const char *verb, const char *orig_old_path, const char *new_path) {
3854 const char *old_path;
3857 old_path = orig_old_path+strlen(arg_root);
3859 old_path = orig_old_path;
3865 if (streq(verb, "enable")) {
3868 mkdir_parents(new_path, 0755);
3870 if (symlink(old_path, new_path) >= 0) {
3873 log_info("ln -s '%s' '%s'", old_path, new_path);
3878 if (errno != EEXIST) {
3879 log_error("Cannot link %s to %s: %m", old_path, new_path);
3883 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3885 if (errno == EINVAL) {
3886 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3890 log_error("readlink() failed: %s", strerror(-r));
3894 if (streq(dest, old_path)) {
3900 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3909 log_info("ln -s '%s' '%s'", old_path, new_path);
3911 if (symlink(old_path, new_path) >= 0)
3914 log_error("Cannot link %s to %s: %m", old_path, new_path);
3917 } else if (streq(verb, "disable")) {
3920 if ((r = mark_symlink_for_removal(old_path)) < 0)
3923 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3924 if (errno == ENOENT)
3927 if (errno == EINVAL) {
3928 log_warning("File %s not a symlink, ignoring.", old_path);
3932 log_error("readlink() failed: %s", strerror(-r));
3936 if (!streq(dest, old_path)) {
3937 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3944 if ((r = mark_symlink_for_removal(new_path)) < 0)
3948 log_info("rm '%s'", new_path);
3950 if (unlink(new_path) >= 0)
3953 log_error("Cannot unlink %s: %m", new_path);
3956 } else if (streq(verb, "is-enabled")) {
3959 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3961 if (errno == ENOENT || errno == EINVAL)
3964 log_error("readlink() failed: %s", strerror(-r));
3968 if (streq(dest, old_path)) {
3977 assert_not_reached("Unknown action.");
3980 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3982 char *alias_path = NULL;
3987 assert(config_path);
3989 STRV_FOREACH(s, i->aliases) {
3992 if (!(alias_path = path_make_absolute(*s, config_path))) {
3993 log_error("Out of memory");
3998 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
4001 if (streq(verb, "disable"))
4002 rmdir_parents(alias_path, config_path);
4012 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
4014 char *alias_path = NULL;
4019 assert(config_path);
4021 STRV_FOREACH(s, i->wanted_by) {
4022 if (!unit_name_is_valid_no_type(*s, true)) {
4023 log_error("Invalid name %s.", *s);
4031 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
4032 log_error("Out of memory");
4037 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
4040 if (streq(verb, "disable"))
4041 rmdir_parents(alias_path, config_path);
4052 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
4054 const ConfigItem items[] = {
4055 { "Alias", config_parse_strv, 0, &i->aliases, "Install" },
4056 { "WantedBy", config_parse_strv, 0, &i->wanted_by, "Install" },
4057 { "Also", config_parse_also, 0, NULL, "Install" },
4059 { NULL, NULL, 0, NULL, NULL }
4063 char *filename = NULL;
4070 STRV_FOREACH(p, paths->unit_path) {
4072 char *path, *should_free;
4075 should_free = path = strappend(arg_root, *p);
4081 if (!(filename = path_make_absolute(i->name, path))) {
4082 log_error("Out of memory");
4089 /* Ensure that we don't follow symlinks */
4090 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
4091 if ((f = fdopen(fd, "re")))
4094 if (errno == ELOOP) {
4095 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
4100 if (errno != ENOENT) {
4101 log_error("Failed to open %s: %m", filename);
4111 #if (defined(TARGET_FEDORA) || defined(TARGET_MANDRIVA) || defined(TARGET_SUSE) || defined(TARGET_MEEGO) || defined(TARGET_ALTLINUX)) && defined (HAVE_SYSV_COMPAT)
4113 if (endswith(i->name, ".service")) {
4117 if (asprintf(&sysv, SYSTEM_SYSVINIT_PATH "/%s", i->name) < 0) {
4118 log_error("Out of memory");
4122 sysv[strlen(sysv) - sizeof(".service") + 1] = 0;
4126 tmp_path = strappend (arg_root, sysv);
4127 exists = access (tmp_path, F_OK) >= 0;
4130 exists = access(sysv, F_OK) >= 0;
4136 const char *argv[] = {
4144 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", i->name);
4146 argv[1] = file_name_from_path(sysv);
4148 streq(verb, "enable") ? "on" :
4149 streq(verb, "disable") ? "off" : "--level=5";
4151 argv[3] = strappend("--root=", arg_root);
4153 log_info("Executing %s %s %s %s", argv[0], argv[1], strempty(argv[2]), strempty(argv[3]));
4155 if ((pid = fork()) < 0) {
4156 log_error("Failed to fork: %m");
4159 } else if (pid == 0) {
4160 execv(argv[0], (char**) argv);
4161 _exit(EXIT_FAILURE);
4166 if ((r = wait_for_terminate(pid, &status)) < 0)
4169 if (status.si_code == CLD_EXITED) {
4171 if (streq(verb, "is-enabled"))
4172 return status.si_status == 0 ? 1 : 0;
4174 if (status.si_status == 0)
4177 return status.si_status == 0 ? 0 : -EINVAL;
4188 log_error("Couldn't find %s.", i->name);
4194 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
4199 /* Consider unit files stored in /lib and /usr always enabled
4200 * if they have no [Install] data. */
4201 if (streq(verb, "is-enabled") &&
4202 strv_isempty(i->aliases) &&
4203 strv_isempty(i->wanted_by) &&
4204 !path_startswith(filename, "/etc")) {
4209 n_symlinks += strv_length(i->aliases);
4210 n_symlinks += strv_length(i->wanted_by);
4214 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
4217 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
4220 if ((r = mark_symlink_for_removal(filename)) < 0)
4223 if ((r = remove_marked_symlinks(config_path)) < 0)
4229 static char *get_config_path(void) {
4232 if (arg_user && arg_global)
4233 ret = strdup(USER_CONFIG_UNIT_PATH);
4236 if (user_config_home(&ret) < 0)
4240 ret = strdup(SYSTEM_CONFIG_UNIT_PATH);
4243 p = strappend (arg_root, ret);
4250 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
4254 char *config_path = NULL;
4257 const char *verb = args[0];
4259 dbus_error_init(&error);
4262 if ((r = lookup_paths_init(&paths, arg_user ? MANAGER_USER : MANAGER_SYSTEM)) < 0) {
4263 log_error("Failed to determine lookup paths: %s", strerror(-r));
4267 if (!(config_path = get_config_path())) {
4268 log_error("Failed to determine config path");
4273 will_install = hashmap_new(string_hash_func, string_compare_func);
4274 have_installed = hashmap_new(string_hash_func, string_compare_func);
4276 if (!will_install || !have_installed) {
4277 log_error("Failed to allocate unit sets.");
4282 if (!arg_defaults && streq(verb, "disable"))
4283 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
4284 log_error("Failed to allocate symlink sets.");
4289 for (j = 1; j < n; j++)
4290 if ((r = install_info_add(args[j])) < 0) {
4291 log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
4297 while ((i = hashmap_first(will_install))) {
4300 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
4302 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
4310 /* In test mode and found something */
4316 if (streq(verb, "is-enabled"))
4317 r = r > 0 ? 0 : -ENOENT;
4319 if (n_symlinks <= 0)
4320 log_warning("Unit files contain no applicable installation information. Ignoring.");
4323 /* Don't try to reload anything if the user asked us to not do this */
4325 /* Don't try to reload anything when updating a unit globally */
4327 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
4328 (arg_user || sd_booted() > 0) &&
4329 /* Don't try to reload anything if we are running in a chroot environment */
4330 (arg_user || running_in_chroot() <= 0 || arg_root) ) {
4333 if ((q = daemon_reload(bus, args, n)) < 0)
4339 install_info_hashmap_free(will_install);
4340 install_info_hashmap_free(have_installed);
4342 set_free_free(remove_symlinks_to);
4344 lookup_paths_free(&paths);
4351 static int systemctl_help(void) {
4353 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4354 "Send control commands to or query the systemd manager.\n\n"
4355 " -h --help Show this help\n"
4356 " --version Show package version\n"
4357 " -t --type=TYPE List only units of a particular type\n"
4358 " -p --property=NAME Show only properties by this name\n"
4359 " -a --all Show all units/properties, including dead/empty ones\n"
4360 " --failed Show only failed units\n"
4361 " --full Don't ellipsize unit names on output\n"
4362 " --fail When queueing a new job, fail if conflicting jobs are\n"
4364 " --ignore-dependencies\n"
4365 " When queueing a new job, ignore all its dependencies\n"
4366 " --kill-mode=MODE How to send signal\n"
4367 " --kill-who=WHO Who to send signal to\n"
4368 " -s --signal=SIGNAL Which signal to send\n"
4369 " -H --host=[user@]host\n"
4370 " Show information for remote host\n"
4371 " -P --privileged Acquire privileges before execution\n"
4372 " -q --quiet Suppress output\n"
4373 " --no-block Do not wait until operation finished\n"
4374 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4375 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4377 " --no-pager Do not pipe output into a pager.\n"
4378 " --no-ask-password\n"
4379 " Do not ask for system passwords\n"
4380 " --order When generating graph for dot, show only order\n"
4381 " --require When generating graph for dot, show only requirement\n"
4382 " --root=path Use <root> as the root file system\n"
4383 " --system Connect to system manager\n"
4384 " --user Connect to user service manager\n"
4385 " --global Enable/disable unit files globally\n"
4386 " -f --force When enabling unit files, override existing symlinks\n"
4387 " When shutting down, execute action immediately\n"
4388 " --defaults When disabling unit files, remove default symlinks only\n\n"
4390 " list-units List units\n"
4391 " start [NAME...] Start (activate) one or more units\n"
4392 " stop [NAME...] Stop (deactivate) one or more units\n"
4393 " reload [NAME...] Reload one or more units\n"
4394 " restart [NAME...] Start or restart one or more units\n"
4395 " try-restart [NAME...] Restart one or more units if active\n"
4396 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4397 " otherwise start or restart\n"
4398 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4399 " otherwise restart if active\n"
4400 " isolate [NAME] Start one unit and stop all others\n"
4401 " kill [NAME...] Send signal to processes of a unit\n"
4402 " is-active [NAME...] Check whether units are active\n"
4403 " status [NAME...|PID...] Show runtime status of one or more units\n"
4404 " show [NAME...|JOB...] Show properties of one or more\n"
4405 " units/jobs or the manager\n"
4406 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4408 " enable [NAME...] Enable one or more unit files\n"
4409 " disable [NAME...] Disable one or more unit files\n"
4410 " is-enabled [NAME...] Check whether unit files are enabled\n"
4411 " load [NAME...] Load one or more units\n"
4412 " list-jobs List jobs\n"
4413 " cancel [JOB...] Cancel all, one, or more jobs\n"
4414 " monitor Monitor unit/job changes\n"
4415 " dump Dump server status\n"
4416 " dot Dump dependency graph for dot(1)\n"
4417 " snapshot [NAME] Create a snapshot\n"
4418 " delete [NAME...] Remove one or more snapshots\n"
4419 " daemon-reload Reload systemd manager configuration\n"
4420 " daemon-reexec Reexecute systemd manager\n"
4421 " show-environment Dump environment\n"
4422 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4423 " unset-environment [NAME...] Unset one or more environment variables\n"
4424 " default Enter system default mode\n"
4425 " rescue Enter system rescue mode\n"
4426 " emergency Enter system emergency mode\n"
4427 " halt Shut down and halt the system\n"
4428 " poweroff Shut down and power-off the system\n"
4429 " reboot Shut down and reboot the system\n"
4430 " kexec Shut down and reboot the system with kexec\n"
4431 " exit Ask for user instance termination\n",
4432 program_invocation_short_name);
4437 static int halt_help(void) {
4439 printf("%s [OPTIONS...]\n\n"
4440 "%s the system.\n\n"
4441 " --help Show this help\n"
4442 " --halt Halt the machine\n"
4443 " -p --poweroff Switch off the machine\n"
4444 " --reboot Reboot the machine\n"
4445 " -f --force Force immediate halt/power-off/reboot\n"
4446 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4447 " -d --no-wtmp Don't write wtmp record\n"
4448 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4449 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4450 program_invocation_short_name,
4451 arg_action == ACTION_REBOOT ? "Reboot" :
4452 arg_action == ACTION_POWEROFF ? "Power off" :
4458 static int shutdown_help(void) {
4460 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4461 "Shut down the system.\n\n"
4462 " --help Show this help\n"
4463 " -H --halt Halt the machine\n"
4464 " -P --poweroff Power-off the machine\n"
4465 " -r --reboot Reboot the machine\n"
4466 " -h Equivalent to --poweroff, overriden by --halt\n"
4467 " -k Don't halt/power-off/reboot, just send warnings\n"
4468 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4469 " -c Cancel a pending shutdown\n",
4470 program_invocation_short_name);
4475 static int telinit_help(void) {
4477 printf("%s [OPTIONS...] {COMMAND}\n\n"
4478 "Send control commands to the init daemon.\n\n"
4479 " --help Show this help\n"
4480 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4482 " 0 Power-off the machine\n"
4483 " 6 Reboot the machine\n"
4484 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4485 " 1, s, S Enter rescue mode\n"
4486 " q, Q Reload init daemon configuration\n"
4487 " u, U Reexecute init daemon\n",
4488 program_invocation_short_name);
4493 static int runlevel_help(void) {
4495 printf("%s [OPTIONS...]\n\n"
4496 "Prints the previous and current runlevel of the init system.\n\n"
4497 " --help Show this help\n",
4498 program_invocation_short_name);
4503 static int systemctl_parse_argv(int argc, char *argv[]) {
4507 ARG_IGNORE_DEPENDENCIES,
4523 ARG_NO_ASK_PASSWORD,
4527 static const struct option options[] = {
4528 { "help", no_argument, NULL, 'h' },
4529 { "version", no_argument, NULL, ARG_VERSION },
4530 { "type", required_argument, NULL, 't' },
4531 { "property", required_argument, NULL, 'p' },
4532 { "all", no_argument, NULL, 'a' },
4533 { "failed", no_argument, NULL, ARG_FAILED },
4534 { "full", no_argument, NULL, ARG_FULL },
4535 { "fail", no_argument, NULL, ARG_FAIL },
4536 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4537 { "user", no_argument, NULL, ARG_USER },
4538 { "system", no_argument, NULL, ARG_SYSTEM },
4539 { "global", no_argument, NULL, ARG_GLOBAL },
4540 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4541 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4542 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4543 { "quiet", no_argument, NULL, 'q' },
4544 { "order", no_argument, NULL, ARG_ORDER },
4545 { "require", no_argument, NULL, ARG_REQUIRE },
4546 { "root", required_argument, NULL, ARG_ROOT },
4547 { "force", no_argument, NULL, 'f' },
4548 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4549 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4550 { "kill-mode", required_argument, NULL, ARG_KILL_MODE },
4551 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4552 { "signal", required_argument, NULL, 's' },
4553 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4554 { "host", required_argument, NULL, 'H' },
4555 { "privileged",no_argument, NULL, 'P' },
4556 { NULL, 0, NULL, 0 }
4564 /* Only when running as systemctl we ask for passwords */
4565 arg_ask_password = true;
4567 while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:P", options, NULL)) >= 0) {
4576 puts(PACKAGE_STRING);
4578 puts(SYSTEMD_FEATURES);
4588 if (!(l = strv_append(arg_property, optarg)))
4591 strv_free(arg_property);
4594 /* If the user asked for a particular
4595 * property, show it to him, even if it is
4606 arg_job_mode = "fail";
4609 case ARG_IGNORE_DEPENDENCIES:
4610 arg_job_mode = "ignore-dependencies";
4622 arg_no_block = true;
4626 arg_no_pager = true;
4634 arg_dot = DOT_ORDER;
4638 arg_dot = DOT_REQUIRE;
4662 arg_no_reload = true;
4671 arg_defaults = true;
4675 arg_kill_who = optarg;
4679 arg_kill_mode = optarg;
4683 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4684 log_error("Failed to parse signal string %s.", optarg);
4689 case ARG_NO_ASK_PASSWORD:
4690 arg_ask_password = false;
4694 arg_transport = TRANSPORT_POLKIT;
4698 arg_transport = TRANSPORT_SSH;
4706 log_error("Unknown option code %c", c);
4711 if (arg_transport != TRANSPORT_NORMAL && arg_user) {
4712 log_error("Cannot access user instance remotely.");
4719 static int halt_parse_argv(int argc, char *argv[]) {
4728 static const struct option options[] = {
4729 { "help", no_argument, NULL, ARG_HELP },
4730 { "halt", no_argument, NULL, ARG_HALT },
4731 { "poweroff", no_argument, NULL, 'p' },
4732 { "reboot", no_argument, NULL, ARG_REBOOT },
4733 { "force", no_argument, NULL, 'f' },
4734 { "wtmp-only", no_argument, NULL, 'w' },
4735 { "no-wtmp", no_argument, NULL, 'd' },
4736 { "no-sync", no_argument, NULL, 'n' },
4737 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4738 { NULL, 0, NULL, 0 }
4746 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4747 if (runlevel == '0' || runlevel == '6')
4748 arg_immediate = true;
4750 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4758 arg_action = ACTION_HALT;
4762 if (arg_action != ACTION_REBOOT)
4763 arg_action = ACTION_POWEROFF;
4767 arg_action = ACTION_REBOOT;
4771 arg_immediate = true;
4792 /* Compatibility nops */
4799 log_error("Unknown option code %c", c);
4804 if (optind < argc) {
4805 log_error("Too many arguments.");
4812 static int parse_time_spec(const char *t, usec_t *_u) {
4816 if (streq(t, "now"))
4818 else if (t[0] == '+') {
4821 if (safe_atou64(t + 1, &u) < 0)
4824 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4833 hour = strtol(t, &e, 10);
4834 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4837 minute = strtol(e+1, &e, 10);
4838 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4841 n = now(CLOCK_REALTIME);
4842 s = (time_t) (n / USEC_PER_SEC);
4845 assert_se(localtime_r(&s, &tm));
4847 tm.tm_hour = (int) hour;
4848 tm.tm_min = (int) minute;
4851 assert_se(s = mktime(&tm));
4853 *_u = (usec_t) s * USEC_PER_SEC;
4856 *_u += USEC_PER_DAY;
4862 static bool kexec_loaded(void) {
4863 bool loaded = false;
4866 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4874 static int shutdown_parse_argv(int argc, char *argv[]) {
4881 static const struct option options[] = {
4882 { "help", no_argument, NULL, ARG_HELP },
4883 { "halt", no_argument, NULL, 'H' },
4884 { "poweroff", no_argument, NULL, 'P' },
4885 { "reboot", no_argument, NULL, 'r' },
4886 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4887 { NULL, 0, NULL, 0 }
4895 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4903 arg_action = ACTION_HALT;
4907 arg_action = ACTION_POWEROFF;
4912 arg_action = ACTION_KEXEC;
4914 arg_action = ACTION_REBOOT;
4918 if (arg_action != ACTION_HALT)
4919 arg_action = ACTION_POWEROFF;
4932 /* Compatibility nops */
4936 arg_action = ACTION_CANCEL_SHUTDOWN;
4943 log_error("Unknown option code %c", c);
4948 if (argc > optind) {
4949 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4950 log_error("Failed to parse time specification: %s", argv[optind]);
4954 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4956 /* We skip the time argument */
4957 if (argc > optind + 1)
4958 arg_wall = argv + optind + 1;
4965 static int telinit_parse_argv(int argc, char *argv[]) {
4972 static const struct option options[] = {
4973 { "help", no_argument, NULL, ARG_HELP },
4974 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4975 { NULL, 0, NULL, 0 }
4978 static const struct {
4982 { '0', ACTION_POWEROFF },
4983 { '6', ACTION_REBOOT },
4984 { '1', ACTION_RESCUE },
4985 { '2', ACTION_RUNLEVEL2 },
4986 { '3', ACTION_RUNLEVEL3 },
4987 { '4', ACTION_RUNLEVEL4 },
4988 { '5', ACTION_RUNLEVEL5 },
4989 { 's', ACTION_RESCUE },
4990 { 'S', ACTION_RESCUE },
4991 { 'q', ACTION_RELOAD },
4992 { 'Q', ACTION_RELOAD },
4993 { 'u', ACTION_REEXEC },
4994 { 'U', ACTION_REEXEC }
5003 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5018 log_error("Unknown option code %c", c);
5023 if (optind >= argc) {
5028 if (optind + 1 < argc) {
5029 log_error("Too many arguments.");
5033 if (strlen(argv[optind]) != 1) {
5034 log_error("Expected single character argument.");
5038 for (i = 0; i < ELEMENTSOF(table); i++)
5039 if (table[i].from == argv[optind][0])
5042 if (i >= ELEMENTSOF(table)) {
5043 log_error("Unknown command %s.", argv[optind]);
5047 arg_action = table[i].to;
5054 static int runlevel_parse_argv(int argc, char *argv[]) {
5060 static const struct option options[] = {
5061 { "help", no_argument, NULL, ARG_HELP },
5062 { NULL, 0, NULL, 0 }
5070 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5081 log_error("Unknown option code %c", c);
5086 if (optind < argc) {
5087 log_error("Too many arguments.");
5094 static int parse_argv(int argc, char *argv[]) {
5098 if (program_invocation_short_name) {
5100 if (strstr(program_invocation_short_name, "halt")) {
5101 arg_action = ACTION_HALT;
5102 return halt_parse_argv(argc, argv);
5103 } else if (strstr(program_invocation_short_name, "poweroff")) {
5104 arg_action = ACTION_POWEROFF;
5105 return halt_parse_argv(argc, argv);
5106 } else if (strstr(program_invocation_short_name, "reboot")) {
5108 arg_action = ACTION_KEXEC;
5110 arg_action = ACTION_REBOOT;
5111 return halt_parse_argv(argc, argv);
5112 } else if (strstr(program_invocation_short_name, "shutdown")) {
5113 arg_action = ACTION_POWEROFF;
5114 return shutdown_parse_argv(argc, argv);
5115 } else if (strstr(program_invocation_short_name, "init")) {
5117 if (sd_booted() > 0) {
5118 arg_action = ACTION_INVALID;
5119 return telinit_parse_argv(argc, argv);
5121 /* Hmm, so some other init system is
5122 * running, we need to forward this
5123 * request to it. For now we simply
5124 * guess that it is Upstart. */
5126 execv("/lib/upstart/telinit", argv);
5128 log_error("Couldn't find an alternative telinit implementation to spawn.");
5132 } else if (strstr(program_invocation_short_name, "runlevel")) {
5133 arg_action = ACTION_RUNLEVEL;
5134 return runlevel_parse_argv(argc, argv);
5138 arg_action = ACTION_SYSTEMCTL;
5139 return systemctl_parse_argv(argc, argv);
5142 static int action_to_runlevel(void) {
5144 static const char table[_ACTION_MAX] = {
5145 [ACTION_HALT] = '0',
5146 [ACTION_POWEROFF] = '0',
5147 [ACTION_REBOOT] = '6',
5148 [ACTION_RUNLEVEL2] = '2',
5149 [ACTION_RUNLEVEL3] = '3',
5150 [ACTION_RUNLEVEL4] = '4',
5151 [ACTION_RUNLEVEL5] = '5',
5152 [ACTION_RESCUE] = '1'
5155 assert(arg_action < _ACTION_MAX);
5157 return table[arg_action];
5160 static int talk_upstart(void) {
5161 DBusMessage *m = NULL, *reply = NULL;
5163 int previous, rl, r;
5165 env1_buf[] = "RUNLEVEL=X",
5166 env2_buf[] = "PREVLEVEL=X";
5167 char *env1 = env1_buf, *env2 = env2_buf;
5168 const char *emit = "runlevel";
5169 dbus_bool_t b_false = FALSE;
5170 DBusMessageIter iter, sub;
5171 DBusConnection *bus;
5173 dbus_error_init(&error);
5175 if (!(rl = action_to_runlevel()))
5178 if (utmp_get_runlevel(&previous, NULL) < 0)
5181 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
5182 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
5187 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
5192 if ((r = bus_check_peercred(bus)) < 0) {
5193 log_error("Failed to verify owner of bus.");
5197 if (!(m = dbus_message_new_method_call(
5198 "com.ubuntu.Upstart",
5199 "/com/ubuntu/Upstart",
5200 "com.ubuntu.Upstart0_6",
5203 log_error("Could not allocate message.");
5208 dbus_message_iter_init_append(m, &iter);
5210 env1_buf[sizeof(env1_buf)-2] = rl;
5211 env2_buf[sizeof(env2_buf)-2] = previous;
5213 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5214 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5215 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5216 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5217 !dbus_message_iter_close_container(&iter, &sub) ||
5218 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5219 log_error("Could not append arguments to message.");
5224 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5226 if (error_is_no_service(&error)) {
5231 log_error("Failed to issue method call: %s", bus_error_message(&error));
5240 dbus_message_unref(m);
5243 dbus_message_unref(reply);
5246 dbus_connection_flush(bus);
5247 dbus_connection_close(bus);
5248 dbus_connection_unref(bus);
5251 dbus_error_free(&error);
5256 static int talk_initctl(void) {
5257 struct init_request request;
5261 if (!(rl = action_to_runlevel()))
5265 request.magic = INIT_MAGIC;
5266 request.sleeptime = 0;
5267 request.cmd = INIT_CMD_RUNLVL;
5268 request.runlevel = rl;
5270 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5272 if (errno == ENOENT)
5275 log_error("Failed to open "INIT_FIFO": %m");
5280 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5281 close_nointr_nofail(fd);
5284 log_error("Failed to write to "INIT_FIFO": %m");
5285 return errno ? -errno : -EIO;
5291 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5293 static const struct {
5301 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
5303 { "list-units", LESS, 1, list_units },
5304 { "list-jobs", EQUAL, 1, list_jobs },
5305 { "clear-jobs", EQUAL, 1, daemon_reload },
5306 { "load", MORE, 2, load_unit },
5307 { "cancel", MORE, 2, cancel_job },
5308 { "start", MORE, 2, start_unit },
5309 { "stop", MORE, 2, start_unit },
5310 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5311 { "reload", MORE, 2, start_unit },
5312 { "restart", MORE, 2, start_unit },
5313 { "try-restart", MORE, 2, start_unit },
5314 { "reload-or-restart", MORE, 2, start_unit },
5315 { "reload-or-try-restart", MORE, 2, start_unit },
5316 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5317 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5318 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5319 { "isolate", EQUAL, 2, start_unit },
5320 { "kill", MORE, 2, kill_unit },
5321 { "is-active", MORE, 2, check_unit },
5322 { "check", MORE, 2, check_unit },
5323 { "show", MORE, 1, show },
5324 { "status", MORE, 2, show },
5325 { "monitor", EQUAL, 1, monitor },
5326 { "dump", EQUAL, 1, dump },
5327 { "dot", EQUAL, 1, dot },
5328 { "snapshot", LESS, 2, snapshot },
5329 { "delete", MORE, 2, delete_snapshot },
5330 { "daemon-reload", EQUAL, 1, daemon_reload },
5331 { "daemon-reexec", EQUAL, 1, daemon_reload },
5332 { "show-environment", EQUAL, 1, show_enviroment },
5333 { "set-environment", MORE, 2, set_environment },
5334 { "unset-environment", MORE, 2, set_environment },
5335 { "halt", EQUAL, 1, start_special },
5336 { "poweroff", EQUAL, 1, start_special },
5337 { "reboot", EQUAL, 1, start_special },
5338 { "kexec", EQUAL, 1, start_special },
5339 { "default", EQUAL, 1, start_special },
5340 { "rescue", EQUAL, 1, start_special },
5341 { "emergency", EQUAL, 1, start_special },
5342 { "exit", EQUAL, 1, start_special },
5343 { "reset-failed", MORE, 1, reset_failed },
5344 { "enable", MORE, 2, enable_unit },
5345 { "disable", MORE, 2, enable_unit },
5346 { "is-enabled", MORE, 2, enable_unit }
5356 left = argc - optind;
5359 /* Special rule: no arguments means "list-units" */
5362 if (streq(argv[optind], "help")) {
5367 for (i = 0; i < ELEMENTSOF(verbs); i++)
5368 if (streq(argv[optind], verbs[i].verb))
5371 if (i >= ELEMENTSOF(verbs)) {
5372 log_error("Unknown operation %s", argv[optind]);
5377 switch (verbs[i].argc_cmp) {
5380 if (left != verbs[i].argc) {
5381 log_error("Invalid number of arguments.");
5388 if (left < verbs[i].argc) {
5389 log_error("Too few arguments.");
5396 if (left > verbs[i].argc) {
5397 log_error("Too many arguments.");
5404 assert_not_reached("Unknown comparison operator.");
5407 /* Require a bus connection for all operations but
5409 if (!streq(verbs[i].verb, "enable") && !streq(verbs[i].verb, "disable")) {
5411 if (running_in_chroot() > 0) {
5412 log_info("Running in chroot, ignoring request.");
5417 log_error("Failed to get D-Bus connection: %s", error->message);
5422 return verbs[i].dispatch(bus, argv + optind, left);
5425 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
5427 struct msghdr msghdr;
5429 union sockaddr_union sockaddr;
5430 struct shutdownd_command c;
5438 strncpy(c.wall_message, message, sizeof(c.wall_message));
5440 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
5444 sockaddr.sa.sa_family = AF_UNIX;
5445 sockaddr.un.sun_path[0] = 0;
5446 strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5449 iovec.iov_base = (char*) &c;
5450 iovec.iov_len = sizeof(c);
5453 msghdr.msg_name = &sockaddr;
5454 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5456 msghdr.msg_iov = &iovec;
5457 msghdr.msg_iovlen = 1;
5459 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5460 close_nointr_nofail(fd);
5464 close_nointr_nofail(fd);
5468 static int reload_with_fallback(DBusConnection *bus) {
5471 /* First, try systemd via D-Bus. */
5472 if (daemon_reload(bus, NULL, 0) > 0)
5476 /* Nothing else worked, so let's try signals */
5477 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5479 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5480 log_error("kill() failed: %m");
5487 static int start_with_fallback(DBusConnection *bus) {
5490 /* First, try systemd via D-Bus. */
5491 if (start_unit(bus, NULL, 0) >= 0)
5495 /* Hmm, talking to systemd via D-Bus didn't work. Then
5496 * let's try to talk to Upstart via D-Bus. */
5497 if (talk_upstart() > 0)
5500 /* Nothing else worked, so let's try
5502 if (talk_initctl() > 0)
5505 log_error("Failed to talk to init daemon.");
5509 warn_wall(arg_action);
5513 static int halt_main(DBusConnection *bus) {
5516 if (geteuid() != 0) {
5517 log_error("Must be root.");
5523 char date[FORMAT_TIMESTAMP_MAX];
5525 m = strv_join(arg_wall, " ");
5526 r = send_shutdownd(arg_when,
5527 arg_action == ACTION_HALT ? 'H' :
5528 arg_action == ACTION_POWEROFF ? 'P' :
5535 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5537 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5538 format_timestamp(date, sizeof(date), arg_when));
5543 if (!arg_dry && !arg_immediate)
5544 return start_with_fallback(bus);
5547 if (sd_booted() > 0)
5548 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5549 else if ((r = utmp_put_shutdown(0)) < 0)
5550 log_warning("Failed to write utmp record: %s", strerror(-r));
5559 /* Make sure C-A-D is handled by the kernel from this
5561 reboot(RB_ENABLE_CAD);
5563 switch (arg_action) {
5566 log_info("Halting.");
5567 reboot(RB_HALT_SYSTEM);
5570 case ACTION_POWEROFF:
5571 log_info("Powering off.");
5572 reboot(RB_POWER_OFF);
5576 log_info("Rebooting.");
5577 reboot(RB_AUTOBOOT);
5581 assert_not_reached("Unknown halt action.");
5584 /* We should never reach this. */
5588 static int runlevel_main(void) {
5589 int r, runlevel, previous;
5591 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5592 printf("unknown\n");
5597 previous <= 0 ? 'N' : previous,
5598 runlevel <= 0 ? 'N' : runlevel);
5603 static void pager_open(void) {
5611 if (!on_tty() || arg_no_pager)
5614 if ((pager = getenv("SYSTEMD_PAGER")) || (pager = getenv("PAGER")))
5615 if (!*pager || streq(pager, "cat"))
5618 /* Determine and cache number of columns before we spawn the
5619 * pager so that we get the value from the actual tty */
5623 log_error("Failed to create pager pipe: %m");
5627 parent_pid = getpid();
5630 if (pager_pid < 0) {
5631 log_error("Failed to fork pager: %m");
5636 /* In the child start the pager */
5637 if (pager_pid == 0) {
5639 dup2(fd[0], STDIN_FILENO);
5642 setenv("LESS", "FRSX", 0);
5644 /* Make sure the pager goes away when the parent dies */
5645 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5646 _exit(EXIT_FAILURE);
5648 /* Check whether our parent died before we were able
5649 * to set the death signal */
5650 if (getppid() != parent_pid)
5651 _exit(EXIT_SUCCESS);
5654 execlp(pager, pager, NULL);
5655 execl("/bin/sh", "sh", "-c", pager, NULL);
5657 /* Debian's alternatives command for pagers is
5658 * called 'pager'. Note that we do not call
5659 * sensible-pagers here, since that is just a
5660 * shell script that implements a logic that
5661 * is similar to this one anyway, but is
5662 * Debian-specific. */
5663 execlp("pager", "pager", NULL);
5665 execlp("less", "less", NULL);
5666 execlp("more", "more", NULL);
5669 log_error("Unable to execute pager: %m");
5670 _exit(EXIT_FAILURE);
5673 /* Return in the parent */
5674 if (dup2(fd[1], STDOUT_FILENO) < 0)
5675 log_error("Failed to duplicate pager pipe: %m");
5680 static void pager_close(void) {
5686 /* Inform pager that we are done */
5688 kill(pager_pid, SIGCONT);
5689 wait_for_terminate(pager_pid, &dummy);
5693 static void agent_close(void) {
5699 /* Inform agent that we are done */
5700 kill(agent_pid, SIGTERM);
5701 kill(agent_pid, SIGCONT);
5702 wait_for_terminate(agent_pid, &dummy);
5706 int main(int argc, char*argv[]) {
5707 int r, retval = EXIT_FAILURE;
5708 DBusConnection *bus = NULL;
5711 dbus_error_init(&error);
5713 log_parse_environment();
5716 if ((r = parse_argv(argc, argv)) < 0)
5719 retval = EXIT_SUCCESS;
5723 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5724 * let's shortcut this */
5725 if (arg_action == ACTION_RUNLEVEL) {
5726 r = runlevel_main();
5727 retval = r < 0 ? EXIT_FAILURE : r;
5731 if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5732 log_info("Running in chroot, ignoring request.");
5737 if (arg_transport == TRANSPORT_NORMAL)
5738 bus_connect(arg_user ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5739 else if (arg_transport == TRANSPORT_POLKIT) {
5740 bus_connect_system_polkit(&bus, &error);
5741 private_bus = false;
5742 } else if (arg_transport == TRANSPORT_SSH) {
5743 bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5744 private_bus = false;
5746 assert_not_reached("Uh, invalid transport...");
5748 switch (arg_action) {
5750 case ACTION_SYSTEMCTL:
5751 r = systemctl_main(bus, argc, argv, &error);
5755 case ACTION_POWEROFF:
5761 case ACTION_RUNLEVEL2:
5762 case ACTION_RUNLEVEL3:
5763 case ACTION_RUNLEVEL4:
5764 case ACTION_RUNLEVEL5:
5766 case ACTION_EMERGENCY:
5767 case ACTION_DEFAULT:
5768 r = start_with_fallback(bus);
5773 r = reload_with_fallback(bus);
5776 case ACTION_CANCEL_SHUTDOWN:
5777 r = send_shutdownd(0, 0, false, NULL);
5780 case ACTION_INVALID:
5781 case ACTION_RUNLEVEL:
5783 assert_not_reached("Unknown action");
5786 retval = r < 0 ? EXIT_FAILURE : r;
5791 dbus_connection_flush(bus);
5792 dbus_connection_close(bus);
5793 dbus_connection_unref(bus);
5796 dbus_error_free(&error);
5800 strv_free(arg_property);