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"
61 static const char *arg_type = NULL;
62 static char **arg_property = NULL;
63 static bool arg_all = false;
64 static const char *arg_job_mode = "replace";
65 static bool arg_user = false;
66 static bool arg_global = false;
67 static bool arg_immediate = false;
68 static bool arg_no_block = false;
69 static bool arg_no_pager = false;
70 static bool arg_no_wtmp = false;
71 static bool arg_no_sync = false;
72 static bool arg_no_wall = false;
73 static bool arg_no_reload = false;
74 static bool arg_dry = false;
75 static bool arg_quiet = false;
76 static bool arg_full = false;
77 static bool arg_force = false;
78 static bool arg_defaults = false;
79 static bool arg_ask_password = false;
80 static bool arg_failed = false;
81 static char **arg_wall = NULL;
82 static const char *arg_kill_who = NULL;
83 static const char *arg_kill_mode = NULL;
84 static const char *arg_root = NULL;
85 static int arg_signal = SIGTERM;
86 static usec_t arg_when = 0;
105 ACTION_CANCEL_SHUTDOWN,
107 } arg_action = ACTION_SYSTEMCTL;
113 static enum transport {
117 } arg_transport = TRANSPORT_NORMAL;
118 static const char *arg_host = NULL;
120 static bool private_bus = false;
122 static pid_t agent_pid = 0;
124 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
126 static void pager_open_if_enabled(void) {
131 static bool on_tty(void) {
134 /* Note that this is invoked relatively early, before we start
135 * the pager. That means the value we return reflects whether
136 * we originally were started on a tty, not if we currently
137 * are. But this is intended, since we want colour and so on
138 * when run in our own pager. */
140 if (_unlikely_(t < 0))
141 t = isatty(STDOUT_FILENO) > 0;
146 static void spawn_ask_password_agent(void) {
152 /* We check STDIN here, not STDOUT, since this is about input,
154 if (!isatty(STDIN_FILENO))
157 if (!arg_ask_password)
165 /* Spawns a temporary TTY agent, making sure it goes away when
168 if ((agent_pid = fork()) < 0)
171 if (agent_pid == 0) {
175 bool stdout_is_tty, stderr_is_tty;
177 /* Make sure the agent goes away when the parent dies */
178 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
181 /* Check whether our parent died before we were able
182 * to set the death signal */
183 if (getppid() != parent)
186 /* Don't leak fds to the agent */
187 close_all_fds(NULL, 0);
189 stdout_is_tty = isatty(STDOUT_FILENO);
190 stderr_is_tty = isatty(STDERR_FILENO);
192 if (!stdout_is_tty || !stderr_is_tty) {
193 /* Detach from stdout/stderr. and reopen
194 * /dev/tty for them. This is important to
195 * ensure that when systemctl is started via
196 * popen() or a similar call that expects to
197 * read EOF we actually do generate EOF and
198 * not delay this indefinitely by because we
199 * keep an unused copy of stdin around. */
200 if ((fd = open("/dev/tty", O_WRONLY)) < 0) {
201 log_error("Failed to open /dev/tty: %m");
206 dup2(fd, STDOUT_FILENO);
209 dup2(fd, STDERR_FILENO);
215 execl(SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, "--watch", NULL);
217 log_error("Unable to execute agent: %m");
222 static const char *ansi_highlight(bool b) {
227 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
230 static const char *ansi_highlight_green(bool b) {
235 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
238 static bool error_is_no_service(const DBusError *error) {
241 if (!dbus_error_is_set(error))
244 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
247 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
250 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
253 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
256 if (!dbus_error_is_set(error))
259 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
260 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
261 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
262 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
263 return EXIT_NOPERMISSION;
265 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
266 return EXIT_NOTINSTALLED;
268 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
269 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
270 return EXIT_NOTIMPLEMENTED;
272 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
273 return EXIT_NOTCONFIGURED;
281 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
286 if (dbus_message_iter_get_arg_type(iter) != type)
289 dbus_message_iter_get_basic(iter, data);
291 if (!dbus_message_iter_next(iter) != !next)
297 static void warn_wall(enum action action) {
298 static const char *table[_ACTION_MAX] = {
299 [ACTION_HALT] = "The system is going down for system halt NOW!",
300 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
301 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
302 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
303 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
304 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
313 if (!(p = strv_join(arg_wall, " "))) {
314 log_error("Failed to join strings.");
330 utmp_wall(table[action], NULL);
335 const char *description;
336 const char *load_state;
337 const char *active_state;
338 const char *sub_state;
339 const char *following;
340 const char *unit_path;
342 const char *job_type;
343 const char *job_path;
346 static int compare_unit_info(const void *a, const void *b) {
348 const struct unit_info *u = a, *v = b;
350 d1 = strrchr(u->id, '.');
351 d2 = strrchr(v->id, '.');
356 if ((r = strcasecmp(d1, d2)) != 0)
360 return strcasecmp(u->id, v->id);
363 static bool output_show_unit(const struct unit_info *u) {
367 return streq(u->active_state, "failed");
369 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
370 streq(dot+1, arg_type))) &&
371 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0);
374 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
375 unsigned active_len, sub_len, job_len, n_shown = 0;
376 const struct unit_info *u;
378 active_len = sizeof("ACTIVE")-1;
379 sub_len = sizeof("SUB")-1;
380 job_len = sizeof("JOB")-1;
382 for (u = unit_infos; u < unit_infos + c; u++) {
383 if (!output_show_unit(u))
386 active_len = MAX(active_len, strlen(u->active_state));
387 sub_len = MAX(sub_len, strlen(u->sub_state));
389 job_len = MAX(job_len, strlen(u->job_type));
393 printf("%-25s %-6s %-*s %-*s %-*s", "UNIT", "LOAD",
394 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
395 if (columns() >= 80+12 || arg_full || !arg_no_pager)
396 printf(" %s\n", "DESCRIPTION");
401 for (u = unit_infos; u < unit_infos + c; u++) {
404 const char *on_loaded, *off_loaded;
405 const char *on_active, *off_active;
407 if (!output_show_unit(u))
412 if (!streq(u->load_state, "loaded") &&
413 !streq(u->load_state, "banned")) {
414 on_loaded = ansi_highlight(true);
415 off_loaded = ansi_highlight(false);
417 on_loaded = off_loaded = "";
419 if (streq(u->active_state, "failed")) {
420 on_active = ansi_highlight(true);
421 off_active = ansi_highlight(false);
423 on_active = off_active = "";
425 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
427 printf("%-25s %s%-6s%s %s%-*s %-*s%s%n",
429 on_loaded, u->load_state, off_loaded,
430 on_active, active_len, u->active_state,
431 sub_len, u->sub_state, off_active,
436 a -= strlen(on_loaded) + strlen(off_loaded);
437 a -= strlen(on_active) + strlen(off_active);
440 printf(" %-*s", job_len, u->job_type);
444 if (a + b + 1 < columns()) {
446 printf(" %-*s", job_len, "");
448 if (arg_full || !arg_no_pager)
449 printf(" %s", u->description);
451 printf(" %.*s", columns() - a - b - 1, u->description);
458 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
459 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
460 "SUB = The low-level unit activation state, values depend on unit type.\n"
461 "JOB = Pending job for the unit.\n");
464 printf("\n%u units listed.\n", n_shown);
466 printf("\n%u units listed. Pass --all to see inactive units, too.\n", n_shown);
470 static int list_units(DBusConnection *bus, char **args, unsigned n) {
471 DBusMessage *m = NULL, *reply = NULL;
474 DBusMessageIter iter, sub, sub2;
475 unsigned c = 0, n_units = 0;
476 struct unit_info *unit_infos = NULL;
478 dbus_error_init(&error);
482 pager_open_if_enabled();
484 if (!(m = dbus_message_new_method_call(
485 "org.freedesktop.systemd1",
486 "/org/freedesktop/systemd1",
487 "org.freedesktop.systemd1.Manager",
489 log_error("Could not allocate message.");
493 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
494 log_error("Failed to issue method call: %s", bus_error_message(&error));
499 if (!dbus_message_iter_init(reply, &iter) ||
500 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
501 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
502 log_error("Failed to parse reply.");
507 dbus_message_iter_recurse(&iter, &sub);
509 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
512 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
513 log_error("Failed to parse reply.");
521 n_units = MAX(2*c, 16);
522 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
525 log_error("Failed to allocate unit array.");
535 dbus_message_iter_recurse(&sub, &sub2);
537 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
538 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
539 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
540 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
541 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
542 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
543 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
544 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
545 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
546 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
547 log_error("Failed to parse reply.");
552 dbus_message_iter_next(&sub);
557 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
558 output_units_list(unit_infos, c);
565 dbus_message_unref(m);
568 dbus_message_unref(reply);
572 dbus_error_free(&error);
577 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
578 static const char * const colors[] = {
579 "Requires", "[color=\"black\"]",
580 "RequiresOverridable", "[color=\"black\"]",
581 "Requisite", "[color=\"darkblue\"]",
582 "RequisiteOverridable", "[color=\"darkblue\"]",
583 "Wants", "[color=\"darkgrey\"]",
584 "Conflicts", "[color=\"red\"]",
585 "ConflictedBy", "[color=\"red\"]",
586 "After", "[color=\"green\"]"
589 const char *c = NULL;
596 for (i = 0; i < ELEMENTSOF(colors); i += 2)
597 if (streq(colors[i], prop)) {
605 if (arg_dot != DOT_ALL)
606 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
609 switch (dbus_message_iter_get_arg_type(iter)) {
611 case DBUS_TYPE_ARRAY:
613 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
616 dbus_message_iter_recurse(iter, &sub);
618 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
621 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
622 dbus_message_iter_get_basic(&sub, &s);
623 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
625 dbus_message_iter_next(&sub);
635 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
636 DBusMessage *m = NULL, *reply = NULL;
637 const char *interface = "org.freedesktop.systemd1.Unit";
640 DBusMessageIter iter, sub, sub2, sub3;
645 dbus_error_init(&error);
647 if (!(m = dbus_message_new_method_call(
648 "org.freedesktop.systemd1",
650 "org.freedesktop.DBus.Properties",
652 log_error("Could not allocate message.");
657 if (!dbus_message_append_args(m,
658 DBUS_TYPE_STRING, &interface,
659 DBUS_TYPE_INVALID)) {
660 log_error("Could not append arguments to message.");
665 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
666 log_error("Failed to issue method call: %s", bus_error_message(&error));
671 if (!dbus_message_iter_init(reply, &iter) ||
672 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
673 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
674 log_error("Failed to parse reply.");
679 dbus_message_iter_recurse(&iter, &sub);
681 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
684 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
685 log_error("Failed to parse reply.");
690 dbus_message_iter_recurse(&sub, &sub2);
692 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
693 log_error("Failed to parse reply.");
698 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
699 log_error("Failed to parse reply.");
704 dbus_message_iter_recurse(&sub2, &sub3);
706 if (dot_one_property(name, prop, &sub3)) {
707 log_error("Failed to parse reply.");
712 dbus_message_iter_next(&sub);
719 dbus_message_unref(m);
722 dbus_message_unref(reply);
724 dbus_error_free(&error);
729 static int dot(DBusConnection *bus, char **args, unsigned n) {
730 DBusMessage *m = NULL, *reply = NULL;
733 DBusMessageIter iter, sub, sub2;
735 dbus_error_init(&error);
739 if (!(m = dbus_message_new_method_call(
740 "org.freedesktop.systemd1",
741 "/org/freedesktop/systemd1",
742 "org.freedesktop.systemd1.Manager",
744 log_error("Could not allocate message.");
748 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
749 log_error("Failed to issue method call: %s", bus_error_message(&error));
754 if (!dbus_message_iter_init(reply, &iter) ||
755 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
756 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
757 log_error("Failed to parse reply.");
762 printf("digraph systemd {\n");
764 dbus_message_iter_recurse(&iter, &sub);
765 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
766 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
768 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
769 log_error("Failed to parse reply.");
774 dbus_message_iter_recurse(&sub, &sub2);
776 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
777 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
778 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
779 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
780 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
781 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
782 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
783 log_error("Failed to parse reply.");
788 if ((r = dot_one(bus, id, unit_path)) < 0)
791 /* printf("\t\"%s\";\n", id); */
792 dbus_message_iter_next(&sub);
797 log_info(" Color legend: black = Requires\n"
798 " dark blue = Requisite\n"
799 " dark grey = Wants\n"
803 if (isatty(fileno(stdout)))
804 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
805 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
811 dbus_message_unref(m);
814 dbus_message_unref(reply);
816 dbus_error_free(&error);
821 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
822 DBusMessage *m = NULL, *reply = NULL;
825 DBusMessageIter iter, sub, sub2;
828 dbus_error_init(&error);
832 pager_open_if_enabled();
834 if (!(m = dbus_message_new_method_call(
835 "org.freedesktop.systemd1",
836 "/org/freedesktop/systemd1",
837 "org.freedesktop.systemd1.Manager",
839 log_error("Could not allocate message.");
843 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
844 log_error("Failed to issue method call: %s", bus_error_message(&error));
849 if (!dbus_message_iter_init(reply, &iter) ||
850 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
851 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
852 log_error("Failed to parse reply.");
857 dbus_message_iter_recurse(&iter, &sub);
859 if (isatty(STDOUT_FILENO))
860 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
862 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
863 const char *name, *type, *state, *job_path, *unit_path;
867 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
868 log_error("Failed to parse reply.");
873 dbus_message_iter_recurse(&sub, &sub2);
875 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
876 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
877 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
878 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
879 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
880 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
881 log_error("Failed to parse reply.");
886 e = arg_full ? NULL : ellipsize(name, 25, 33);
887 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
892 dbus_message_iter_next(&sub);
895 if (isatty(STDOUT_FILENO))
896 printf("\n%u jobs listed.\n", k);
902 dbus_message_unref(m);
905 dbus_message_unref(reply);
907 dbus_error_free(&error);
912 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
913 DBusMessage *m = NULL, *reply = NULL;
918 dbus_error_init(&error);
923 for (i = 1; i < n; i++) {
925 if (!(m = dbus_message_new_method_call(
926 "org.freedesktop.systemd1",
927 "/org/freedesktop/systemd1",
928 "org.freedesktop.systemd1.Manager",
930 log_error("Could not allocate message.");
935 if (!dbus_message_append_args(m,
936 DBUS_TYPE_STRING, &args[i],
937 DBUS_TYPE_INVALID)) {
938 log_error("Could not append arguments to message.");
943 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
944 log_error("Failed to issue method call: %s", bus_error_message(&error));
949 dbus_message_unref(m);
950 dbus_message_unref(reply);
959 dbus_message_unref(m);
962 dbus_message_unref(reply);
964 dbus_error_free(&error);
969 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
970 DBusMessage *m = NULL, *reply = NULL;
975 dbus_error_init(&error);
981 return daemon_reload(bus, args, n);
983 for (i = 1; i < n; i++) {
987 if (!(m = dbus_message_new_method_call(
988 "org.freedesktop.systemd1",
989 "/org/freedesktop/systemd1",
990 "org.freedesktop.systemd1.Manager",
992 log_error("Could not allocate message.");
997 if ((r = safe_atou(args[i], &id)) < 0) {
998 log_error("Failed to parse job id: %s", strerror(-r));
1002 assert_cc(sizeof(uint32_t) == sizeof(id));
1003 if (!dbus_message_append_args(m,
1004 DBUS_TYPE_UINT32, &id,
1005 DBUS_TYPE_INVALID)) {
1006 log_error("Could not append arguments to message.");
1011 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1012 log_error("Failed to issue method call: %s", bus_error_message(&error));
1017 if (!dbus_message_get_args(reply, &error,
1018 DBUS_TYPE_OBJECT_PATH, &path,
1019 DBUS_TYPE_INVALID)) {
1020 log_error("Failed to parse reply: %s", bus_error_message(&error));
1025 dbus_message_unref(m);
1026 if (!(m = dbus_message_new_method_call(
1027 "org.freedesktop.systemd1",
1029 "org.freedesktop.systemd1.Job",
1031 log_error("Could not allocate message.");
1036 dbus_message_unref(reply);
1037 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1038 log_error("Failed to issue method call: %s", bus_error_message(&error));
1043 dbus_message_unref(m);
1044 dbus_message_unref(reply);
1052 dbus_message_unref(m);
1055 dbus_message_unref(reply);
1057 dbus_error_free(&error);
1062 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1063 DBusMessage *m = NULL, *reply = NULL;
1064 dbus_bool_t b = FALSE;
1065 DBusMessageIter iter, sub;
1067 *interface = "org.freedesktop.systemd1.Unit",
1068 *property = "NeedDaemonReload",
1071 /* We ignore all errors here, since this is used to show a warning only */
1073 if (!(m = dbus_message_new_method_call(
1074 "org.freedesktop.systemd1",
1075 "/org/freedesktop/systemd1",
1076 "org.freedesktop.systemd1.Manager",
1080 if (!dbus_message_append_args(m,
1081 DBUS_TYPE_STRING, &unit,
1085 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1088 if (!dbus_message_get_args(reply, NULL,
1089 DBUS_TYPE_OBJECT_PATH, &path,
1093 dbus_message_unref(m);
1094 if (!(m = dbus_message_new_method_call(
1095 "org.freedesktop.systemd1",
1097 "org.freedesktop.DBus.Properties",
1101 if (!dbus_message_append_args(m,
1102 DBUS_TYPE_STRING, &interface,
1103 DBUS_TYPE_STRING, &property,
1104 DBUS_TYPE_INVALID)) {
1108 dbus_message_unref(reply);
1109 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1112 if (!dbus_message_iter_init(reply, &iter) ||
1113 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1116 dbus_message_iter_recurse(&iter, &sub);
1118 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1121 dbus_message_iter_get_basic(&sub, &b);
1125 dbus_message_unref(m);
1128 dbus_message_unref(reply);
1133 typedef struct WaitData {
1138 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1146 dbus_error_init(&error);
1148 log_debug("Got D-Bus request: %s.%s() on %s",
1149 dbus_message_get_interface(message),
1150 dbus_message_get_member(message),
1151 dbus_message_get_path(message));
1153 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1154 log_error("Warning! D-Bus connection terminated.");
1155 dbus_connection_close(connection);
1157 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1159 const char *path, *result;
1160 dbus_bool_t success = true;
1162 if (dbus_message_get_args(message, &error,
1163 DBUS_TYPE_UINT32, &id,
1164 DBUS_TYPE_OBJECT_PATH, &path,
1165 DBUS_TYPE_STRING, &result,
1166 DBUS_TYPE_INVALID)) {
1169 if ((p = set_remove(d->set, (char*) path)))
1173 d->result = strdup(result);
1178 dbus_error_free(&error);
1180 if (dbus_message_get_args(message, &error,
1181 DBUS_TYPE_UINT32, &id,
1182 DBUS_TYPE_OBJECT_PATH, &path,
1183 DBUS_TYPE_BOOLEAN, &success,
1184 DBUS_TYPE_INVALID)) {
1187 /* Compatibility with older systemd versions <
1188 * 19 during upgrades. This should be dropped
1191 if ((p = set_remove(d->set, (char*) path)))
1195 d->result = strdup("failed");
1201 log_error("Failed to parse message: %s", bus_error_message(&error));
1205 dbus_error_free(&error);
1206 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1209 static int enable_wait_for_jobs(DBusConnection *bus) {
1217 dbus_error_init(&error);
1218 dbus_bus_add_match(bus,
1220 "sender='org.freedesktop.systemd1',"
1221 "interface='org.freedesktop.systemd1.Manager',"
1222 "member='JobRemoved',"
1223 "path='/org/freedesktop/systemd1'",
1226 if (dbus_error_is_set(&error)) {
1227 log_error("Failed to add match: %s", bus_error_message(&error));
1228 dbus_error_free(&error);
1232 /* This is slightly dirty, since we don't undo the match registrations. */
1236 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1246 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1247 log_error("Failed to add filter.");
1252 while (!set_isempty(s) &&
1253 dbus_connection_read_write_dispatch(bus, -1))
1256 if (!arg_quiet && d.result) {
1257 if (streq(d.result, "timeout"))
1258 log_error("Job timed out.");
1259 else if (streq(d.result, "canceled"))
1260 log_error("Job canceled.");
1261 else if (streq(d.result, "dependency"))
1262 log_error("A dependency job failed. See system logs for details.");
1263 else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
1264 log_error("Job failed. See system logs and 'systemctl status' for details.");
1267 if (streq_ptr(d.result, "timeout"))
1269 else if (streq_ptr(d.result, "canceled"))
1271 else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
1279 /* This is slightly dirty, since we don't undo the filter registration. */
1284 static int start_unit_one(
1285 DBusConnection *bus,
1292 DBusMessage *m = NULL, *reply = NULL;
1301 assert(arg_no_block || s);
1303 if (!(m = dbus_message_new_method_call(
1304 "org.freedesktop.systemd1",
1305 "/org/freedesktop/systemd1",
1306 "org.freedesktop.systemd1.Manager",
1308 log_error("Could not allocate message.");
1313 if (!dbus_message_append_args(m,
1314 DBUS_TYPE_STRING, &name,
1315 DBUS_TYPE_STRING, &mode,
1316 DBUS_TYPE_INVALID)) {
1317 log_error("Could not append arguments to message.");
1322 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1324 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1325 /* There's always a fallback possible for
1326 * legacy actions. */
1331 log_error("Failed to issue method call: %s", bus_error_message(error));
1336 if (!dbus_message_get_args(reply, error,
1337 DBUS_TYPE_OBJECT_PATH, &path,
1338 DBUS_TYPE_INVALID)) {
1339 log_error("Failed to parse reply: %s", bus_error_message(error));
1344 if (need_daemon_reload(bus, name))
1345 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1346 arg_user ? "--user" : "--system");
1348 if (!arg_no_block) {
1351 if (!(p = strdup(path))) {
1352 log_error("Failed to duplicate path.");
1357 if ((r = set_put(s, p)) < 0) {
1359 log_error("Failed to add path to set.");
1368 dbus_message_unref(m);
1371 dbus_message_unref(reply);
1376 static enum action verb_to_action(const char *verb) {
1377 if (streq(verb, "halt"))
1379 else if (streq(verb, "poweroff"))
1380 return ACTION_POWEROFF;
1381 else if (streq(verb, "reboot"))
1382 return ACTION_REBOOT;
1383 else if (streq(verb, "kexec"))
1384 return ACTION_KEXEC;
1385 else if (streq(verb, "rescue"))
1386 return ACTION_RESCUE;
1387 else if (streq(verb, "emergency"))
1388 return ACTION_EMERGENCY;
1389 else if (streq(verb, "default"))
1390 return ACTION_DEFAULT;
1391 else if (streq(verb, "exit"))
1394 return ACTION_INVALID;
1397 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1399 static const char * const table[_ACTION_MAX] = {
1400 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1401 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1402 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1403 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1404 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1405 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1406 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1407 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1408 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1409 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1410 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1411 [ACTION_EXIT] = SPECIAL_EXIT_TARGET
1416 const char *method, *mode, *one_name;
1420 dbus_error_init(&error);
1424 spawn_ask_password_agent();
1426 if (arg_action == ACTION_SYSTEMCTL) {
1428 streq(args[0], "stop") ||
1429 streq(args[0], "condstop") ? "StopUnit" :
1430 streq(args[0], "reload") ? "ReloadUnit" :
1431 streq(args[0], "restart") ? "RestartUnit" :
1433 streq(args[0], "try-restart") ||
1434 streq(args[0], "condrestart") ? "TryRestartUnit" :
1436 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1438 streq(args[0], "reload-or-try-restart") ||
1439 streq(args[0], "condreload") ||
1441 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1445 (streq(args[0], "isolate") ||
1446 streq(args[0], "rescue") ||
1447 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1449 one_name = table[verb_to_action(args[0])];
1452 assert(arg_action < ELEMENTSOF(table));
1453 assert(table[arg_action]);
1455 method = "StartUnit";
1457 mode = (arg_action == ACTION_EMERGENCY ||
1458 arg_action == ACTION_RESCUE ||
1459 arg_action == ACTION_RUNLEVEL2 ||
1460 arg_action == ACTION_RUNLEVEL3 ||
1461 arg_action == ACTION_RUNLEVEL4 ||
1462 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1464 one_name = table[arg_action];
1467 if (!arg_no_block) {
1468 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1469 log_error("Could not watch jobs: %s", strerror(-ret));
1473 if (!(s = set_new(string_hash_func, string_compare_func))) {
1474 log_error("Failed to allocate set.");
1481 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1484 for (i = 1; i < n; i++)
1485 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1486 ret = translate_bus_error_to_exit_status(r, &error);
1487 dbus_error_free(&error);
1492 if ((r = wait_for_jobs(bus, s)) < 0) {
1501 dbus_error_free(&error);
1506 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1513 (streq(args[0], "halt") ||
1514 streq(args[0], "poweroff") ||
1515 streq(args[0], "reboot") ||
1516 streq(args[0], "kexec") ||
1517 streq(args[0], "exit")))
1518 return daemon_reload(bus, args, n);
1520 r = start_unit(bus, args, n);
1523 warn_wall(verb_to_action(args[0]));
1528 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1529 DBusMessage *m = NULL, *reply = NULL;
1531 *interface = "org.freedesktop.systemd1.Unit",
1532 *property = "ActiveState";
1533 int r = 3; /* According to LSB: "program is not running" */
1540 dbus_error_init(&error);
1542 for (i = 1; i < n; i++) {
1543 const char *path = NULL;
1545 DBusMessageIter iter, sub;
1547 if (!(m = dbus_message_new_method_call(
1548 "org.freedesktop.systemd1",
1549 "/org/freedesktop/systemd1",
1550 "org.freedesktop.systemd1.Manager",
1552 log_error("Could not allocate message.");
1557 if (!dbus_message_append_args(m,
1558 DBUS_TYPE_STRING, &args[i],
1559 DBUS_TYPE_INVALID)) {
1560 log_error("Could not append arguments to message.");
1565 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1567 /* Hmm, cannot figure out anything about this unit... */
1571 dbus_error_free(&error);
1572 dbus_message_unref(m);
1577 if (!dbus_message_get_args(reply, &error,
1578 DBUS_TYPE_OBJECT_PATH, &path,
1579 DBUS_TYPE_INVALID)) {
1580 log_error("Failed to parse reply: %s", bus_error_message(&error));
1585 dbus_message_unref(m);
1586 if (!(m = dbus_message_new_method_call(
1587 "org.freedesktop.systemd1",
1589 "org.freedesktop.DBus.Properties",
1591 log_error("Could not allocate message.");
1596 if (!dbus_message_append_args(m,
1597 DBUS_TYPE_STRING, &interface,
1598 DBUS_TYPE_STRING, &property,
1599 DBUS_TYPE_INVALID)) {
1600 log_error("Could not append arguments to message.");
1605 dbus_message_unref(reply);
1606 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1607 log_error("Failed to issue method call: %s", bus_error_message(&error));
1612 if (!dbus_message_iter_init(reply, &iter) ||
1613 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1614 log_error("Failed to parse reply.");
1619 dbus_message_iter_recurse(&iter, &sub);
1621 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1622 log_error("Failed to parse reply.");
1627 dbus_message_iter_get_basic(&sub, &state);
1632 if (streq(state, "active") || streq(state, "reloading"))
1635 dbus_message_unref(m);
1636 dbus_message_unref(reply);
1642 dbus_message_unref(m);
1645 dbus_message_unref(reply);
1647 dbus_error_free(&error);
1652 static int kill_unit(DBusConnection *bus, char **args, unsigned n) {
1653 DBusMessage *m = NULL, *reply = NULL;
1661 dbus_error_init(&error);
1664 arg_kill_who = "all";
1667 arg_kill_mode = streq(arg_kill_who, "all") ? "control-group" : "process";
1669 for (i = 1; i < n; i++) {
1671 if (!(m = dbus_message_new_method_call(
1672 "org.freedesktop.systemd1",
1673 "/org/freedesktop/systemd1",
1674 "org.freedesktop.systemd1.Manager",
1676 log_error("Could not allocate message.");
1681 if (!dbus_message_append_args(m,
1682 DBUS_TYPE_STRING, &args[i],
1683 DBUS_TYPE_STRING, &arg_kill_who,
1684 DBUS_TYPE_STRING, &arg_kill_mode,
1685 DBUS_TYPE_INT32, &arg_signal,
1686 DBUS_TYPE_INVALID)) {
1687 log_error("Could not append arguments to message.");
1692 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1693 log_error("Failed to issue method call: %s", bus_error_message(&error));
1694 dbus_error_free(&error);
1698 dbus_message_unref(m);
1701 dbus_message_unref(reply);
1707 dbus_message_unref(m);
1710 dbus_message_unref(reply);
1712 dbus_error_free(&error);
1717 typedef struct ExecStatusInfo {
1725 usec_t start_timestamp;
1726 usec_t exit_timestamp;
1731 LIST_FIELDS(struct ExecStatusInfo, exec);
1734 static void exec_status_info_free(ExecStatusInfo *i) {
1743 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1744 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
1745 DBusMessageIter sub2, sub3;
1749 int32_t code, status;
1755 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1758 dbus_message_iter_recurse(sub, &sub2);
1760 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1763 if (!(i->path = strdup(path)))
1766 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1767 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1771 dbus_message_iter_recurse(&sub2, &sub3);
1772 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1773 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1774 dbus_message_iter_next(&sub3);
1779 if (!(i->argv = new0(char*, n+1)))
1783 dbus_message_iter_recurse(&sub2, &sub3);
1784 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1787 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1788 dbus_message_iter_get_basic(&sub3, &s);
1789 dbus_message_iter_next(&sub3);
1791 if (!(i->argv[n++] = strdup(s)))
1795 if (!dbus_message_iter_next(&sub2) ||
1796 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1797 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1798 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
1799 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1800 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
1801 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1802 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1803 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1807 i->start_timestamp = (usec_t) start_timestamp;
1808 i->exit_timestamp = (usec_t) exit_timestamp;
1809 i->pid = (pid_t) pid;
1816 typedef struct UnitStatusInfo {
1818 const char *load_state;
1819 const char *active_state;
1820 const char *sub_state;
1822 const char *description;
1823 const char *following;
1826 const char *default_control_group;
1828 usec_t inactive_exit_timestamp;
1829 usec_t active_enter_timestamp;
1830 usec_t active_exit_timestamp;
1831 usec_t inactive_enter_timestamp;
1833 bool need_daemon_reload;
1838 const char *status_text;
1840 #ifdef HAVE_SYSV_COMPAT
1844 usec_t start_timestamp;
1845 usec_t exit_timestamp;
1847 int exit_code, exit_status;
1849 usec_t condition_timestamp;
1850 bool condition_result;
1853 unsigned n_accepted;
1854 unsigned n_connections;
1858 const char *sysfs_path;
1860 /* Mount, Automount */
1866 LIST_HEAD(ExecStatusInfo, exec);
1869 static void print_status_info(UnitStatusInfo *i) {
1871 const char *on, *off, *ss;
1873 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1874 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1878 /* This shows pretty information about a unit. See
1879 * print_property() for a low-level property printer */
1881 printf("%s", strna(i->id));
1883 if (i->description && !streq_ptr(i->id, i->description))
1884 printf(" - %s", i->description);
1889 printf("\t Follow: unit currently follows state of %s\n", i->following);
1891 if (streq_ptr(i->load_state, "failed") ||
1892 streq_ptr(i->load_state, "banned")) {
1893 on = ansi_highlight(true);
1894 off = ansi_highlight(false);
1899 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1901 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1903 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1905 if (streq_ptr(i->active_state, "failed")) {
1906 on = ansi_highlight(true);
1907 off = ansi_highlight(false);
1908 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1909 on = ansi_highlight_green(true);
1910 off = ansi_highlight_green(false);
1915 printf("\t Active: %s%s (%s)%s",
1917 strna(i->active_state),
1921 printf("\t Active: %s%s%s",
1923 strna(i->active_state),
1926 timestamp = (streq_ptr(i->active_state, "active") ||
1927 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1928 (streq_ptr(i->active_state, "inactive") ||
1929 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1930 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1931 i->active_exit_timestamp;
1933 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1934 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1937 printf(" since %s; %s\n", s2, s1);
1939 printf(" since %s\n", s2);
1943 if (!i->condition_result && i->condition_timestamp > 0) {
1944 s1 = format_timestamp_pretty(since1, sizeof(since1), i->condition_timestamp);
1945 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
1948 printf("\t start condition failed at %s; %s\n", s2, s1);
1950 printf("\t start condition failed at %s\n", s2);
1954 printf("\t Device: %s\n", i->sysfs_path);
1956 printf("\t Where: %s\n", i->where);
1958 printf("\t What: %s\n", i->what);
1961 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1963 LIST_FOREACH(exec, p, i->exec) {
1967 /* Only show exited processes here */
1971 t = strv_join(p->argv, " ");
1972 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
1975 #ifdef HAVE_SYSV_COMPAT
1977 good = is_clean_exit_lsb(p->code, p->status);
1980 good = is_clean_exit(p->code, p->status);
1983 on = ansi_highlight(true);
1984 off = ansi_highlight(false);
1988 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
1990 if (p->code == CLD_EXITED) {
1993 printf("status=%i", p->status);
1995 #ifdef HAVE_SYSV_COMPAT
1996 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1998 if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
2003 printf("signal=%s", signal_to_string(p->status));
2005 printf(")%s\n", off);
2009 if (i->main_pid == p->pid &&
2010 i->start_timestamp == p->start_timestamp &&
2011 i->exit_timestamp == p->start_timestamp)
2012 /* Let's not show this twice */
2015 if (p->pid == i->control_pid)
2019 if (i->main_pid > 0 || i->control_pid > 0) {
2022 if (i->main_pid > 0) {
2023 printf("Main PID: %u", (unsigned) i->main_pid);
2027 get_process_name(i->main_pid, &t);
2032 } else if (i->exit_code > 0) {
2033 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2035 if (i->exit_code == CLD_EXITED) {
2038 printf("status=%i", i->exit_status);
2040 #ifdef HAVE_SYSV_COMPAT
2041 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
2043 if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
2048 printf("signal=%s", signal_to_string(i->exit_status));
2053 if (i->main_pid > 0 && i->control_pid > 0)
2056 if (i->control_pid > 0) {
2059 printf(" Control: %u", (unsigned) i->control_pid);
2061 get_process_name(i->control_pid, &t);
2072 printf("\t Status: \"%s\"\n", i->status_text);
2074 if (i->default_control_group) {
2077 printf("\t CGroup: %s\n", i->default_control_group);
2079 if (arg_transport != TRANSPORT_SSH) {
2080 if ((c = columns()) > 18)
2085 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
2089 if (i->need_daemon_reload)
2090 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2091 ansi_highlight(true),
2092 ansi_highlight(false),
2093 arg_user ? "--user" : "--system");
2096 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2098 switch (dbus_message_iter_get_arg_type(iter)) {
2100 case DBUS_TYPE_STRING: {
2103 dbus_message_iter_get_basic(iter, &s);
2106 if (streq(name, "Id"))
2108 else if (streq(name, "LoadState"))
2110 else if (streq(name, "ActiveState"))
2111 i->active_state = s;
2112 else if (streq(name, "SubState"))
2114 else if (streq(name, "Description"))
2116 else if (streq(name, "FragmentPath"))
2118 #ifdef HAVE_SYSV_COMPAT
2119 else if (streq(name, "SysVPath")) {
2124 else if (streq(name, "DefaultControlGroup"))
2125 i->default_control_group = s;
2126 else if (streq(name, "StatusText"))
2128 else if (streq(name, "SysFSPath"))
2130 else if (streq(name, "Where"))
2132 else if (streq(name, "What"))
2134 else if (streq(name, "Following"))
2141 case DBUS_TYPE_BOOLEAN: {
2144 dbus_message_iter_get_basic(iter, &b);
2146 if (streq(name, "Accept"))
2148 else if (streq(name, "NeedDaemonReload"))
2149 i->need_daemon_reload = b;
2150 else if (streq(name, "ConditionResult"))
2151 i->condition_result = b;
2156 case DBUS_TYPE_UINT32: {
2159 dbus_message_iter_get_basic(iter, &u);
2161 if (streq(name, "MainPID")) {
2163 i->main_pid = (pid_t) u;
2166 } else if (streq(name, "ControlPID"))
2167 i->control_pid = (pid_t) u;
2168 else if (streq(name, "ExecMainPID")) {
2170 i->main_pid = (pid_t) u;
2171 } else if (streq(name, "NAccepted"))
2173 else if (streq(name, "NConnections"))
2174 i->n_connections = u;
2179 case DBUS_TYPE_INT32: {
2182 dbus_message_iter_get_basic(iter, &j);
2184 if (streq(name, "ExecMainCode"))
2185 i->exit_code = (int) j;
2186 else if (streq(name, "ExecMainStatus"))
2187 i->exit_status = (int) j;
2192 case DBUS_TYPE_UINT64: {
2195 dbus_message_iter_get_basic(iter, &u);
2197 if (streq(name, "ExecMainStartTimestamp"))
2198 i->start_timestamp = (usec_t) u;
2199 else if (streq(name, "ExecMainExitTimestamp"))
2200 i->exit_timestamp = (usec_t) u;
2201 else if (streq(name, "ActiveEnterTimestamp"))
2202 i->active_enter_timestamp = (usec_t) u;
2203 else if (streq(name, "InactiveEnterTimestamp"))
2204 i->inactive_enter_timestamp = (usec_t) u;
2205 else if (streq(name, "InactiveExitTimestamp"))
2206 i->inactive_exit_timestamp = (usec_t) u;
2207 else if (streq(name, "ActiveExitTimestamp"))
2208 i->active_exit_timestamp = (usec_t) u;
2209 else if (streq(name, "ConditionTimestamp"))
2210 i->condition_timestamp = (usec_t) u;
2215 case DBUS_TYPE_ARRAY: {
2217 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2218 startswith(name, "Exec")) {
2219 DBusMessageIter sub;
2221 dbus_message_iter_recurse(iter, &sub);
2222 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2223 ExecStatusInfo *info;
2226 if (!(info = new0(ExecStatusInfo, 1)))
2229 if (!(info->name = strdup(name))) {
2234 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2239 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2241 dbus_message_iter_next(&sub);
2252 static int print_property(const char *name, DBusMessageIter *iter) {
2256 /* This is a low-level property printer, see
2257 * print_status_info() for the nicer output */
2259 if (arg_property && !strv_find(arg_property, name))
2262 switch (dbus_message_iter_get_arg_type(iter)) {
2264 case DBUS_TYPE_STRING: {
2266 dbus_message_iter_get_basic(iter, &s);
2268 if (arg_all || s[0])
2269 printf("%s=%s\n", name, s);
2274 case DBUS_TYPE_BOOLEAN: {
2276 dbus_message_iter_get_basic(iter, &b);
2277 printf("%s=%s\n", name, yes_no(b));
2282 case DBUS_TYPE_UINT64: {
2284 dbus_message_iter_get_basic(iter, &u);
2286 /* Yes, heuristics! But we can change this check
2287 * should it turn out to not be sufficient */
2289 if (endswith(name, "Timestamp")) {
2290 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
2292 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
2293 printf("%s=%s\n", name, strempty(t));
2294 } else if (strstr(name, "USec")) {
2295 char timespan[FORMAT_TIMESPAN_MAX];
2297 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
2299 printf("%s=%llu\n", name, (unsigned long long) u);
2304 case DBUS_TYPE_UINT32: {
2306 dbus_message_iter_get_basic(iter, &u);
2308 if (strstr(name, "UMask") || strstr(name, "Mode"))
2309 printf("%s=%04o\n", name, u);
2311 printf("%s=%u\n", name, (unsigned) u);
2316 case DBUS_TYPE_INT32: {
2318 dbus_message_iter_get_basic(iter, &i);
2320 printf("%s=%i\n", name, (int) i);
2324 case DBUS_TYPE_DOUBLE: {
2326 dbus_message_iter_get_basic(iter, &d);
2328 printf("%s=%g\n", name, d);
2332 case DBUS_TYPE_STRUCT: {
2333 DBusMessageIter sub;
2334 dbus_message_iter_recurse(iter, &sub);
2336 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2339 dbus_message_iter_get_basic(&sub, &u);
2342 printf("%s=%u\n", name, (unsigned) u);
2344 printf("%s=\n", name);
2347 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2350 dbus_message_iter_get_basic(&sub, &s);
2352 if (arg_all || s[0])
2353 printf("%s=%s\n", name, s);
2361 case DBUS_TYPE_ARRAY:
2363 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2364 DBusMessageIter sub;
2367 dbus_message_iter_recurse(iter, &sub);
2369 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2370 printf("%s=", name);
2372 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2375 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2376 dbus_message_iter_get_basic(&sub, &s);
2377 printf("%s%s", space ? " " : "", s);
2380 dbus_message_iter_next(&sub);
2388 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2389 DBusMessageIter sub;
2391 dbus_message_iter_recurse(iter, &sub);
2393 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2394 printf("%s=", name);
2396 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2399 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2400 dbus_message_iter_get_basic(&sub, &u);
2403 dbus_message_iter_next(&sub);
2411 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
2412 DBusMessageIter sub, sub2;
2414 dbus_message_iter_recurse(iter, &sub);
2415 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2419 dbus_message_iter_recurse(&sub, &sub2);
2421 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
2422 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
2423 printf("EnvironmentFile=%s (ignore=%s)\n", path, yes_no(ignore));
2425 dbus_message_iter_next(&sub);
2430 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2431 DBusMessageIter sub, sub2;
2433 dbus_message_iter_recurse(iter, &sub);
2434 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2435 const char *type, *path;
2437 dbus_message_iter_recurse(&sub, &sub2);
2439 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2440 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2441 printf("%s=%s\n", type, path);
2443 dbus_message_iter_next(&sub);
2448 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2449 DBusMessageIter sub, sub2;
2451 dbus_message_iter_recurse(iter, &sub);
2452 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2454 uint64_t value, next_elapse;
2456 dbus_message_iter_recurse(&sub, &sub2);
2458 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2459 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2460 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2461 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2463 printf("%s={ value=%s ; next_elapse=%s }\n",
2465 format_timespan(timespan1, sizeof(timespan1), value),
2466 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2469 dbus_message_iter_next(&sub);
2474 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2475 DBusMessageIter sub;
2477 dbus_message_iter_recurse(iter, &sub);
2478 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2479 ExecStatusInfo info;
2482 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2483 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2486 t = strv_join(info.argv, " ");
2488 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2492 yes_no(info.ignore),
2493 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2494 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2495 (unsigned) info. pid,
2496 sigchld_code_to_string(info.code),
2498 info.code == CLD_EXITED ? "" : "/",
2499 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2505 strv_free(info.argv);
2507 dbus_message_iter_next(&sub);
2517 printf("%s=[unprintable]\n", name);
2522 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2523 DBusMessage *m = NULL, *reply = NULL;
2524 const char *interface = "";
2527 DBusMessageIter iter, sub, sub2, sub3;
2528 UnitStatusInfo info;
2536 dbus_error_init(&error);
2538 if (!(m = dbus_message_new_method_call(
2539 "org.freedesktop.systemd1",
2541 "org.freedesktop.DBus.Properties",
2543 log_error("Could not allocate message.");
2548 if (!dbus_message_append_args(m,
2549 DBUS_TYPE_STRING, &interface,
2550 DBUS_TYPE_INVALID)) {
2551 log_error("Could not append arguments to message.");
2556 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2557 log_error("Failed to issue method call: %s", bus_error_message(&error));
2562 if (!dbus_message_iter_init(reply, &iter) ||
2563 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2564 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2565 log_error("Failed to parse reply.");
2570 dbus_message_iter_recurse(&iter, &sub);
2577 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2580 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2581 log_error("Failed to parse reply.");
2586 dbus_message_iter_recurse(&sub, &sub2);
2588 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2589 log_error("Failed to parse reply.");
2594 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2595 log_error("Failed to parse reply.");
2600 dbus_message_iter_recurse(&sub2, &sub3);
2602 if (show_properties)
2603 r = print_property(name, &sub3);
2605 r = status_property(name, &sub3, &info);
2608 log_error("Failed to parse reply.");
2613 dbus_message_iter_next(&sub);
2618 if (!show_properties)
2619 print_status_info(&info);
2621 if (!streq_ptr(info.active_state, "active") &&
2622 !streq_ptr(info.active_state, "reloading") &&
2623 streq(verb, "status"))
2624 /* According to LSB: "program not running" */
2627 while ((p = info.exec)) {
2628 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2629 exec_status_info_free(p);
2634 dbus_message_unref(m);
2637 dbus_message_unref(reply);
2639 dbus_error_free(&error);
2644 static int show(DBusConnection *bus, char **args, unsigned n) {
2645 DBusMessage *m = NULL, *reply = NULL;
2649 bool show_properties, new_line = false;
2654 dbus_error_init(&error);
2656 show_properties = !streq(args[0], "status");
2658 if (show_properties)
2659 pager_open_if_enabled();
2661 if (show_properties && n <= 1) {
2662 /* If not argument is specified inspect the manager
2665 ret = show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2669 for (i = 1; i < n; i++) {
2670 const char *path = NULL;
2673 if (safe_atou32(args[i], &id) < 0) {
2675 /* Interpret as unit name */
2677 if (!(m = dbus_message_new_method_call(
2678 "org.freedesktop.systemd1",
2679 "/org/freedesktop/systemd1",
2680 "org.freedesktop.systemd1.Manager",
2682 log_error("Could not allocate message.");
2687 if (!dbus_message_append_args(m,
2688 DBUS_TYPE_STRING, &args[i],
2689 DBUS_TYPE_INVALID)) {
2690 log_error("Could not append arguments to message.");
2695 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2697 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2698 log_error("Failed to issue method call: %s", bus_error_message(&error));
2703 dbus_error_free(&error);
2705 dbus_message_unref(m);
2706 if (!(m = dbus_message_new_method_call(
2707 "org.freedesktop.systemd1",
2708 "/org/freedesktop/systemd1",
2709 "org.freedesktop.systemd1.Manager",
2711 log_error("Could not allocate message.");
2716 if (!dbus_message_append_args(m,
2717 DBUS_TYPE_STRING, &args[i],
2718 DBUS_TYPE_INVALID)) {
2719 log_error("Could not append arguments to message.");
2724 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2725 log_error("Failed to issue method call: %s", bus_error_message(&error));
2727 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2728 ret = 4; /* According to LSB: "program or service status is unknown" */
2735 } else if (show_properties) {
2737 /* Interpret as job id */
2739 if (!(m = dbus_message_new_method_call(
2740 "org.freedesktop.systemd1",
2741 "/org/freedesktop/systemd1",
2742 "org.freedesktop.systemd1.Manager",
2744 log_error("Could not allocate message.");
2749 if (!dbus_message_append_args(m,
2750 DBUS_TYPE_UINT32, &id,
2751 DBUS_TYPE_INVALID)) {
2752 log_error("Could not append arguments to message.");
2757 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2758 log_error("Failed to issue method call: %s", bus_error_message(&error));
2764 /* Interpret as PID */
2766 if (!(m = dbus_message_new_method_call(
2767 "org.freedesktop.systemd1",
2768 "/org/freedesktop/systemd1",
2769 "org.freedesktop.systemd1.Manager",
2771 log_error("Could not allocate message.");
2776 if (!dbus_message_append_args(m,
2777 DBUS_TYPE_UINT32, &id,
2778 DBUS_TYPE_INVALID)) {
2779 log_error("Could not append arguments to message.");
2784 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2785 log_error("Failed to issue method call: %s", bus_error_message(&error));
2791 if (!dbus_message_get_args(reply, &error,
2792 DBUS_TYPE_OBJECT_PATH, &path,
2793 DBUS_TYPE_INVALID)) {
2794 log_error("Failed to parse reply: %s", bus_error_message(&error));
2799 if ((r = show_one(args[0], bus, path, show_properties, &new_line)) != 0)
2802 dbus_message_unref(m);
2803 dbus_message_unref(reply);
2809 dbus_message_unref(m);
2812 dbus_message_unref(reply);
2814 dbus_error_free(&error);
2819 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2821 DBusMessage *m = NULL, *reply = NULL;
2826 dbus_error_init(&error);
2828 log_debug("Got D-Bus request: %s.%s() on %s",
2829 dbus_message_get_interface(message),
2830 dbus_message_get_member(message),
2831 dbus_message_get_path(message));
2833 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2834 log_error("Warning! D-Bus connection terminated.");
2835 dbus_connection_close(connection);
2837 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2838 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2839 const char *id, *path;
2841 if (!dbus_message_get_args(message, &error,
2842 DBUS_TYPE_STRING, &id,
2843 DBUS_TYPE_OBJECT_PATH, &path,
2845 log_error("Failed to parse message: %s", bus_error_message(&error));
2846 else if (streq(dbus_message_get_member(message), "UnitNew"))
2847 printf("Unit %s added.\n", id);
2849 printf("Unit %s removed.\n", id);
2851 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew")) {
2855 if (!dbus_message_get_args(message, &error,
2856 DBUS_TYPE_UINT32, &id,
2857 DBUS_TYPE_OBJECT_PATH, &path,
2859 log_error("Failed to parse message: %s", bus_error_message(&error));
2861 printf("Job %u added.\n", id);
2864 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2866 const char *path, *result;
2868 if (!dbus_message_get_args(message, &error,
2869 DBUS_TYPE_UINT32, &id,
2870 DBUS_TYPE_OBJECT_PATH, &path,
2871 DBUS_TYPE_STRING, &result,
2873 log_error("Failed to parse message: %s", bus_error_message(&error));
2875 printf("Job %u removed (result=%s).\n", id, result);
2878 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2880 const char *path, *interface, *property = "Id";
2881 DBusMessageIter iter, sub;
2883 path = dbus_message_get_path(message);
2885 if (!dbus_message_get_args(message, &error,
2886 DBUS_TYPE_STRING, &interface,
2887 DBUS_TYPE_INVALID)) {
2888 log_error("Failed to parse message: %s", bus_error_message(&error));
2892 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2893 !streq(interface, "org.freedesktop.systemd1.Unit"))
2896 if (!(m = dbus_message_new_method_call(
2897 "org.freedesktop.systemd1",
2899 "org.freedesktop.DBus.Properties",
2901 log_error("Could not allocate message.");
2905 if (!dbus_message_append_args(m,
2906 DBUS_TYPE_STRING, &interface,
2907 DBUS_TYPE_STRING, &property,
2908 DBUS_TYPE_INVALID)) {
2909 log_error("Could not append arguments to message.");
2913 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2914 log_error("Failed to issue method call: %s", bus_error_message(&error));
2918 if (!dbus_message_iter_init(reply, &iter) ||
2919 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2920 log_error("Failed to parse reply.");
2924 dbus_message_iter_recurse(&iter, &sub);
2926 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2929 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2930 log_error("Failed to parse reply.");
2934 dbus_message_iter_get_basic(&sub, &id);
2935 printf("Unit %s changed.\n", id);
2939 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2940 log_error("Failed to parse reply.");
2944 dbus_message_iter_get_basic(&sub, &id);
2945 printf("Job %u changed.\n", id);
2951 dbus_message_unref(m);
2954 dbus_message_unref(reply);
2956 dbus_error_free(&error);
2957 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2961 dbus_message_unref(m);
2964 dbus_message_unref(reply);
2966 dbus_error_free(&error);
2967 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2970 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2971 DBusMessage *m = NULL, *reply = NULL;
2975 dbus_error_init(&error);
2978 dbus_bus_add_match(bus,
2980 "sender='org.freedesktop.systemd1',"
2981 "interface='org.freedesktop.systemd1.Manager',"
2982 "path='/org/freedesktop/systemd1'",
2985 if (dbus_error_is_set(&error)) {
2986 log_error("Failed to add match: %s", bus_error_message(&error));
2991 dbus_bus_add_match(bus,
2993 "sender='org.freedesktop.systemd1',"
2994 "interface='org.freedesktop.DBus.Properties',"
2995 "member='PropertiesChanged'",
2998 if (dbus_error_is_set(&error)) {
2999 log_error("Failed to add match: %s", bus_error_message(&error));
3005 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
3006 log_error("Failed to add filter.");
3011 if (!(m = dbus_message_new_method_call(
3012 "org.freedesktop.systemd1",
3013 "/org/freedesktop/systemd1",
3014 "org.freedesktop.systemd1.Manager",
3016 log_error("Could not allocate message.");
3021 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3022 log_error("Failed to issue method call: %s", bus_error_message(&error));
3027 while (dbus_connection_read_write_dispatch(bus, -1))
3034 /* This is slightly dirty, since we don't undo the filter or the matches. */
3037 dbus_message_unref(m);
3040 dbus_message_unref(reply);
3042 dbus_error_free(&error);
3047 static int dump(DBusConnection *bus, char **args, unsigned n) {
3048 DBusMessage *m = NULL, *reply = NULL;
3053 dbus_error_init(&error);
3055 pager_open_if_enabled();
3057 if (!(m = dbus_message_new_method_call(
3058 "org.freedesktop.systemd1",
3059 "/org/freedesktop/systemd1",
3060 "org.freedesktop.systemd1.Manager",
3062 log_error("Could not allocate message.");
3066 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3067 log_error("Failed to issue method call: %s", bus_error_message(&error));
3072 if (!dbus_message_get_args(reply, &error,
3073 DBUS_TYPE_STRING, &text,
3074 DBUS_TYPE_INVALID)) {
3075 log_error("Failed to parse reply: %s", bus_error_message(&error));
3080 fputs(text, stdout);
3086 dbus_message_unref(m);
3089 dbus_message_unref(reply);
3091 dbus_error_free(&error);
3096 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
3097 DBusMessage *m = NULL, *reply = NULL;
3100 const char *name = "", *path, *id;
3101 dbus_bool_t cleanup = FALSE;
3102 DBusMessageIter iter, sub;
3104 *interface = "org.freedesktop.systemd1.Unit",
3107 dbus_error_init(&error);
3109 if (!(m = dbus_message_new_method_call(
3110 "org.freedesktop.systemd1",
3111 "/org/freedesktop/systemd1",
3112 "org.freedesktop.systemd1.Manager",
3113 "CreateSnapshot"))) {
3114 log_error("Could not allocate message.");
3121 if (!dbus_message_append_args(m,
3122 DBUS_TYPE_STRING, &name,
3123 DBUS_TYPE_BOOLEAN, &cleanup,
3124 DBUS_TYPE_INVALID)) {
3125 log_error("Could not append arguments to message.");
3130 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3131 log_error("Failed to issue method call: %s", bus_error_message(&error));
3136 if (!dbus_message_get_args(reply, &error,
3137 DBUS_TYPE_OBJECT_PATH, &path,
3138 DBUS_TYPE_INVALID)) {
3139 log_error("Failed to parse reply: %s", bus_error_message(&error));
3144 dbus_message_unref(m);
3145 if (!(m = dbus_message_new_method_call(
3146 "org.freedesktop.systemd1",
3148 "org.freedesktop.DBus.Properties",
3150 log_error("Could not allocate message.");
3154 if (!dbus_message_append_args(m,
3155 DBUS_TYPE_STRING, &interface,
3156 DBUS_TYPE_STRING, &property,
3157 DBUS_TYPE_INVALID)) {
3158 log_error("Could not append arguments to message.");
3163 dbus_message_unref(reply);
3164 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3165 log_error("Failed to issue method call: %s", bus_error_message(&error));
3170 if (!dbus_message_iter_init(reply, &iter) ||
3171 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3172 log_error("Failed to parse reply.");
3177 dbus_message_iter_recurse(&iter, &sub);
3179 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3180 log_error("Failed to parse reply.");
3185 dbus_message_iter_get_basic(&sub, &id);
3193 dbus_message_unref(m);
3196 dbus_message_unref(reply);
3198 dbus_error_free(&error);
3203 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
3204 DBusMessage *m = NULL, *reply = NULL;
3212 dbus_error_init(&error);
3214 for (i = 1; i < n; i++) {
3215 const char *path = NULL;
3217 if (!(m = dbus_message_new_method_call(
3218 "org.freedesktop.systemd1",
3219 "/org/freedesktop/systemd1",
3220 "org.freedesktop.systemd1.Manager",
3222 log_error("Could not allocate message.");
3227 if (!dbus_message_append_args(m,
3228 DBUS_TYPE_STRING, &args[i],
3229 DBUS_TYPE_INVALID)) {
3230 log_error("Could not append arguments to message.");
3235 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3236 log_error("Failed to issue method call: %s", bus_error_message(&error));
3241 if (!dbus_message_get_args(reply, &error,
3242 DBUS_TYPE_OBJECT_PATH, &path,
3243 DBUS_TYPE_INVALID)) {
3244 log_error("Failed to parse reply: %s", bus_error_message(&error));
3249 dbus_message_unref(m);
3250 if (!(m = dbus_message_new_method_call(
3251 "org.freedesktop.systemd1",
3253 "org.freedesktop.systemd1.Snapshot",
3255 log_error("Could not allocate message.");
3260 dbus_message_unref(reply);
3261 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3262 log_error("Failed to issue method call: %s", bus_error_message(&error));
3267 dbus_message_unref(m);
3268 dbus_message_unref(reply);
3276 dbus_message_unref(m);
3279 dbus_message_unref(reply);
3281 dbus_error_free(&error);
3286 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
3287 DBusMessage *m = NULL, *reply = NULL;
3292 dbus_error_init(&error);
3294 if (arg_action == ACTION_RELOAD)
3296 else if (arg_action == ACTION_REEXEC)
3297 method = "Reexecute";
3299 assert(arg_action == ACTION_SYSTEMCTL);
3302 streq(args[0], "clear-jobs") ||
3303 streq(args[0], "cancel") ? "ClearJobs" :
3304 streq(args[0], "daemon-reexec") ? "Reexecute" :
3305 streq(args[0], "reset-failed") ? "ResetFailed" :
3306 streq(args[0], "halt") ? "Halt" :
3307 streq(args[0], "poweroff") ? "PowerOff" :
3308 streq(args[0], "reboot") ? "Reboot" :
3309 streq(args[0], "kexec") ? "KExec" :
3310 streq(args[0], "exit") ? "Exit" :
3311 /* "daemon-reload" */ "Reload";
3314 if (!(m = dbus_message_new_method_call(
3315 "org.freedesktop.systemd1",
3316 "/org/freedesktop/systemd1",
3317 "org.freedesktop.systemd1.Manager",
3319 log_error("Could not allocate message.");
3323 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3325 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3326 /* There's always a fallback possible for
3327 * legacy actions. */
3332 if (streq(method, "Reexecute") && dbus_error_has_name(&error, DBUS_ERROR_NO_REPLY)) {
3333 /* On reexecution, we expect a disconnect, not
3339 log_error("Failed to issue method call: %s", bus_error_message(&error));
3348 dbus_message_unref(m);
3351 dbus_message_unref(reply);
3353 dbus_error_free(&error);
3358 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3359 DBusMessage *m = NULL, *reply = NULL;
3365 dbus_error_init(&error);
3368 return daemon_reload(bus, args, n);
3370 for (i = 1; i < n; i++) {
3372 if (!(m = dbus_message_new_method_call(
3373 "org.freedesktop.systemd1",
3374 "/org/freedesktop/systemd1",
3375 "org.freedesktop.systemd1.Manager",
3376 "ResetFailedUnit"))) {
3377 log_error("Could not allocate message.");
3382 if (!dbus_message_append_args(m,
3383 DBUS_TYPE_STRING, args + i,
3384 DBUS_TYPE_INVALID)) {
3385 log_error("Could not append arguments to message.");
3390 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3391 log_error("Failed to issue method call: %s", bus_error_message(&error));
3396 dbus_message_unref(m);
3397 dbus_message_unref(reply);
3405 dbus_message_unref(m);
3408 dbus_message_unref(reply);
3410 dbus_error_free(&error);
3415 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3416 DBusMessage *m = NULL, *reply = NULL;
3418 DBusMessageIter iter, sub, sub2;
3421 *interface = "org.freedesktop.systemd1.Manager",
3422 *property = "Environment";
3424 dbus_error_init(&error);
3426 pager_open_if_enabled();
3428 if (!(m = dbus_message_new_method_call(
3429 "org.freedesktop.systemd1",
3430 "/org/freedesktop/systemd1",
3431 "org.freedesktop.DBus.Properties",
3433 log_error("Could not allocate message.");
3437 if (!dbus_message_append_args(m,
3438 DBUS_TYPE_STRING, &interface,
3439 DBUS_TYPE_STRING, &property,
3440 DBUS_TYPE_INVALID)) {
3441 log_error("Could not append arguments to message.");
3446 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3447 log_error("Failed to issue method call: %s", bus_error_message(&error));
3452 if (!dbus_message_iter_init(reply, &iter) ||
3453 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3454 log_error("Failed to parse reply.");
3459 dbus_message_iter_recurse(&iter, &sub);
3461 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3462 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3463 log_error("Failed to parse reply.");
3468 dbus_message_iter_recurse(&sub, &sub2);
3470 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3473 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3474 log_error("Failed to parse reply.");
3479 dbus_message_iter_get_basic(&sub2, &text);
3480 printf("%s\n", text);
3482 dbus_message_iter_next(&sub2);
3489 dbus_message_unref(m);
3492 dbus_message_unref(reply);
3494 dbus_error_free(&error);
3499 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3500 DBusMessage *m = NULL, *reply = NULL;
3504 DBusMessageIter iter, sub;
3507 dbus_error_init(&error);
3509 method = streq(args[0], "set-environment")
3511 : "UnsetEnvironment";
3513 if (!(m = dbus_message_new_method_call(
3514 "org.freedesktop.systemd1",
3515 "/org/freedesktop/systemd1",
3516 "org.freedesktop.systemd1.Manager",
3519 log_error("Could not allocate message.");
3523 dbus_message_iter_init_append(m, &iter);
3525 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3526 log_error("Could not append arguments to message.");
3531 for (i = 1; i < n; i++)
3532 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3533 log_error("Could not append arguments to message.");
3538 if (!dbus_message_iter_close_container(&iter, &sub)) {
3539 log_error("Could not append arguments to message.");
3544 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3545 log_error("Failed to issue method call: %s", bus_error_message(&error));
3554 dbus_message_unref(m);
3557 dbus_message_unref(reply);
3559 dbus_error_free(&error);
3572 static Hashmap *will_install = NULL, *have_installed = NULL;
3573 static Set *remove_symlinks_to = NULL;
3574 static unsigned n_symlinks = 0;
3576 static void install_info_free(InstallInfo *i) {
3581 strv_free(i->aliases);
3582 strv_free(i->wanted_by);
3586 static void install_info_hashmap_free(Hashmap *m) {
3589 while ((i = hashmap_steal_first(m)))
3590 install_info_free(i);
3595 static int install_info_add(const char *name) {
3599 assert(will_install);
3601 if (!unit_name_is_valid_no_type(name, true)) {
3602 log_warning("Unit name %s is not a valid unit name.", name);
3606 if (hashmap_get(have_installed, name) ||
3607 hashmap_get(will_install, name))
3610 if (!(i = new0(InstallInfo, 1))) {
3615 if (!(i->name = strdup(name))) {
3620 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3627 install_info_free(i);
3632 static int config_parse_also(
3633 const char *filename,
3635 const char *section,
3650 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3654 if (!(n = strndup(w, l)))
3657 if ((r = install_info_add(n)) < 0) {
3658 log_warning("Cannot install unit %s: %s", n, strerror(-r));
3669 static int mark_symlink_for_removal(const char *p) {
3674 assert(path_is_absolute(p));
3676 if (!remove_symlinks_to)
3679 if (!(n = strdup(p)))
3682 path_kill_slashes(n);
3684 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3686 return r == -EEXIST ? 0 : r;
3692 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3701 if (!(d = fdopendir(fd))) {
3702 close_nointr_nofail(fd);
3708 while ((de = readdir(d))) {
3709 bool is_dir = false, is_link = false;
3711 if (ignore_file(de->d_name))
3714 if (de->d_type == DT_LNK)
3716 else if (de->d_type == DT_DIR)
3718 else if (de->d_type == DT_UNKNOWN) {
3721 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3722 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3729 is_link = S_ISLNK(st.st_mode);
3730 is_dir = S_ISDIR(st.st_mode);
3738 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3739 log_error("Failed to open %s/%s: %m", root, de->d_name);
3746 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3747 log_error("Failed to allocate directory string.");
3748 close_nointr_nofail(nfd);
3753 /* This will close nfd, regardless whether it succeeds or not */
3754 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3760 } else if (is_link) {
3764 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3765 log_error("Failed to allocate symlink string.");
3770 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3771 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3779 if ((c = canonicalize_file_name(dest))) {
3780 /* This might fail if the destination
3781 * is already removed */
3787 path_kill_slashes(dest);
3788 if (set_get(remove_symlinks_to, dest)) {
3791 log_info("rm '%s'", p);
3793 if (unlink(p) < 0) {
3794 log_error("Cannot unlink symlink %s: %m", p);
3799 rmdir_parents(p, config_path);
3800 path_kill_slashes(p);
3802 if (!set_get(remove_symlinks_to, p)) {
3804 if ((r = mark_symlink_for_removal(p)) < 0) {
3823 static int remove_marked_symlinks(const char *config_path) {
3827 assert(config_path);
3829 if (set_size(remove_symlinks_to) <= 0)
3832 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3839 if ((cfd = dup(fd)) < 0) {
3844 /* This takes possession of cfd and closes it */
3845 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3851 close_nointr_nofail(fd);
3856 static int create_symlink(const char *verb, const char *orig_old_path, const char *new_path) {
3858 const char *old_path;
3861 old_path = orig_old_path+strlen(arg_root);
3863 old_path = orig_old_path;
3869 if (streq(verb, "enable")) {
3872 mkdir_parents(new_path, 0755);
3874 if (symlink(old_path, new_path) >= 0) {
3877 log_info("ln -s '%s' '%s'", old_path, new_path);
3882 if (errno != EEXIST) {
3883 log_error("Cannot link %s to %s: %m", old_path, new_path);
3887 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3889 if (errno == EINVAL) {
3890 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3894 log_error("readlink() failed: %s", strerror(-r));
3898 if (streq(dest, old_path)) {
3904 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3913 log_info("ln -s '%s' '%s'", old_path, new_path);
3915 if (symlink(old_path, new_path) >= 0)
3918 log_error("Cannot link %s to %s: %m", old_path, new_path);
3921 } else if (streq(verb, "disable")) {
3924 if ((r = mark_symlink_for_removal(old_path)) < 0)
3927 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3928 if (errno == ENOENT)
3931 if (errno == EINVAL) {
3932 log_warning("File %s not a symlink, ignoring.", old_path);
3936 log_error("readlink() failed: %s", strerror(-r));
3940 if (!streq(dest, old_path)) {
3941 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3948 if ((r = mark_symlink_for_removal(new_path)) < 0)
3952 log_info("rm '%s'", new_path);
3954 if (unlink(new_path) >= 0)
3957 log_error("Cannot unlink %s: %m", new_path);
3960 } else if (streq(verb, "is-enabled")) {
3963 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3965 if (errno == ENOENT || errno == EINVAL)
3968 log_error("readlink() failed: %s", strerror(-r));
3972 if (streq(dest, old_path)) {
3981 assert_not_reached("Unknown action.");
3984 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3986 char *alias_path = NULL;
3991 assert(config_path);
3993 STRV_FOREACH(s, i->aliases) {
3996 if (!(alias_path = path_make_absolute(*s, config_path))) {
3997 log_error("Out of memory");
4002 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
4005 if (streq(verb, "disable"))
4006 rmdir_parents(alias_path, config_path);
4016 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
4018 char *alias_path = NULL;
4023 assert(config_path);
4025 STRV_FOREACH(s, i->wanted_by) {
4026 if (!unit_name_is_valid_no_type(*s, true)) {
4027 log_error("Invalid name %s.", *s);
4035 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
4036 log_error("Out of memory");
4041 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
4044 if (streq(verb, "disable"))
4045 rmdir_parents(alias_path, config_path);
4056 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
4058 const ConfigItem items[] = {
4059 { "Alias", config_parse_strv, 0, &i->aliases, "Install" },
4060 { "WantedBy", config_parse_strv, 0, &i->wanted_by, "Install" },
4061 { "Also", config_parse_also, 0, NULL, "Install" },
4063 { NULL, NULL, 0, NULL, NULL }
4067 char *filename = NULL;
4074 STRV_FOREACH(p, paths->unit_path) {
4076 char *path, *should_free;
4079 should_free = path = strappend(arg_root, *p);
4085 if (!(filename = path_make_absolute(i->name, path))) {
4086 log_error("Out of memory");
4093 /* Ensure that we don't follow symlinks */
4094 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
4095 if ((f = fdopen(fd, "re")))
4098 if (errno == ELOOP) {
4099 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
4104 if (errno != ENOENT) {
4105 log_error("Failed to open %s: %m", filename);
4115 #if (defined(TARGET_FEDORA) || defined(TARGET_MANDRIVA) || defined(TARGET_SUSE) || defined(TARGET_MEEGO) || defined(TARGET_ALTLINUX)) && defined (HAVE_SYSV_COMPAT)
4117 if (endswith(i->name, ".service")) {
4121 if (asprintf(&sysv, SYSTEM_SYSVINIT_PATH "/%s", i->name) < 0) {
4122 log_error("Out of memory");
4126 sysv[strlen(sysv) - sizeof(".service") + 1] = 0;
4130 tmp_path = strappend (arg_root, sysv);
4131 exists = access (tmp_path, F_OK) >= 0;
4134 exists = access(sysv, F_OK) >= 0;
4140 const char *argv[] = {
4148 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", i->name);
4150 argv[1] = file_name_from_path(sysv);
4152 streq(verb, "enable") ? "on" :
4153 streq(verb, "disable") ? "off" : "--level=5";
4155 argv[3] = strappend("--root=", arg_root);
4157 log_info("Executing %s %s %s %s", argv[0], argv[1], strempty(argv[2]), strempty(argv[3]));
4159 if ((pid = fork()) < 0) {
4160 log_error("Failed to fork: %m");
4163 } else if (pid == 0) {
4164 execv(argv[0], (char**) argv);
4165 _exit(EXIT_FAILURE);
4170 if ((r = wait_for_terminate(pid, &status)) < 0)
4173 if (status.si_code == CLD_EXITED) {
4175 if (streq(verb, "is-enabled"))
4176 return status.si_status == 0 ? 1 : 0;
4178 if (status.si_status == 0)
4181 return status.si_status == 0 ? 0 : -EINVAL;
4192 log_error("Couldn't find %s.", i->name);
4198 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
4203 /* Consider unit files stored in /lib and /usr always enabled
4204 * if they have no [Install] data. */
4205 if (streq(verb, "is-enabled") &&
4206 strv_isempty(i->aliases) &&
4207 strv_isempty(i->wanted_by) &&
4208 !path_startswith(filename, "/etc")) {
4213 n_symlinks += strv_length(i->aliases);
4214 n_symlinks += strv_length(i->wanted_by);
4218 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
4221 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
4224 if ((r = mark_symlink_for_removal(filename)) < 0)
4227 if ((r = remove_marked_symlinks(config_path)) < 0)
4233 static char *get_config_path(void) {
4236 if (arg_user && arg_global)
4237 ret = strdup(USER_CONFIG_UNIT_PATH);
4240 if (user_config_home(&ret) < 0)
4244 ret = strdup(SYSTEM_CONFIG_UNIT_PATH);
4247 p = strappend (arg_root, ret);
4254 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
4258 char *config_path = NULL;
4261 const char *verb = args[0];
4263 dbus_error_init(&error);
4266 if ((r = lookup_paths_init(&paths, arg_user ? MANAGER_USER : MANAGER_SYSTEM)) < 0) {
4267 log_error("Failed to determine lookup paths: %s", strerror(-r));
4271 if (!(config_path = get_config_path())) {
4272 log_error("Failed to determine config path");
4277 will_install = hashmap_new(string_hash_func, string_compare_func);
4278 have_installed = hashmap_new(string_hash_func, string_compare_func);
4280 if (!will_install || !have_installed) {
4281 log_error("Failed to allocate unit sets.");
4286 if (!arg_defaults && streq(verb, "disable"))
4287 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
4288 log_error("Failed to allocate symlink sets.");
4293 for (j = 1; j < n; j++)
4294 if ((r = install_info_add(args[j])) < 0) {
4295 log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
4301 while ((i = hashmap_first(will_install))) {
4304 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
4306 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
4314 /* In test mode and found something */
4320 if (streq(verb, "is-enabled"))
4321 r = r > 0 ? 0 : -ENOENT;
4323 if (n_symlinks <= 0)
4324 log_warning("Unit files contain no applicable installation information. Ignoring.");
4327 /* Don't try to reload anything if the user asked us to not do this */
4329 /* Don't try to reload anything when updating a unit globally */
4331 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
4332 (arg_user || sd_booted() > 0) &&
4333 /* Don't try to reload anything if we are running in a chroot environment */
4334 (arg_user || running_in_chroot() <= 0 || arg_root) ) {
4337 if ((q = daemon_reload(bus, args, n)) < 0)
4343 install_info_hashmap_free(will_install);
4344 install_info_hashmap_free(have_installed);
4346 set_free_free(remove_symlinks_to);
4348 lookup_paths_free(&paths);
4355 static int systemctl_help(void) {
4357 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4358 "Send control commands to or query the systemd manager.\n\n"
4359 " -h --help Show this help\n"
4360 " --version Show package version\n"
4361 " -t --type=TYPE List only units of a particular type\n"
4362 " -p --property=NAME Show only properties by this name\n"
4363 " -a --all Show all units/properties, including dead/empty ones\n"
4364 " --failed Show only failed units\n"
4365 " --full Don't ellipsize unit names on output\n"
4366 " --fail When queueing a new job, fail if conflicting jobs are\n"
4368 " --ignore-dependencies\n"
4369 " When queueing a new job, ignore all its dependencies\n"
4370 " --kill-mode=MODE How to send signal\n"
4371 " --kill-who=WHO Who to send signal to\n"
4372 " -s --signal=SIGNAL Which signal to send\n"
4373 " -H --host=[user@]host\n"
4374 " Show information for remote host\n"
4375 " -P --privileged Acquire privileges before execution\n"
4376 " -q --quiet Suppress output\n"
4377 " --no-block Do not wait until operation finished\n"
4378 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4379 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4381 " --no-pager Do not pipe output into a pager.\n"
4382 " --no-ask-password\n"
4383 " Do not ask for system passwords\n"
4384 " --order When generating graph for dot, show only order\n"
4385 " --require When generating graph for dot, show only requirement\n"
4386 " --root=path Use <root> as the root file system\n"
4387 " --system Connect to system manager\n"
4388 " --user Connect to user service manager\n"
4389 " --global Enable/disable unit files globally\n"
4390 " -f --force When enabling unit files, override existing symlinks\n"
4391 " When shutting down, execute action immediately\n"
4392 " --defaults When disabling unit files, remove default symlinks only\n\n"
4394 " list-units List units\n"
4395 " start [NAME...] Start (activate) one or more units\n"
4396 " stop [NAME...] Stop (deactivate) one or more units\n"
4397 " reload [NAME...] Reload one or more units\n"
4398 " restart [NAME...] Start or restart one or more units\n"
4399 " try-restart [NAME...] Restart one or more units if active\n"
4400 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4401 " otherwise start or restart\n"
4402 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4403 " otherwise restart if active\n"
4404 " isolate [NAME] Start one unit and stop all others\n"
4405 " kill [NAME...] Send signal to processes of a unit\n"
4406 " is-active [NAME...] Check whether units are active\n"
4407 " status [NAME...|PID...] Show runtime status of one or more units\n"
4408 " show [NAME...|JOB...] Show properties of one or more\n"
4409 " units/jobs or the manager\n"
4410 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4412 " enable [NAME...] Enable one or more unit files\n"
4413 " disable [NAME...] Disable one or more unit files\n"
4414 " is-enabled [NAME...] Check whether unit files are enabled\n"
4415 " load [NAME...] Load one or more units\n"
4416 " list-jobs List jobs\n"
4417 " cancel [JOB...] Cancel all, one, or more jobs\n"
4418 " monitor Monitor unit/job changes\n"
4419 " dump Dump server status\n"
4420 " dot Dump dependency graph for dot(1)\n"
4421 " snapshot [NAME] Create a snapshot\n"
4422 " delete [NAME...] Remove one or more snapshots\n"
4423 " daemon-reload Reload systemd manager configuration\n"
4424 " daemon-reexec Reexecute systemd manager\n"
4425 " show-environment Dump environment\n"
4426 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4427 " unset-environment [NAME...] Unset one or more environment variables\n"
4428 " default Enter system default mode\n"
4429 " rescue Enter system rescue mode\n"
4430 " emergency Enter system emergency mode\n"
4431 " halt Shut down and halt the system\n"
4432 " poweroff Shut down and power-off the system\n"
4433 " reboot Shut down and reboot the system\n"
4434 " kexec Shut down and reboot the system with kexec\n"
4435 " exit Ask for user instance termination\n",
4436 program_invocation_short_name);
4441 static int halt_help(void) {
4443 printf("%s [OPTIONS...]\n\n"
4444 "%s the system.\n\n"
4445 " --help Show this help\n"
4446 " --halt Halt the machine\n"
4447 " -p --poweroff Switch off the machine\n"
4448 " --reboot Reboot the machine\n"
4449 " -f --force Force immediate halt/power-off/reboot\n"
4450 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4451 " -d --no-wtmp Don't write wtmp record\n"
4452 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4453 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4454 program_invocation_short_name,
4455 arg_action == ACTION_REBOOT ? "Reboot" :
4456 arg_action == ACTION_POWEROFF ? "Power off" :
4462 static int shutdown_help(void) {
4464 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4465 "Shut down the system.\n\n"
4466 " --help Show this help\n"
4467 " -H --halt Halt the machine\n"
4468 " -P --poweroff Power-off the machine\n"
4469 " -r --reboot Reboot the machine\n"
4470 " -h Equivalent to --poweroff, overriden by --halt\n"
4471 " -k Don't halt/power-off/reboot, just send warnings\n"
4472 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4473 " -c Cancel a pending shutdown\n",
4474 program_invocation_short_name);
4479 static int telinit_help(void) {
4481 printf("%s [OPTIONS...] {COMMAND}\n\n"
4482 "Send control commands to the init daemon.\n\n"
4483 " --help Show this help\n"
4484 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4486 " 0 Power-off the machine\n"
4487 " 6 Reboot the machine\n"
4488 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4489 " 1, s, S Enter rescue mode\n"
4490 " q, Q Reload init daemon configuration\n"
4491 " u, U Reexecute init daemon\n",
4492 program_invocation_short_name);
4497 static int runlevel_help(void) {
4499 printf("%s [OPTIONS...]\n\n"
4500 "Prints the previous and current runlevel of the init system.\n\n"
4501 " --help Show this help\n",
4502 program_invocation_short_name);
4507 static int systemctl_parse_argv(int argc, char *argv[]) {
4511 ARG_IGNORE_DEPENDENCIES,
4527 ARG_NO_ASK_PASSWORD,
4531 static const struct option options[] = {
4532 { "help", no_argument, NULL, 'h' },
4533 { "version", no_argument, NULL, ARG_VERSION },
4534 { "type", required_argument, NULL, 't' },
4535 { "property", required_argument, NULL, 'p' },
4536 { "all", no_argument, NULL, 'a' },
4537 { "failed", no_argument, NULL, ARG_FAILED },
4538 { "full", no_argument, NULL, ARG_FULL },
4539 { "fail", no_argument, NULL, ARG_FAIL },
4540 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4541 { "user", no_argument, NULL, ARG_USER },
4542 { "system", no_argument, NULL, ARG_SYSTEM },
4543 { "global", no_argument, NULL, ARG_GLOBAL },
4544 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4545 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4546 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4547 { "quiet", no_argument, NULL, 'q' },
4548 { "order", no_argument, NULL, ARG_ORDER },
4549 { "require", no_argument, NULL, ARG_REQUIRE },
4550 { "root", required_argument, NULL, ARG_ROOT },
4551 { "force", no_argument, NULL, 'f' },
4552 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4553 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4554 { "kill-mode", required_argument, NULL, ARG_KILL_MODE },
4555 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4556 { "signal", required_argument, NULL, 's' },
4557 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4558 { "host", required_argument, NULL, 'H' },
4559 { "privileged",no_argument, NULL, 'P' },
4560 { NULL, 0, NULL, 0 }
4568 /* Only when running as systemctl we ask for passwords */
4569 arg_ask_password = true;
4571 while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:P", options, NULL)) >= 0) {
4580 puts(PACKAGE_STRING);
4582 puts(SYSTEMD_FEATURES);
4592 if (!(l = strv_append(arg_property, optarg)))
4595 strv_free(arg_property);
4598 /* If the user asked for a particular
4599 * property, show it to him, even if it is
4610 arg_job_mode = "fail";
4613 case ARG_IGNORE_DEPENDENCIES:
4614 arg_job_mode = "ignore-dependencies";
4626 arg_no_block = true;
4630 arg_no_pager = true;
4638 arg_dot = DOT_ORDER;
4642 arg_dot = DOT_REQUIRE;
4666 arg_no_reload = true;
4675 arg_defaults = true;
4679 arg_kill_who = optarg;
4683 arg_kill_mode = optarg;
4687 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4688 log_error("Failed to parse signal string %s.", optarg);
4693 case ARG_NO_ASK_PASSWORD:
4694 arg_ask_password = false;
4698 arg_transport = TRANSPORT_POLKIT;
4702 arg_transport = TRANSPORT_SSH;
4710 log_error("Unknown option code %c", c);
4715 if (arg_transport != TRANSPORT_NORMAL && arg_user) {
4716 log_error("Cannot access user instance remotely.");
4723 static int halt_parse_argv(int argc, char *argv[]) {
4732 static const struct option options[] = {
4733 { "help", no_argument, NULL, ARG_HELP },
4734 { "halt", no_argument, NULL, ARG_HALT },
4735 { "poweroff", no_argument, NULL, 'p' },
4736 { "reboot", no_argument, NULL, ARG_REBOOT },
4737 { "force", no_argument, NULL, 'f' },
4738 { "wtmp-only", no_argument, NULL, 'w' },
4739 { "no-wtmp", no_argument, NULL, 'd' },
4740 { "no-sync", no_argument, NULL, 'n' },
4741 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4742 { NULL, 0, NULL, 0 }
4750 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4751 if (runlevel == '0' || runlevel == '6')
4752 arg_immediate = true;
4754 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4762 arg_action = ACTION_HALT;
4766 if (arg_action != ACTION_REBOOT)
4767 arg_action = ACTION_POWEROFF;
4771 arg_action = ACTION_REBOOT;
4775 arg_immediate = true;
4796 /* Compatibility nops */
4803 log_error("Unknown option code %c", c);
4808 if (optind < argc) {
4809 log_error("Too many arguments.");
4816 static int parse_time_spec(const char *t, usec_t *_u) {
4820 if (streq(t, "now"))
4822 else if (!strchr(t, ':')) {
4825 if (safe_atou64(t, &u) < 0)
4828 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4837 hour = strtol(t, &e, 10);
4838 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4841 minute = strtol(e+1, &e, 10);
4842 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4845 n = now(CLOCK_REALTIME);
4846 s = (time_t) (n / USEC_PER_SEC);
4849 assert_se(localtime_r(&s, &tm));
4851 tm.tm_hour = (int) hour;
4852 tm.tm_min = (int) minute;
4855 assert_se(s = mktime(&tm));
4857 *_u = (usec_t) s * USEC_PER_SEC;
4860 *_u += USEC_PER_DAY;
4866 static bool kexec_loaded(void) {
4867 bool loaded = false;
4870 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4878 static int shutdown_parse_argv(int argc, char *argv[]) {
4885 static const struct option options[] = {
4886 { "help", no_argument, NULL, ARG_HELP },
4887 { "halt", no_argument, NULL, 'H' },
4888 { "poweroff", no_argument, NULL, 'P' },
4889 { "reboot", no_argument, NULL, 'r' },
4890 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4891 { NULL, 0, NULL, 0 }
4899 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4907 arg_action = ACTION_HALT;
4911 arg_action = ACTION_POWEROFF;
4916 arg_action = ACTION_KEXEC;
4918 arg_action = ACTION_REBOOT;
4922 if (arg_action != ACTION_HALT)
4923 arg_action = ACTION_POWEROFF;
4936 /* Compatibility nops */
4940 arg_action = ACTION_CANCEL_SHUTDOWN;
4947 log_error("Unknown option code %c", c);
4952 if (argc > optind) {
4953 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4954 log_error("Failed to parse time specification: %s", argv[optind]);
4958 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4960 /* We skip the time argument */
4961 if (argc > optind + 1)
4962 arg_wall = argv + optind + 1;
4969 static int telinit_parse_argv(int argc, char *argv[]) {
4976 static const struct option options[] = {
4977 { "help", no_argument, NULL, ARG_HELP },
4978 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4979 { NULL, 0, NULL, 0 }
4982 static const struct {
4986 { '0', ACTION_POWEROFF },
4987 { '6', ACTION_REBOOT },
4988 { '1', ACTION_RESCUE },
4989 { '2', ACTION_RUNLEVEL2 },
4990 { '3', ACTION_RUNLEVEL3 },
4991 { '4', ACTION_RUNLEVEL4 },
4992 { '5', ACTION_RUNLEVEL5 },
4993 { 's', ACTION_RESCUE },
4994 { 'S', ACTION_RESCUE },
4995 { 'q', ACTION_RELOAD },
4996 { 'Q', ACTION_RELOAD },
4997 { 'u', ACTION_REEXEC },
4998 { 'U', ACTION_REEXEC }
5007 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5022 log_error("Unknown option code %c", c);
5027 if (optind >= argc) {
5032 if (optind + 1 < argc) {
5033 log_error("Too many arguments.");
5037 if (strlen(argv[optind]) != 1) {
5038 log_error("Expected single character argument.");
5042 for (i = 0; i < ELEMENTSOF(table); i++)
5043 if (table[i].from == argv[optind][0])
5046 if (i >= ELEMENTSOF(table)) {
5047 log_error("Unknown command %s.", argv[optind]);
5051 arg_action = table[i].to;
5058 static int runlevel_parse_argv(int argc, char *argv[]) {
5064 static const struct option options[] = {
5065 { "help", no_argument, NULL, ARG_HELP },
5066 { NULL, 0, NULL, 0 }
5074 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5085 log_error("Unknown option code %c", c);
5090 if (optind < argc) {
5091 log_error("Too many arguments.");
5098 static int parse_argv(int argc, char *argv[]) {
5102 if (program_invocation_short_name) {
5104 if (strstr(program_invocation_short_name, "halt")) {
5105 arg_action = ACTION_HALT;
5106 return halt_parse_argv(argc, argv);
5107 } else if (strstr(program_invocation_short_name, "poweroff")) {
5108 arg_action = ACTION_POWEROFF;
5109 return halt_parse_argv(argc, argv);
5110 } else if (strstr(program_invocation_short_name, "reboot")) {
5112 arg_action = ACTION_KEXEC;
5114 arg_action = ACTION_REBOOT;
5115 return halt_parse_argv(argc, argv);
5116 } else if (strstr(program_invocation_short_name, "shutdown")) {
5117 arg_action = ACTION_POWEROFF;
5118 return shutdown_parse_argv(argc, argv);
5119 } else if (strstr(program_invocation_short_name, "init")) {
5121 if (sd_booted() > 0) {
5122 arg_action = ACTION_INVALID;
5123 return telinit_parse_argv(argc, argv);
5125 /* Hmm, so some other init system is
5126 * running, we need to forward this
5127 * request to it. For now we simply
5128 * guess that it is Upstart. */
5130 execv("/lib/upstart/telinit", argv);
5132 log_error("Couldn't find an alternative telinit implementation to spawn.");
5136 } else if (strstr(program_invocation_short_name, "runlevel")) {
5137 arg_action = ACTION_RUNLEVEL;
5138 return runlevel_parse_argv(argc, argv);
5142 arg_action = ACTION_SYSTEMCTL;
5143 return systemctl_parse_argv(argc, argv);
5146 static int action_to_runlevel(void) {
5148 static const char table[_ACTION_MAX] = {
5149 [ACTION_HALT] = '0',
5150 [ACTION_POWEROFF] = '0',
5151 [ACTION_REBOOT] = '6',
5152 [ACTION_RUNLEVEL2] = '2',
5153 [ACTION_RUNLEVEL3] = '3',
5154 [ACTION_RUNLEVEL4] = '4',
5155 [ACTION_RUNLEVEL5] = '5',
5156 [ACTION_RESCUE] = '1'
5159 assert(arg_action < _ACTION_MAX);
5161 return table[arg_action];
5164 static int talk_upstart(void) {
5165 DBusMessage *m = NULL, *reply = NULL;
5167 int previous, rl, r;
5169 env1_buf[] = "RUNLEVEL=X",
5170 env2_buf[] = "PREVLEVEL=X";
5171 char *env1 = env1_buf, *env2 = env2_buf;
5172 const char *emit = "runlevel";
5173 dbus_bool_t b_false = FALSE;
5174 DBusMessageIter iter, sub;
5175 DBusConnection *bus;
5177 dbus_error_init(&error);
5179 if (!(rl = action_to_runlevel()))
5182 if (utmp_get_runlevel(&previous, NULL) < 0)
5185 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
5186 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
5191 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
5196 if ((r = bus_check_peercred(bus)) < 0) {
5197 log_error("Failed to verify owner of bus.");
5201 if (!(m = dbus_message_new_method_call(
5202 "com.ubuntu.Upstart",
5203 "/com/ubuntu/Upstart",
5204 "com.ubuntu.Upstart0_6",
5207 log_error("Could not allocate message.");
5212 dbus_message_iter_init_append(m, &iter);
5214 env1_buf[sizeof(env1_buf)-2] = rl;
5215 env2_buf[sizeof(env2_buf)-2] = previous;
5217 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5218 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5219 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5220 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5221 !dbus_message_iter_close_container(&iter, &sub) ||
5222 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5223 log_error("Could not append arguments to message.");
5228 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5230 if (error_is_no_service(&error)) {
5235 log_error("Failed to issue method call: %s", bus_error_message(&error));
5244 dbus_message_unref(m);
5247 dbus_message_unref(reply);
5250 dbus_connection_flush(bus);
5251 dbus_connection_close(bus);
5252 dbus_connection_unref(bus);
5255 dbus_error_free(&error);
5260 static int talk_initctl(void) {
5261 struct init_request request;
5265 if (!(rl = action_to_runlevel()))
5269 request.magic = INIT_MAGIC;
5270 request.sleeptime = 0;
5271 request.cmd = INIT_CMD_RUNLVL;
5272 request.runlevel = rl;
5274 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5276 if (errno == ENOENT)
5279 log_error("Failed to open "INIT_FIFO": %m");
5284 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5285 close_nointr_nofail(fd);
5288 log_error("Failed to write to "INIT_FIFO": %m");
5289 return errno ? -errno : -EIO;
5295 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5297 static const struct {
5305 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
5307 { "list-units", LESS, 1, list_units },
5308 { "list-jobs", EQUAL, 1, list_jobs },
5309 { "clear-jobs", EQUAL, 1, daemon_reload },
5310 { "load", MORE, 2, load_unit },
5311 { "cancel", MORE, 2, cancel_job },
5312 { "start", MORE, 2, start_unit },
5313 { "stop", MORE, 2, start_unit },
5314 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5315 { "reload", MORE, 2, start_unit },
5316 { "restart", MORE, 2, start_unit },
5317 { "try-restart", MORE, 2, start_unit },
5318 { "reload-or-restart", MORE, 2, start_unit },
5319 { "reload-or-try-restart", MORE, 2, start_unit },
5320 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5321 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5322 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5323 { "isolate", EQUAL, 2, start_unit },
5324 { "kill", MORE, 2, kill_unit },
5325 { "is-active", MORE, 2, check_unit },
5326 { "check", MORE, 2, check_unit },
5327 { "show", MORE, 1, show },
5328 { "status", MORE, 2, show },
5329 { "monitor", EQUAL, 1, monitor },
5330 { "dump", EQUAL, 1, dump },
5331 { "dot", EQUAL, 1, dot },
5332 { "snapshot", LESS, 2, snapshot },
5333 { "delete", MORE, 2, delete_snapshot },
5334 { "daemon-reload", EQUAL, 1, daemon_reload },
5335 { "daemon-reexec", EQUAL, 1, daemon_reload },
5336 { "show-environment", EQUAL, 1, show_enviroment },
5337 { "set-environment", MORE, 2, set_environment },
5338 { "unset-environment", MORE, 2, set_environment },
5339 { "halt", EQUAL, 1, start_special },
5340 { "poweroff", EQUAL, 1, start_special },
5341 { "reboot", EQUAL, 1, start_special },
5342 { "kexec", EQUAL, 1, start_special },
5343 { "default", EQUAL, 1, start_special },
5344 { "rescue", EQUAL, 1, start_special },
5345 { "emergency", EQUAL, 1, start_special },
5346 { "exit", EQUAL, 1, start_special },
5347 { "reset-failed", MORE, 1, reset_failed },
5348 { "enable", MORE, 2, enable_unit },
5349 { "disable", MORE, 2, enable_unit },
5350 { "is-enabled", MORE, 2, enable_unit }
5360 left = argc - optind;
5363 /* Special rule: no arguments means "list-units" */
5366 if (streq(argv[optind], "help")) {
5371 for (i = 0; i < ELEMENTSOF(verbs); i++)
5372 if (streq(argv[optind], verbs[i].verb))
5375 if (i >= ELEMENTSOF(verbs)) {
5376 log_error("Unknown operation %s", argv[optind]);
5381 switch (verbs[i].argc_cmp) {
5384 if (left != verbs[i].argc) {
5385 log_error("Invalid number of arguments.");
5392 if (left < verbs[i].argc) {
5393 log_error("Too few arguments.");
5400 if (left > verbs[i].argc) {
5401 log_error("Too many arguments.");
5408 assert_not_reached("Unknown comparison operator.");
5411 /* Require a bus connection for all operations but
5413 if (!streq(verbs[i].verb, "enable") && !streq(verbs[i].verb, "disable")) {
5415 if (running_in_chroot() > 0) {
5416 log_info("Running in chroot, ignoring request.");
5421 log_error("Failed to get D-Bus connection: %s", error->message);
5426 return verbs[i].dispatch(bus, argv + optind, left);
5429 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
5431 struct msghdr msghdr;
5433 union sockaddr_union sockaddr;
5434 struct shutdownd_command c;
5439 c.dry_run = dry_run;
5443 strncpy(c.wall_message, message, sizeof(c.wall_message));
5445 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
5449 sockaddr.sa.sa_family = AF_UNIX;
5450 sockaddr.un.sun_path[0] = 0;
5451 strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5454 iovec.iov_base = (char*) &c;
5455 iovec.iov_len = sizeof(c);
5458 msghdr.msg_name = &sockaddr;
5459 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5461 msghdr.msg_iov = &iovec;
5462 msghdr.msg_iovlen = 1;
5464 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5465 close_nointr_nofail(fd);
5469 close_nointr_nofail(fd);
5473 static int reload_with_fallback(DBusConnection *bus) {
5476 /* First, try systemd via D-Bus. */
5477 if (daemon_reload(bus, NULL, 0) > 0)
5481 /* Nothing else worked, so let's try signals */
5482 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5484 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5485 log_error("kill() failed: %m");
5492 static int start_with_fallback(DBusConnection *bus) {
5495 /* First, try systemd via D-Bus. */
5496 if (start_unit(bus, NULL, 0) >= 0)
5500 /* Hmm, talking to systemd via D-Bus didn't work. Then
5501 * let's try to talk to Upstart via D-Bus. */
5502 if (talk_upstart() > 0)
5505 /* Nothing else worked, so let's try
5507 if (talk_initctl() > 0)
5510 log_error("Failed to talk to init daemon.");
5514 warn_wall(arg_action);
5518 static int halt_main(DBusConnection *bus) {
5521 if (geteuid() != 0) {
5522 log_error("Must be root.");
5528 char date[FORMAT_TIMESTAMP_MAX];
5530 m = strv_join(arg_wall, " ");
5531 r = send_shutdownd(arg_when,
5532 arg_action == ACTION_HALT ? 'H' :
5533 arg_action == ACTION_POWEROFF ? 'P' :
5541 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5543 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5544 format_timestamp(date, sizeof(date), arg_when));
5549 if (!arg_dry && !arg_immediate)
5550 return start_with_fallback(bus);
5553 if (sd_booted() > 0)
5554 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5555 else if ((r = utmp_put_shutdown(0)) < 0)
5556 log_warning("Failed to write utmp record: %s", strerror(-r));
5565 /* Make sure C-A-D is handled by the kernel from this
5567 reboot(RB_ENABLE_CAD);
5569 switch (arg_action) {
5572 log_info("Halting.");
5573 reboot(RB_HALT_SYSTEM);
5576 case ACTION_POWEROFF:
5577 log_info("Powering off.");
5578 reboot(RB_POWER_OFF);
5582 log_info("Rebooting.");
5583 reboot(RB_AUTOBOOT);
5587 assert_not_reached("Unknown halt action.");
5590 /* We should never reach this. */
5594 static int runlevel_main(void) {
5595 int r, runlevel, previous;
5597 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5598 printf("unknown\n");
5603 previous <= 0 ? 'N' : previous,
5604 runlevel <= 0 ? 'N' : runlevel);
5609 static void agent_close(void) {
5615 /* Inform agent that we are done */
5616 kill(agent_pid, SIGTERM);
5617 kill(agent_pid, SIGCONT);
5618 wait_for_terminate(agent_pid, &dummy);
5622 int main(int argc, char*argv[]) {
5623 int r, retval = EXIT_FAILURE;
5624 DBusConnection *bus = NULL;
5627 dbus_error_init(&error);
5629 log_parse_environment();
5632 if ((r = parse_argv(argc, argv)) < 0)
5635 retval = EXIT_SUCCESS;
5639 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5640 * let's shortcut this */
5641 if (arg_action == ACTION_RUNLEVEL) {
5642 r = runlevel_main();
5643 retval = r < 0 ? EXIT_FAILURE : r;
5647 if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5648 log_info("Running in chroot, ignoring request.");
5653 if (arg_transport == TRANSPORT_NORMAL)
5654 bus_connect(arg_user ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5655 else if (arg_transport == TRANSPORT_POLKIT) {
5656 bus_connect_system_polkit(&bus, &error);
5657 private_bus = false;
5658 } else if (arg_transport == TRANSPORT_SSH) {
5659 bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5660 private_bus = false;
5662 assert_not_reached("Uh, invalid transport...");
5664 switch (arg_action) {
5666 case ACTION_SYSTEMCTL:
5667 r = systemctl_main(bus, argc, argv, &error);
5671 case ACTION_POWEROFF:
5677 case ACTION_RUNLEVEL2:
5678 case ACTION_RUNLEVEL3:
5679 case ACTION_RUNLEVEL4:
5680 case ACTION_RUNLEVEL5:
5682 case ACTION_EMERGENCY:
5683 case ACTION_DEFAULT:
5684 r = start_with_fallback(bus);
5689 r = reload_with_fallback(bus);
5692 case ACTION_CANCEL_SHUTDOWN:
5693 r = send_shutdownd(0, 0, false, false, NULL);
5696 case ACTION_INVALID:
5697 case ACTION_RUNLEVEL:
5699 assert_not_reached("Unknown action");
5702 retval = r < 0 ? EXIT_FAILURE : r;
5707 dbus_connection_flush(bus);
5708 dbus_connection_close(bus);
5709 dbus_connection_unref(bus);
5712 dbus_error_free(&error);
5716 strv_free(arg_property);