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>
36 #include <dbus/dbus.h>
42 #include "utmp-wtmp.h"
46 #include "dbus-common.h"
47 #include "cgroup-show.h"
48 #include "cgroup-util.h"
50 #include "path-lookup.h"
51 #include "conf-parser.h"
52 #include "sd-daemon.h"
53 #include "shutdownd.h"
54 #include "exit-status.h"
55 #include "bus-errors.h"
57 #include "unit-name.h"
60 static const char *arg_type = NULL;
61 static char **arg_property = NULL;
62 static bool arg_all = false;
63 static const char *arg_job_mode = "replace";
64 static bool arg_user = false;
65 static bool arg_global = false;
66 static bool arg_immediate = false;
67 static bool arg_no_block = false;
68 static bool arg_no_pager = false;
69 static bool arg_no_wtmp = false;
70 static bool arg_no_sync = false;
71 static bool arg_no_wall = false;
72 static bool arg_no_reload = false;
73 static bool arg_dry = false;
74 static bool arg_quiet = false;
75 static bool arg_full = false;
76 static bool arg_force = false;
77 static bool arg_defaults = false;
78 static bool arg_ask_password = false;
79 static bool arg_failed = false;
80 static char **arg_wall = NULL;
81 static const char *arg_kill_who = NULL;
82 static const char *arg_kill_mode = NULL;
83 static const char *arg_root = NULL;
84 static int arg_signal = SIGTERM;
85 static usec_t arg_when = 0;
104 ACTION_CANCEL_SHUTDOWN,
106 } arg_action = ACTION_SYSTEMCTL;
112 static enum transport {
116 } arg_transport = TRANSPORT_NORMAL;
117 static const char *arg_host = NULL;
119 static bool private_bus = false;
121 static pid_t agent_pid = 0;
123 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
125 static bool on_tty(void) {
128 /* Note that this is invoked relatively early, before we start
129 * the pager. That means the value we return reflects whether
130 * we originally were started on a tty, not if we currently
131 * are. But this is intended, since we want colour and so on
132 * when run in our own pager. */
134 if (_unlikely_(t < 0))
135 t = isatty(STDOUT_FILENO) > 0;
140 static void pager_open_if_enabled(void) {
147 static void spawn_ask_password_agent(void) {
153 /* We check STDIN here, not STDOUT, since this is about input,
155 if (!isatty(STDIN_FILENO))
158 if (!arg_ask_password)
166 /* Spawns a temporary TTY agent, making sure it goes away when
169 if ((agent_pid = fork()) < 0)
172 if (agent_pid == 0) {
176 bool stdout_is_tty, stderr_is_tty;
178 /* Make sure the agent goes away when the parent dies */
179 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
182 /* Check whether our parent died before we were able
183 * to set the death signal */
184 if (getppid() != parent)
187 /* Don't leak fds to the agent */
188 close_all_fds(NULL, 0);
190 stdout_is_tty = isatty(STDOUT_FILENO);
191 stderr_is_tty = isatty(STDERR_FILENO);
193 if (!stdout_is_tty || !stderr_is_tty) {
194 /* Detach from stdout/stderr. and reopen
195 * /dev/tty for them. This is important to
196 * ensure that when systemctl is started via
197 * popen() or a similar call that expects to
198 * read EOF we actually do generate EOF and
199 * not delay this indefinitely by because we
200 * keep an unused copy of stdin around. */
201 if ((fd = open("/dev/tty", O_WRONLY)) < 0) {
202 log_error("Failed to open /dev/tty: %m");
207 dup2(fd, STDOUT_FILENO);
210 dup2(fd, STDERR_FILENO);
216 execl(SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, "--watch", NULL);
218 log_error("Unable to execute agent: %m");
223 static const char *ansi_highlight(bool b) {
228 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
231 static const char *ansi_highlight_green(bool b) {
236 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
239 static bool error_is_no_service(const DBusError *error) {
242 if (!dbus_error_is_set(error))
245 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
248 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
251 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
254 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
257 if (!dbus_error_is_set(error))
260 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
261 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
262 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
263 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
264 return EXIT_NOPERMISSION;
266 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
267 return EXIT_NOTINSTALLED;
269 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
270 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
271 return EXIT_NOTIMPLEMENTED;
273 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
274 return EXIT_NOTCONFIGURED;
282 static void warn_wall(enum action action) {
283 static const char *table[_ACTION_MAX] = {
284 [ACTION_HALT] = "The system is going down for system halt NOW!",
285 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
286 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
287 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
288 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
289 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
298 if (!(p = strv_join(arg_wall, " "))) {
299 log_error("Failed to join strings.");
315 utmp_wall(table[action], NULL);
320 const char *description;
321 const char *load_state;
322 const char *active_state;
323 const char *sub_state;
324 const char *following;
325 const char *unit_path;
327 const char *job_type;
328 const char *job_path;
331 static int compare_unit_info(const void *a, const void *b) {
333 const struct unit_info *u = a, *v = b;
335 d1 = strrchr(u->id, '.');
336 d2 = strrchr(v->id, '.');
341 if ((r = strcasecmp(d1, d2)) != 0)
345 return strcasecmp(u->id, v->id);
348 static bool output_show_unit(const struct unit_info *u) {
352 return streq(u->active_state, "failed");
354 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
355 streq(dot+1, arg_type))) &&
356 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0);
359 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
360 unsigned active_len, sub_len, job_len, n_shown = 0;
361 const struct unit_info *u;
363 active_len = sizeof("ACTIVE")-1;
364 sub_len = sizeof("SUB")-1;
365 job_len = sizeof("JOB")-1;
367 for (u = unit_infos; u < unit_infos + c; u++) {
368 if (!output_show_unit(u))
371 active_len = MAX(active_len, strlen(u->active_state));
372 sub_len = MAX(sub_len, strlen(u->sub_state));
374 job_len = MAX(job_len, strlen(u->job_type));
378 printf("%-25s %-6s %-*s %-*s %-*s", "UNIT", "LOAD",
379 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
380 if (columns() >= 80+12 || arg_full || !arg_no_pager)
381 printf(" %s\n", "DESCRIPTION");
386 for (u = unit_infos; u < unit_infos + c; u++) {
389 const char *on_loaded, *off_loaded;
390 const char *on_active, *off_active;
392 if (!output_show_unit(u))
397 if (!streq(u->load_state, "loaded") &&
398 !streq(u->load_state, "banned")) {
399 on_loaded = ansi_highlight(true);
400 off_loaded = ansi_highlight(false);
402 on_loaded = off_loaded = "";
404 if (streq(u->active_state, "failed")) {
405 on_active = ansi_highlight(true);
406 off_active = ansi_highlight(false);
408 on_active = off_active = "";
410 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
412 printf("%-25s %s%-6s%s %s%-*s %-*s%s%n",
414 on_loaded, u->load_state, off_loaded,
415 on_active, active_len, u->active_state,
416 sub_len, u->sub_state, off_active,
421 a -= strlen(on_loaded) + strlen(off_loaded);
422 a -= strlen(on_active) + strlen(off_active);
425 printf(" %-*s", job_len, u->job_type);
429 if (a + b + 1 < columns()) {
431 printf(" %-*s", job_len, "");
433 if (arg_full || !arg_no_pager)
434 printf(" %s", u->description);
436 printf(" %.*s", columns() - a - b - 1, u->description);
443 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
444 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
445 "SUB = The low-level unit activation state, values depend on unit type.\n"
446 "JOB = Pending job for the unit.\n");
449 printf("\n%u units listed.\n", n_shown);
451 printf("\n%u units listed. Pass --all to see inactive units, too.\n", n_shown);
455 static int list_units(DBusConnection *bus, char **args, unsigned n) {
456 DBusMessage *m = NULL, *reply = NULL;
459 DBusMessageIter iter, sub, sub2;
460 unsigned c = 0, n_units = 0;
461 struct unit_info *unit_infos = NULL;
463 dbus_error_init(&error);
467 pager_open_if_enabled();
469 if (!(m = dbus_message_new_method_call(
470 "org.freedesktop.systemd1",
471 "/org/freedesktop/systemd1",
472 "org.freedesktop.systemd1.Manager",
474 log_error("Could not allocate message.");
478 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
479 log_error("Failed to issue method call: %s", bus_error_message(&error));
484 if (!dbus_message_iter_init(reply, &iter) ||
485 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
486 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
487 log_error("Failed to parse reply.");
492 dbus_message_iter_recurse(&iter, &sub);
494 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
497 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
498 log_error("Failed to parse reply.");
506 n_units = MAX(2*c, 16);
507 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
510 log_error("Failed to allocate unit array.");
520 dbus_message_iter_recurse(&sub, &sub2);
522 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
523 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
524 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
525 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
526 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
527 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
528 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
529 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
530 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
531 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
532 log_error("Failed to parse reply.");
537 dbus_message_iter_next(&sub);
542 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
543 output_units_list(unit_infos, c);
550 dbus_message_unref(m);
553 dbus_message_unref(reply);
557 dbus_error_free(&error);
562 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
563 static const char * const colors[] = {
564 "Requires", "[color=\"black\"]",
565 "RequiresOverridable", "[color=\"black\"]",
566 "Requisite", "[color=\"darkblue\"]",
567 "RequisiteOverridable", "[color=\"darkblue\"]",
568 "Wants", "[color=\"darkgrey\"]",
569 "Conflicts", "[color=\"red\"]",
570 "ConflictedBy", "[color=\"red\"]",
571 "After", "[color=\"green\"]"
574 const char *c = NULL;
581 for (i = 0; i < ELEMENTSOF(colors); i += 2)
582 if (streq(colors[i], prop)) {
590 if (arg_dot != DOT_ALL)
591 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
594 switch (dbus_message_iter_get_arg_type(iter)) {
596 case DBUS_TYPE_ARRAY:
598 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
601 dbus_message_iter_recurse(iter, &sub);
603 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
606 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
607 dbus_message_iter_get_basic(&sub, &s);
608 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
610 dbus_message_iter_next(&sub);
620 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
621 DBusMessage *m = NULL, *reply = NULL;
622 const char *interface = "org.freedesktop.systemd1.Unit";
625 DBusMessageIter iter, sub, sub2, sub3;
630 dbus_error_init(&error);
632 if (!(m = dbus_message_new_method_call(
633 "org.freedesktop.systemd1",
635 "org.freedesktop.DBus.Properties",
637 log_error("Could not allocate message.");
642 if (!dbus_message_append_args(m,
643 DBUS_TYPE_STRING, &interface,
644 DBUS_TYPE_INVALID)) {
645 log_error("Could not append arguments to message.");
650 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
651 log_error("Failed to issue method call: %s", bus_error_message(&error));
656 if (!dbus_message_iter_init(reply, &iter) ||
657 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
658 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
659 log_error("Failed to parse reply.");
664 dbus_message_iter_recurse(&iter, &sub);
666 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
669 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
670 log_error("Failed to parse reply.");
675 dbus_message_iter_recurse(&sub, &sub2);
677 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
678 log_error("Failed to parse reply.");
683 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
684 log_error("Failed to parse reply.");
689 dbus_message_iter_recurse(&sub2, &sub3);
691 if (dot_one_property(name, prop, &sub3)) {
692 log_error("Failed to parse reply.");
697 dbus_message_iter_next(&sub);
704 dbus_message_unref(m);
707 dbus_message_unref(reply);
709 dbus_error_free(&error);
714 static int dot(DBusConnection *bus, char **args, unsigned n) {
715 DBusMessage *m = NULL, *reply = NULL;
718 DBusMessageIter iter, sub, sub2;
720 dbus_error_init(&error);
724 if (!(m = dbus_message_new_method_call(
725 "org.freedesktop.systemd1",
726 "/org/freedesktop/systemd1",
727 "org.freedesktop.systemd1.Manager",
729 log_error("Could not allocate message.");
733 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
734 log_error("Failed to issue method call: %s", bus_error_message(&error));
739 if (!dbus_message_iter_init(reply, &iter) ||
740 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
741 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
742 log_error("Failed to parse reply.");
747 printf("digraph systemd {\n");
749 dbus_message_iter_recurse(&iter, &sub);
750 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
751 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
753 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
754 log_error("Failed to parse reply.");
759 dbus_message_iter_recurse(&sub, &sub2);
761 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
762 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
763 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
764 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
765 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
766 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
767 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
768 log_error("Failed to parse reply.");
773 if ((r = dot_one(bus, id, unit_path)) < 0)
776 /* printf("\t\"%s\";\n", id); */
777 dbus_message_iter_next(&sub);
782 log_info(" Color legend: black = Requires\n"
783 " dark blue = Requisite\n"
784 " dark grey = Wants\n"
788 if (isatty(fileno(stdout)))
789 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
790 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
796 dbus_message_unref(m);
799 dbus_message_unref(reply);
801 dbus_error_free(&error);
806 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
807 DBusMessage *m = NULL, *reply = NULL;
810 DBusMessageIter iter, sub, sub2;
813 dbus_error_init(&error);
817 pager_open_if_enabled();
819 if (!(m = dbus_message_new_method_call(
820 "org.freedesktop.systemd1",
821 "/org/freedesktop/systemd1",
822 "org.freedesktop.systemd1.Manager",
824 log_error("Could not allocate message.");
828 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
829 log_error("Failed to issue method call: %s", bus_error_message(&error));
834 if (!dbus_message_iter_init(reply, &iter) ||
835 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
836 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
837 log_error("Failed to parse reply.");
842 dbus_message_iter_recurse(&iter, &sub);
844 if (isatty(STDOUT_FILENO))
845 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
847 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
848 const char *name, *type, *state, *job_path, *unit_path;
852 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
853 log_error("Failed to parse reply.");
858 dbus_message_iter_recurse(&sub, &sub2);
860 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
861 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
862 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
863 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
864 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
865 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
866 log_error("Failed to parse reply.");
871 e = arg_full ? NULL : ellipsize(name, 25, 33);
872 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
877 dbus_message_iter_next(&sub);
880 if (isatty(STDOUT_FILENO))
881 printf("\n%u jobs listed.\n", k);
887 dbus_message_unref(m);
890 dbus_message_unref(reply);
892 dbus_error_free(&error);
897 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
898 DBusMessage *m = NULL, *reply = NULL;
903 dbus_error_init(&error);
908 for (i = 1; i < n; i++) {
910 if (!(m = dbus_message_new_method_call(
911 "org.freedesktop.systemd1",
912 "/org/freedesktop/systemd1",
913 "org.freedesktop.systemd1.Manager",
915 log_error("Could not allocate message.");
920 if (!dbus_message_append_args(m,
921 DBUS_TYPE_STRING, &args[i],
922 DBUS_TYPE_INVALID)) {
923 log_error("Could not append arguments to message.");
928 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
929 log_error("Failed to issue method call: %s", bus_error_message(&error));
934 dbus_message_unref(m);
935 dbus_message_unref(reply);
944 dbus_message_unref(m);
947 dbus_message_unref(reply);
949 dbus_error_free(&error);
954 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
955 DBusMessage *m = NULL, *reply = NULL;
960 dbus_error_init(&error);
966 return daemon_reload(bus, args, n);
968 for (i = 1; i < n; i++) {
972 if (!(m = dbus_message_new_method_call(
973 "org.freedesktop.systemd1",
974 "/org/freedesktop/systemd1",
975 "org.freedesktop.systemd1.Manager",
977 log_error("Could not allocate message.");
982 if ((r = safe_atou(args[i], &id)) < 0) {
983 log_error("Failed to parse job id: %s", strerror(-r));
987 assert_cc(sizeof(uint32_t) == sizeof(id));
988 if (!dbus_message_append_args(m,
989 DBUS_TYPE_UINT32, &id,
990 DBUS_TYPE_INVALID)) {
991 log_error("Could not append arguments to message.");
996 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
997 log_error("Failed to issue method call: %s", bus_error_message(&error));
1002 if (!dbus_message_get_args(reply, &error,
1003 DBUS_TYPE_OBJECT_PATH, &path,
1004 DBUS_TYPE_INVALID)) {
1005 log_error("Failed to parse reply: %s", bus_error_message(&error));
1010 dbus_message_unref(m);
1011 if (!(m = dbus_message_new_method_call(
1012 "org.freedesktop.systemd1",
1014 "org.freedesktop.systemd1.Job",
1016 log_error("Could not allocate message.");
1021 dbus_message_unref(reply);
1022 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1023 log_error("Failed to issue method call: %s", bus_error_message(&error));
1028 dbus_message_unref(m);
1029 dbus_message_unref(reply);
1037 dbus_message_unref(m);
1040 dbus_message_unref(reply);
1042 dbus_error_free(&error);
1047 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1048 DBusMessage *m = NULL, *reply = NULL;
1049 dbus_bool_t b = FALSE;
1050 DBusMessageIter iter, sub;
1052 *interface = "org.freedesktop.systemd1.Unit",
1053 *property = "NeedDaemonReload",
1056 /* We ignore all errors here, since this is used to show a warning only */
1058 if (!(m = dbus_message_new_method_call(
1059 "org.freedesktop.systemd1",
1060 "/org/freedesktop/systemd1",
1061 "org.freedesktop.systemd1.Manager",
1065 if (!dbus_message_append_args(m,
1066 DBUS_TYPE_STRING, &unit,
1070 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1073 if (!dbus_message_get_args(reply, NULL,
1074 DBUS_TYPE_OBJECT_PATH, &path,
1078 dbus_message_unref(m);
1079 if (!(m = dbus_message_new_method_call(
1080 "org.freedesktop.systemd1",
1082 "org.freedesktop.DBus.Properties",
1086 if (!dbus_message_append_args(m,
1087 DBUS_TYPE_STRING, &interface,
1088 DBUS_TYPE_STRING, &property,
1089 DBUS_TYPE_INVALID)) {
1093 dbus_message_unref(reply);
1094 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1097 if (!dbus_message_iter_init(reply, &iter) ||
1098 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1101 dbus_message_iter_recurse(&iter, &sub);
1103 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1106 dbus_message_iter_get_basic(&sub, &b);
1110 dbus_message_unref(m);
1113 dbus_message_unref(reply);
1118 typedef struct WaitData {
1123 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1131 dbus_error_init(&error);
1133 log_debug("Got D-Bus request: %s.%s() on %s",
1134 dbus_message_get_interface(message),
1135 dbus_message_get_member(message),
1136 dbus_message_get_path(message));
1138 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1139 log_error("Warning! D-Bus connection terminated.");
1140 dbus_connection_close(connection);
1142 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1144 const char *path, *result;
1145 dbus_bool_t success = true;
1147 if (dbus_message_get_args(message, &error,
1148 DBUS_TYPE_UINT32, &id,
1149 DBUS_TYPE_OBJECT_PATH, &path,
1150 DBUS_TYPE_STRING, &result,
1151 DBUS_TYPE_INVALID)) {
1154 if ((p = set_remove(d->set, (char*) path)))
1158 d->result = strdup(result);
1163 dbus_error_free(&error);
1165 if (dbus_message_get_args(message, &error,
1166 DBUS_TYPE_UINT32, &id,
1167 DBUS_TYPE_OBJECT_PATH, &path,
1168 DBUS_TYPE_BOOLEAN, &success,
1169 DBUS_TYPE_INVALID)) {
1172 /* Compatibility with older systemd versions <
1173 * 19 during upgrades. This should be dropped
1176 if ((p = set_remove(d->set, (char*) path)))
1180 d->result = strdup("failed");
1186 log_error("Failed to parse message: %s", bus_error_message(&error));
1190 dbus_error_free(&error);
1191 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1194 static int enable_wait_for_jobs(DBusConnection *bus) {
1202 dbus_error_init(&error);
1203 dbus_bus_add_match(bus,
1205 "sender='org.freedesktop.systemd1',"
1206 "interface='org.freedesktop.systemd1.Manager',"
1207 "member='JobRemoved',"
1208 "path='/org/freedesktop/systemd1'",
1211 if (dbus_error_is_set(&error)) {
1212 log_error("Failed to add match: %s", bus_error_message(&error));
1213 dbus_error_free(&error);
1217 /* This is slightly dirty, since we don't undo the match registrations. */
1221 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1231 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1232 log_error("Failed to add filter.");
1237 while (!set_isempty(s) &&
1238 dbus_connection_read_write_dispatch(bus, -1))
1241 if (!arg_quiet && d.result) {
1242 if (streq(d.result, "timeout"))
1243 log_error("Job timed out.");
1244 else if (streq(d.result, "canceled"))
1245 log_error("Job canceled.");
1246 else if (streq(d.result, "dependency"))
1247 log_error("A dependency job failed. See system logs for details.");
1248 else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
1249 log_error("Job failed. See system logs and 'systemctl status' for details.");
1252 if (streq_ptr(d.result, "timeout"))
1254 else if (streq_ptr(d.result, "canceled"))
1256 else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
1264 /* This is slightly dirty, since we don't undo the filter registration. */
1269 static int start_unit_one(
1270 DBusConnection *bus,
1277 DBusMessage *m = NULL, *reply = NULL;
1286 assert(arg_no_block || s);
1288 if (!(m = dbus_message_new_method_call(
1289 "org.freedesktop.systemd1",
1290 "/org/freedesktop/systemd1",
1291 "org.freedesktop.systemd1.Manager",
1293 log_error("Could not allocate message.");
1298 if (!dbus_message_append_args(m,
1299 DBUS_TYPE_STRING, &name,
1300 DBUS_TYPE_STRING, &mode,
1301 DBUS_TYPE_INVALID)) {
1302 log_error("Could not append arguments to message.");
1307 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1309 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1310 /* There's always a fallback possible for
1311 * legacy actions. */
1316 log_error("Failed to issue method call: %s", bus_error_message(error));
1321 if (!dbus_message_get_args(reply, error,
1322 DBUS_TYPE_OBJECT_PATH, &path,
1323 DBUS_TYPE_INVALID)) {
1324 log_error("Failed to parse reply: %s", bus_error_message(error));
1329 if (need_daemon_reload(bus, name))
1330 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1331 arg_user ? "--user" : "--system");
1333 if (!arg_no_block) {
1336 if (!(p = strdup(path))) {
1337 log_error("Failed to duplicate path.");
1342 if ((r = set_put(s, p)) < 0) {
1344 log_error("Failed to add path to set.");
1353 dbus_message_unref(m);
1356 dbus_message_unref(reply);
1361 static enum action verb_to_action(const char *verb) {
1362 if (streq(verb, "halt"))
1364 else if (streq(verb, "poweroff"))
1365 return ACTION_POWEROFF;
1366 else if (streq(verb, "reboot"))
1367 return ACTION_REBOOT;
1368 else if (streq(verb, "kexec"))
1369 return ACTION_KEXEC;
1370 else if (streq(verb, "rescue"))
1371 return ACTION_RESCUE;
1372 else if (streq(verb, "emergency"))
1373 return ACTION_EMERGENCY;
1374 else if (streq(verb, "default"))
1375 return ACTION_DEFAULT;
1376 else if (streq(verb, "exit"))
1379 return ACTION_INVALID;
1382 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1384 static const char * const table[_ACTION_MAX] = {
1385 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1386 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1387 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1388 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1389 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1390 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1391 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1392 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1393 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1394 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1395 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1396 [ACTION_EXIT] = SPECIAL_EXIT_TARGET
1401 const char *method, *mode, *one_name;
1405 dbus_error_init(&error);
1409 spawn_ask_password_agent();
1411 if (arg_action == ACTION_SYSTEMCTL) {
1413 streq(args[0], "stop") ||
1414 streq(args[0], "condstop") ? "StopUnit" :
1415 streq(args[0], "reload") ? "ReloadUnit" :
1416 streq(args[0], "restart") ? "RestartUnit" :
1418 streq(args[0], "try-restart") ||
1419 streq(args[0], "condrestart") ? "TryRestartUnit" :
1421 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1423 streq(args[0], "reload-or-try-restart") ||
1424 streq(args[0], "condreload") ||
1426 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1430 (streq(args[0], "isolate") ||
1431 streq(args[0], "rescue") ||
1432 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1434 one_name = table[verb_to_action(args[0])];
1437 assert(arg_action < ELEMENTSOF(table));
1438 assert(table[arg_action]);
1440 method = "StartUnit";
1442 mode = (arg_action == ACTION_EMERGENCY ||
1443 arg_action == ACTION_RESCUE ||
1444 arg_action == ACTION_RUNLEVEL2 ||
1445 arg_action == ACTION_RUNLEVEL3 ||
1446 arg_action == ACTION_RUNLEVEL4 ||
1447 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1449 one_name = table[arg_action];
1452 if (!arg_no_block) {
1453 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1454 log_error("Could not watch jobs: %s", strerror(-ret));
1458 if (!(s = set_new(string_hash_func, string_compare_func))) {
1459 log_error("Failed to allocate set.");
1466 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1469 for (i = 1; i < n; i++)
1470 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1471 ret = translate_bus_error_to_exit_status(r, &error);
1472 dbus_error_free(&error);
1477 if ((r = wait_for_jobs(bus, s)) < 0) {
1486 dbus_error_free(&error);
1491 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1498 (streq(args[0], "halt") ||
1499 streq(args[0], "poweroff") ||
1500 streq(args[0], "reboot") ||
1501 streq(args[0], "kexec") ||
1502 streq(args[0], "exit")))
1503 return daemon_reload(bus, args, n);
1505 r = start_unit(bus, args, n);
1508 warn_wall(verb_to_action(args[0]));
1513 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1514 DBusMessage *m = NULL, *reply = NULL;
1516 *interface = "org.freedesktop.systemd1.Unit",
1517 *property = "ActiveState";
1518 int r = 3; /* According to LSB: "program is not running" */
1525 dbus_error_init(&error);
1527 for (i = 1; i < n; i++) {
1528 const char *path = NULL;
1530 DBusMessageIter iter, sub;
1532 if (!(m = dbus_message_new_method_call(
1533 "org.freedesktop.systemd1",
1534 "/org/freedesktop/systemd1",
1535 "org.freedesktop.systemd1.Manager",
1537 log_error("Could not allocate message.");
1542 if (!dbus_message_append_args(m,
1543 DBUS_TYPE_STRING, &args[i],
1544 DBUS_TYPE_INVALID)) {
1545 log_error("Could not append arguments to message.");
1550 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1552 /* Hmm, cannot figure out anything about this unit... */
1556 dbus_error_free(&error);
1557 dbus_message_unref(m);
1562 if (!dbus_message_get_args(reply, &error,
1563 DBUS_TYPE_OBJECT_PATH, &path,
1564 DBUS_TYPE_INVALID)) {
1565 log_error("Failed to parse reply: %s", bus_error_message(&error));
1570 dbus_message_unref(m);
1571 if (!(m = dbus_message_new_method_call(
1572 "org.freedesktop.systemd1",
1574 "org.freedesktop.DBus.Properties",
1576 log_error("Could not allocate message.");
1581 if (!dbus_message_append_args(m,
1582 DBUS_TYPE_STRING, &interface,
1583 DBUS_TYPE_STRING, &property,
1584 DBUS_TYPE_INVALID)) {
1585 log_error("Could not append arguments to message.");
1590 dbus_message_unref(reply);
1591 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1592 log_error("Failed to issue method call: %s", bus_error_message(&error));
1597 if (!dbus_message_iter_init(reply, &iter) ||
1598 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1599 log_error("Failed to parse reply.");
1604 dbus_message_iter_recurse(&iter, &sub);
1606 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1607 log_error("Failed to parse reply.");
1612 dbus_message_iter_get_basic(&sub, &state);
1617 if (streq(state, "active") || streq(state, "reloading"))
1620 dbus_message_unref(m);
1621 dbus_message_unref(reply);
1627 dbus_message_unref(m);
1630 dbus_message_unref(reply);
1632 dbus_error_free(&error);
1637 static int kill_unit(DBusConnection *bus, char **args, unsigned n) {
1638 DBusMessage *m = NULL, *reply = NULL;
1646 dbus_error_init(&error);
1649 arg_kill_who = "all";
1652 arg_kill_mode = streq(arg_kill_who, "all") ? "control-group" : "process";
1654 for (i = 1; i < n; i++) {
1656 if (!(m = dbus_message_new_method_call(
1657 "org.freedesktop.systemd1",
1658 "/org/freedesktop/systemd1",
1659 "org.freedesktop.systemd1.Manager",
1661 log_error("Could not allocate message.");
1666 if (!dbus_message_append_args(m,
1667 DBUS_TYPE_STRING, &args[i],
1668 DBUS_TYPE_STRING, &arg_kill_who,
1669 DBUS_TYPE_STRING, &arg_kill_mode,
1670 DBUS_TYPE_INT32, &arg_signal,
1671 DBUS_TYPE_INVALID)) {
1672 log_error("Could not append arguments to message.");
1677 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1678 log_error("Failed to issue method call: %s", bus_error_message(&error));
1679 dbus_error_free(&error);
1683 dbus_message_unref(m);
1686 dbus_message_unref(reply);
1692 dbus_message_unref(m);
1695 dbus_message_unref(reply);
1697 dbus_error_free(&error);
1702 typedef struct ExecStatusInfo {
1710 usec_t start_timestamp;
1711 usec_t exit_timestamp;
1716 LIST_FIELDS(struct ExecStatusInfo, exec);
1719 static void exec_status_info_free(ExecStatusInfo *i) {
1728 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1729 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
1730 DBusMessageIter sub2, sub3;
1734 int32_t code, status;
1740 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1743 dbus_message_iter_recurse(sub, &sub2);
1745 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1748 if (!(i->path = strdup(path)))
1751 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1752 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1756 dbus_message_iter_recurse(&sub2, &sub3);
1757 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1758 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1759 dbus_message_iter_next(&sub3);
1764 if (!(i->argv = new0(char*, n+1)))
1768 dbus_message_iter_recurse(&sub2, &sub3);
1769 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1772 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1773 dbus_message_iter_get_basic(&sub3, &s);
1774 dbus_message_iter_next(&sub3);
1776 if (!(i->argv[n++] = strdup(s)))
1780 if (!dbus_message_iter_next(&sub2) ||
1781 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1782 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1783 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
1784 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1785 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
1786 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1787 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1788 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1792 i->start_timestamp = (usec_t) start_timestamp;
1793 i->exit_timestamp = (usec_t) exit_timestamp;
1794 i->pid = (pid_t) pid;
1801 typedef struct UnitStatusInfo {
1803 const char *load_state;
1804 const char *active_state;
1805 const char *sub_state;
1807 const char *description;
1808 const char *following;
1811 const char *default_control_group;
1813 usec_t inactive_exit_timestamp;
1814 usec_t active_enter_timestamp;
1815 usec_t active_exit_timestamp;
1816 usec_t inactive_enter_timestamp;
1818 bool need_daemon_reload;
1823 const char *status_text;
1825 #ifdef HAVE_SYSV_COMPAT
1829 usec_t start_timestamp;
1830 usec_t exit_timestamp;
1832 int exit_code, exit_status;
1834 usec_t condition_timestamp;
1835 bool condition_result;
1838 unsigned n_accepted;
1839 unsigned n_connections;
1843 const char *sysfs_path;
1845 /* Mount, Automount */
1851 LIST_HEAD(ExecStatusInfo, exec);
1854 static void print_status_info(UnitStatusInfo *i) {
1856 const char *on, *off, *ss;
1858 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1859 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1863 /* This shows pretty information about a unit. See
1864 * print_property() for a low-level property printer */
1866 printf("%s", strna(i->id));
1868 if (i->description && !streq_ptr(i->id, i->description))
1869 printf(" - %s", i->description);
1874 printf("\t Follow: unit currently follows state of %s\n", i->following);
1876 if (streq_ptr(i->load_state, "failed") ||
1877 streq_ptr(i->load_state, "banned")) {
1878 on = ansi_highlight(true);
1879 off = ansi_highlight(false);
1884 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1886 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1888 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1890 if (streq_ptr(i->active_state, "failed")) {
1891 on = ansi_highlight(true);
1892 off = ansi_highlight(false);
1893 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1894 on = ansi_highlight_green(true);
1895 off = ansi_highlight_green(false);
1900 printf("\t Active: %s%s (%s)%s",
1902 strna(i->active_state),
1906 printf("\t Active: %s%s%s",
1908 strna(i->active_state),
1911 timestamp = (streq_ptr(i->active_state, "active") ||
1912 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1913 (streq_ptr(i->active_state, "inactive") ||
1914 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1915 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1916 i->active_exit_timestamp;
1918 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1919 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1922 printf(" since %s; %s\n", s2, s1);
1924 printf(" since %s\n", s2);
1928 if (!i->condition_result && i->condition_timestamp > 0) {
1929 s1 = format_timestamp_pretty(since1, sizeof(since1), i->condition_timestamp);
1930 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
1933 printf("\t start condition failed at %s; %s\n", s2, s1);
1935 printf("\t start condition failed at %s\n", s2);
1939 printf("\t Device: %s\n", i->sysfs_path);
1941 printf("\t Where: %s\n", i->where);
1943 printf("\t What: %s\n", i->what);
1946 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1948 LIST_FOREACH(exec, p, i->exec) {
1952 /* Only show exited processes here */
1956 t = strv_join(p->argv, " ");
1957 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
1960 #ifdef HAVE_SYSV_COMPAT
1962 good = is_clean_exit_lsb(p->code, p->status);
1965 good = is_clean_exit(p->code, p->status);
1968 on = ansi_highlight(true);
1969 off = ansi_highlight(false);
1973 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
1975 if (p->code == CLD_EXITED) {
1978 printf("status=%i", p->status);
1980 #ifdef HAVE_SYSV_COMPAT
1981 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1983 if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1988 printf("signal=%s", signal_to_string(p->status));
1990 printf(")%s\n", off);
1994 if (i->main_pid == p->pid &&
1995 i->start_timestamp == p->start_timestamp &&
1996 i->exit_timestamp == p->start_timestamp)
1997 /* Let's not show this twice */
2000 if (p->pid == i->control_pid)
2004 if (i->main_pid > 0 || i->control_pid > 0) {
2007 if (i->main_pid > 0) {
2008 printf("Main PID: %u", (unsigned) i->main_pid);
2012 get_process_name(i->main_pid, &t);
2017 } else if (i->exit_code > 0) {
2018 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2020 if (i->exit_code == CLD_EXITED) {
2023 printf("status=%i", i->exit_status);
2025 #ifdef HAVE_SYSV_COMPAT
2026 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
2028 if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
2033 printf("signal=%s", signal_to_string(i->exit_status));
2038 if (i->main_pid > 0 && i->control_pid > 0)
2041 if (i->control_pid > 0) {
2044 printf(" Control: %u", (unsigned) i->control_pid);
2046 get_process_name(i->control_pid, &t);
2057 printf("\t Status: \"%s\"\n", i->status_text);
2059 if (i->default_control_group) {
2062 printf("\t CGroup: %s\n", i->default_control_group);
2064 if (arg_transport != TRANSPORT_SSH) {
2065 if ((c = columns()) > 18)
2070 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
2074 if (i->need_daemon_reload)
2075 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2076 ansi_highlight(true),
2077 ansi_highlight(false),
2078 arg_user ? "--user" : "--system");
2081 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2083 switch (dbus_message_iter_get_arg_type(iter)) {
2085 case DBUS_TYPE_STRING: {
2088 dbus_message_iter_get_basic(iter, &s);
2091 if (streq(name, "Id"))
2093 else if (streq(name, "LoadState"))
2095 else if (streq(name, "ActiveState"))
2096 i->active_state = s;
2097 else if (streq(name, "SubState"))
2099 else if (streq(name, "Description"))
2101 else if (streq(name, "FragmentPath"))
2103 #ifdef HAVE_SYSV_COMPAT
2104 else if (streq(name, "SysVPath")) {
2109 else if (streq(name, "DefaultControlGroup"))
2110 i->default_control_group = s;
2111 else if (streq(name, "StatusText"))
2113 else if (streq(name, "SysFSPath"))
2115 else if (streq(name, "Where"))
2117 else if (streq(name, "What"))
2119 else if (streq(name, "Following"))
2126 case DBUS_TYPE_BOOLEAN: {
2129 dbus_message_iter_get_basic(iter, &b);
2131 if (streq(name, "Accept"))
2133 else if (streq(name, "NeedDaemonReload"))
2134 i->need_daemon_reload = b;
2135 else if (streq(name, "ConditionResult"))
2136 i->condition_result = b;
2141 case DBUS_TYPE_UINT32: {
2144 dbus_message_iter_get_basic(iter, &u);
2146 if (streq(name, "MainPID")) {
2148 i->main_pid = (pid_t) u;
2151 } else if (streq(name, "ControlPID"))
2152 i->control_pid = (pid_t) u;
2153 else if (streq(name, "ExecMainPID")) {
2155 i->main_pid = (pid_t) u;
2156 } else if (streq(name, "NAccepted"))
2158 else if (streq(name, "NConnections"))
2159 i->n_connections = u;
2164 case DBUS_TYPE_INT32: {
2167 dbus_message_iter_get_basic(iter, &j);
2169 if (streq(name, "ExecMainCode"))
2170 i->exit_code = (int) j;
2171 else if (streq(name, "ExecMainStatus"))
2172 i->exit_status = (int) j;
2177 case DBUS_TYPE_UINT64: {
2180 dbus_message_iter_get_basic(iter, &u);
2182 if (streq(name, "ExecMainStartTimestamp"))
2183 i->start_timestamp = (usec_t) u;
2184 else if (streq(name, "ExecMainExitTimestamp"))
2185 i->exit_timestamp = (usec_t) u;
2186 else if (streq(name, "ActiveEnterTimestamp"))
2187 i->active_enter_timestamp = (usec_t) u;
2188 else if (streq(name, "InactiveEnterTimestamp"))
2189 i->inactive_enter_timestamp = (usec_t) u;
2190 else if (streq(name, "InactiveExitTimestamp"))
2191 i->inactive_exit_timestamp = (usec_t) u;
2192 else if (streq(name, "ActiveExitTimestamp"))
2193 i->active_exit_timestamp = (usec_t) u;
2194 else if (streq(name, "ConditionTimestamp"))
2195 i->condition_timestamp = (usec_t) u;
2200 case DBUS_TYPE_ARRAY: {
2202 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2203 startswith(name, "Exec")) {
2204 DBusMessageIter sub;
2206 dbus_message_iter_recurse(iter, &sub);
2207 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2208 ExecStatusInfo *info;
2211 if (!(info = new0(ExecStatusInfo, 1)))
2214 if (!(info->name = strdup(name))) {
2219 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2224 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2226 dbus_message_iter_next(&sub);
2237 static int print_property(const char *name, DBusMessageIter *iter) {
2241 /* This is a low-level property printer, see
2242 * print_status_info() for the nicer output */
2244 if (arg_property && !strv_find(arg_property, name))
2247 switch (dbus_message_iter_get_arg_type(iter)) {
2249 case DBUS_TYPE_STRING: {
2251 dbus_message_iter_get_basic(iter, &s);
2253 if (arg_all || s[0])
2254 printf("%s=%s\n", name, s);
2259 case DBUS_TYPE_BOOLEAN: {
2261 dbus_message_iter_get_basic(iter, &b);
2262 printf("%s=%s\n", name, yes_no(b));
2267 case DBUS_TYPE_UINT64: {
2269 dbus_message_iter_get_basic(iter, &u);
2271 /* Yes, heuristics! But we can change this check
2272 * should it turn out to not be sufficient */
2274 if (endswith(name, "Timestamp")) {
2275 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
2277 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
2278 printf("%s=%s\n", name, strempty(t));
2279 } else if (strstr(name, "USec")) {
2280 char timespan[FORMAT_TIMESPAN_MAX];
2282 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
2284 printf("%s=%llu\n", name, (unsigned long long) u);
2289 case DBUS_TYPE_UINT32: {
2291 dbus_message_iter_get_basic(iter, &u);
2293 if (strstr(name, "UMask") || strstr(name, "Mode"))
2294 printf("%s=%04o\n", name, u);
2296 printf("%s=%u\n", name, (unsigned) u);
2301 case DBUS_TYPE_INT32: {
2303 dbus_message_iter_get_basic(iter, &i);
2305 printf("%s=%i\n", name, (int) i);
2309 case DBUS_TYPE_DOUBLE: {
2311 dbus_message_iter_get_basic(iter, &d);
2313 printf("%s=%g\n", name, d);
2317 case DBUS_TYPE_STRUCT: {
2318 DBusMessageIter sub;
2319 dbus_message_iter_recurse(iter, &sub);
2321 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2324 dbus_message_iter_get_basic(&sub, &u);
2327 printf("%s=%u\n", name, (unsigned) u);
2329 printf("%s=\n", name);
2332 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2335 dbus_message_iter_get_basic(&sub, &s);
2337 if (arg_all || s[0])
2338 printf("%s=%s\n", name, s);
2346 case DBUS_TYPE_ARRAY:
2348 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2349 DBusMessageIter sub;
2352 dbus_message_iter_recurse(iter, &sub);
2354 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2355 printf("%s=", name);
2357 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2360 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2361 dbus_message_iter_get_basic(&sub, &s);
2362 printf("%s%s", space ? " " : "", s);
2365 dbus_message_iter_next(&sub);
2373 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2374 DBusMessageIter sub;
2376 dbus_message_iter_recurse(iter, &sub);
2378 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2379 printf("%s=", name);
2381 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2384 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2385 dbus_message_iter_get_basic(&sub, &u);
2388 dbus_message_iter_next(&sub);
2396 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
2397 DBusMessageIter sub, sub2;
2399 dbus_message_iter_recurse(iter, &sub);
2400 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2404 dbus_message_iter_recurse(&sub, &sub2);
2406 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
2407 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
2408 printf("EnvironmentFile=%s (ignore=%s)\n", path, yes_no(ignore));
2410 dbus_message_iter_next(&sub);
2415 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2416 DBusMessageIter sub, sub2;
2418 dbus_message_iter_recurse(iter, &sub);
2419 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2420 const char *type, *path;
2422 dbus_message_iter_recurse(&sub, &sub2);
2424 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2425 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2426 printf("%s=%s\n", type, path);
2428 dbus_message_iter_next(&sub);
2433 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2434 DBusMessageIter sub, sub2;
2436 dbus_message_iter_recurse(iter, &sub);
2437 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2439 uint64_t value, next_elapse;
2441 dbus_message_iter_recurse(&sub, &sub2);
2443 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2444 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2445 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2446 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2448 printf("%s={ value=%s ; next_elapse=%s }\n",
2450 format_timespan(timespan1, sizeof(timespan1), value),
2451 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2454 dbus_message_iter_next(&sub);
2459 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2460 DBusMessageIter sub;
2462 dbus_message_iter_recurse(iter, &sub);
2463 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2464 ExecStatusInfo info;
2467 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2468 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2471 t = strv_join(info.argv, " ");
2473 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2477 yes_no(info.ignore),
2478 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2479 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2480 (unsigned) info. pid,
2481 sigchld_code_to_string(info.code),
2483 info.code == CLD_EXITED ? "" : "/",
2484 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2490 strv_free(info.argv);
2492 dbus_message_iter_next(&sub);
2502 printf("%s=[unprintable]\n", name);
2507 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2508 DBusMessage *m = NULL, *reply = NULL;
2509 const char *interface = "";
2512 DBusMessageIter iter, sub, sub2, sub3;
2513 UnitStatusInfo info;
2521 dbus_error_init(&error);
2523 if (!(m = dbus_message_new_method_call(
2524 "org.freedesktop.systemd1",
2526 "org.freedesktop.DBus.Properties",
2528 log_error("Could not allocate message.");
2533 if (!dbus_message_append_args(m,
2534 DBUS_TYPE_STRING, &interface,
2535 DBUS_TYPE_INVALID)) {
2536 log_error("Could not append arguments to message.");
2541 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2542 log_error("Failed to issue method call: %s", bus_error_message(&error));
2547 if (!dbus_message_iter_init(reply, &iter) ||
2548 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2549 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2550 log_error("Failed to parse reply.");
2555 dbus_message_iter_recurse(&iter, &sub);
2562 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2565 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2566 log_error("Failed to parse reply.");
2571 dbus_message_iter_recurse(&sub, &sub2);
2573 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2574 log_error("Failed to parse reply.");
2579 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2580 log_error("Failed to parse reply.");
2585 dbus_message_iter_recurse(&sub2, &sub3);
2587 if (show_properties)
2588 r = print_property(name, &sub3);
2590 r = status_property(name, &sub3, &info);
2593 log_error("Failed to parse reply.");
2598 dbus_message_iter_next(&sub);
2603 if (!show_properties)
2604 print_status_info(&info);
2606 if (!streq_ptr(info.active_state, "active") &&
2607 !streq_ptr(info.active_state, "reloading") &&
2608 streq(verb, "status"))
2609 /* According to LSB: "program not running" */
2612 while ((p = info.exec)) {
2613 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2614 exec_status_info_free(p);
2619 dbus_message_unref(m);
2622 dbus_message_unref(reply);
2624 dbus_error_free(&error);
2629 static int show(DBusConnection *bus, char **args, unsigned n) {
2630 DBusMessage *m = NULL, *reply = NULL;
2634 bool show_properties, new_line = false;
2639 dbus_error_init(&error);
2641 show_properties = !streq(args[0], "status");
2643 if (show_properties)
2644 pager_open_if_enabled();
2646 if (show_properties && n <= 1) {
2647 /* If not argument is specified inspect the manager
2650 ret = show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2654 for (i = 1; i < n; i++) {
2655 const char *path = NULL;
2658 if (safe_atou32(args[i], &id) < 0) {
2660 /* Interpret as unit name */
2662 if (!(m = dbus_message_new_method_call(
2663 "org.freedesktop.systemd1",
2664 "/org/freedesktop/systemd1",
2665 "org.freedesktop.systemd1.Manager",
2667 log_error("Could not allocate message.");
2672 if (!dbus_message_append_args(m,
2673 DBUS_TYPE_STRING, &args[i],
2674 DBUS_TYPE_INVALID)) {
2675 log_error("Could not append arguments to message.");
2680 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2682 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2683 log_error("Failed to issue method call: %s", bus_error_message(&error));
2688 dbus_error_free(&error);
2690 dbus_message_unref(m);
2691 if (!(m = dbus_message_new_method_call(
2692 "org.freedesktop.systemd1",
2693 "/org/freedesktop/systemd1",
2694 "org.freedesktop.systemd1.Manager",
2696 log_error("Could not allocate message.");
2701 if (!dbus_message_append_args(m,
2702 DBUS_TYPE_STRING, &args[i],
2703 DBUS_TYPE_INVALID)) {
2704 log_error("Could not append arguments to message.");
2709 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2710 log_error("Failed to issue method call: %s", bus_error_message(&error));
2712 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2713 ret = 4; /* According to LSB: "program or service status is unknown" */
2720 } else if (show_properties) {
2722 /* Interpret as job id */
2724 if (!(m = dbus_message_new_method_call(
2725 "org.freedesktop.systemd1",
2726 "/org/freedesktop/systemd1",
2727 "org.freedesktop.systemd1.Manager",
2729 log_error("Could not allocate message.");
2734 if (!dbus_message_append_args(m,
2735 DBUS_TYPE_UINT32, &id,
2736 DBUS_TYPE_INVALID)) {
2737 log_error("Could not append arguments to message.");
2742 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2743 log_error("Failed to issue method call: %s", bus_error_message(&error));
2749 /* Interpret as PID */
2751 if (!(m = dbus_message_new_method_call(
2752 "org.freedesktop.systemd1",
2753 "/org/freedesktop/systemd1",
2754 "org.freedesktop.systemd1.Manager",
2756 log_error("Could not allocate message.");
2761 if (!dbus_message_append_args(m,
2762 DBUS_TYPE_UINT32, &id,
2763 DBUS_TYPE_INVALID)) {
2764 log_error("Could not append arguments to message.");
2769 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2770 log_error("Failed to issue method call: %s", bus_error_message(&error));
2776 if (!dbus_message_get_args(reply, &error,
2777 DBUS_TYPE_OBJECT_PATH, &path,
2778 DBUS_TYPE_INVALID)) {
2779 log_error("Failed to parse reply: %s", bus_error_message(&error));
2784 if ((r = show_one(args[0], bus, path, show_properties, &new_line)) != 0)
2787 dbus_message_unref(m);
2788 dbus_message_unref(reply);
2794 dbus_message_unref(m);
2797 dbus_message_unref(reply);
2799 dbus_error_free(&error);
2804 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2806 DBusMessage *m = NULL, *reply = NULL;
2811 dbus_error_init(&error);
2813 log_debug("Got D-Bus request: %s.%s() on %s",
2814 dbus_message_get_interface(message),
2815 dbus_message_get_member(message),
2816 dbus_message_get_path(message));
2818 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2819 log_error("Warning! D-Bus connection terminated.");
2820 dbus_connection_close(connection);
2822 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2823 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2824 const char *id, *path;
2826 if (!dbus_message_get_args(message, &error,
2827 DBUS_TYPE_STRING, &id,
2828 DBUS_TYPE_OBJECT_PATH, &path,
2830 log_error("Failed to parse message: %s", bus_error_message(&error));
2831 else if (streq(dbus_message_get_member(message), "UnitNew"))
2832 printf("Unit %s added.\n", id);
2834 printf("Unit %s removed.\n", id);
2836 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew")) {
2840 if (!dbus_message_get_args(message, &error,
2841 DBUS_TYPE_UINT32, &id,
2842 DBUS_TYPE_OBJECT_PATH, &path,
2844 log_error("Failed to parse message: %s", bus_error_message(&error));
2846 printf("Job %u added.\n", id);
2849 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2851 const char *path, *result;
2853 if (!dbus_message_get_args(message, &error,
2854 DBUS_TYPE_UINT32, &id,
2855 DBUS_TYPE_OBJECT_PATH, &path,
2856 DBUS_TYPE_STRING, &result,
2858 log_error("Failed to parse message: %s", bus_error_message(&error));
2860 printf("Job %u removed (result=%s).\n", id, result);
2863 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2865 const char *path, *interface, *property = "Id";
2866 DBusMessageIter iter, sub;
2868 path = dbus_message_get_path(message);
2870 if (!dbus_message_get_args(message, &error,
2871 DBUS_TYPE_STRING, &interface,
2872 DBUS_TYPE_INVALID)) {
2873 log_error("Failed to parse message: %s", bus_error_message(&error));
2877 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2878 !streq(interface, "org.freedesktop.systemd1.Unit"))
2881 if (!(m = dbus_message_new_method_call(
2882 "org.freedesktop.systemd1",
2884 "org.freedesktop.DBus.Properties",
2886 log_error("Could not allocate message.");
2890 if (!dbus_message_append_args(m,
2891 DBUS_TYPE_STRING, &interface,
2892 DBUS_TYPE_STRING, &property,
2893 DBUS_TYPE_INVALID)) {
2894 log_error("Could not append arguments to message.");
2898 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2899 log_error("Failed to issue method call: %s", bus_error_message(&error));
2903 if (!dbus_message_iter_init(reply, &iter) ||
2904 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2905 log_error("Failed to parse reply.");
2909 dbus_message_iter_recurse(&iter, &sub);
2911 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2914 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2915 log_error("Failed to parse reply.");
2919 dbus_message_iter_get_basic(&sub, &id);
2920 printf("Unit %s changed.\n", id);
2924 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2925 log_error("Failed to parse reply.");
2929 dbus_message_iter_get_basic(&sub, &id);
2930 printf("Job %u changed.\n", id);
2936 dbus_message_unref(m);
2939 dbus_message_unref(reply);
2941 dbus_error_free(&error);
2942 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2946 dbus_message_unref(m);
2949 dbus_message_unref(reply);
2951 dbus_error_free(&error);
2952 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2955 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2956 DBusMessage *m = NULL, *reply = NULL;
2960 dbus_error_init(&error);
2963 dbus_bus_add_match(bus,
2965 "sender='org.freedesktop.systemd1',"
2966 "interface='org.freedesktop.systemd1.Manager',"
2967 "path='/org/freedesktop/systemd1'",
2970 if (dbus_error_is_set(&error)) {
2971 log_error("Failed to add match: %s", bus_error_message(&error));
2976 dbus_bus_add_match(bus,
2978 "sender='org.freedesktop.systemd1',"
2979 "interface='org.freedesktop.DBus.Properties',"
2980 "member='PropertiesChanged'",
2983 if (dbus_error_is_set(&error)) {
2984 log_error("Failed to add match: %s", bus_error_message(&error));
2990 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2991 log_error("Failed to add filter.");
2996 if (!(m = dbus_message_new_method_call(
2997 "org.freedesktop.systemd1",
2998 "/org/freedesktop/systemd1",
2999 "org.freedesktop.systemd1.Manager",
3001 log_error("Could not allocate message.");
3006 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3007 log_error("Failed to issue method call: %s", bus_error_message(&error));
3012 while (dbus_connection_read_write_dispatch(bus, -1))
3019 /* This is slightly dirty, since we don't undo the filter or the matches. */
3022 dbus_message_unref(m);
3025 dbus_message_unref(reply);
3027 dbus_error_free(&error);
3032 static int dump(DBusConnection *bus, char **args, unsigned n) {
3033 DBusMessage *m = NULL, *reply = NULL;
3038 dbus_error_init(&error);
3040 pager_open_if_enabled();
3042 if (!(m = dbus_message_new_method_call(
3043 "org.freedesktop.systemd1",
3044 "/org/freedesktop/systemd1",
3045 "org.freedesktop.systemd1.Manager",
3047 log_error("Could not allocate message.");
3051 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3052 log_error("Failed to issue method call: %s", bus_error_message(&error));
3057 if (!dbus_message_get_args(reply, &error,
3058 DBUS_TYPE_STRING, &text,
3059 DBUS_TYPE_INVALID)) {
3060 log_error("Failed to parse reply: %s", bus_error_message(&error));
3065 fputs(text, stdout);
3071 dbus_message_unref(m);
3074 dbus_message_unref(reply);
3076 dbus_error_free(&error);
3081 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
3082 DBusMessage *m = NULL, *reply = NULL;
3085 const char *name = "", *path, *id;
3086 dbus_bool_t cleanup = FALSE;
3087 DBusMessageIter iter, sub;
3089 *interface = "org.freedesktop.systemd1.Unit",
3092 dbus_error_init(&error);
3094 if (!(m = dbus_message_new_method_call(
3095 "org.freedesktop.systemd1",
3096 "/org/freedesktop/systemd1",
3097 "org.freedesktop.systemd1.Manager",
3098 "CreateSnapshot"))) {
3099 log_error("Could not allocate message.");
3106 if (!dbus_message_append_args(m,
3107 DBUS_TYPE_STRING, &name,
3108 DBUS_TYPE_BOOLEAN, &cleanup,
3109 DBUS_TYPE_INVALID)) {
3110 log_error("Could not append arguments to message.");
3115 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3116 log_error("Failed to issue method call: %s", bus_error_message(&error));
3121 if (!dbus_message_get_args(reply, &error,
3122 DBUS_TYPE_OBJECT_PATH, &path,
3123 DBUS_TYPE_INVALID)) {
3124 log_error("Failed to parse reply: %s", bus_error_message(&error));
3129 dbus_message_unref(m);
3130 if (!(m = dbus_message_new_method_call(
3131 "org.freedesktop.systemd1",
3133 "org.freedesktop.DBus.Properties",
3135 log_error("Could not allocate message.");
3139 if (!dbus_message_append_args(m,
3140 DBUS_TYPE_STRING, &interface,
3141 DBUS_TYPE_STRING, &property,
3142 DBUS_TYPE_INVALID)) {
3143 log_error("Could not append arguments to message.");
3148 dbus_message_unref(reply);
3149 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3150 log_error("Failed to issue method call: %s", bus_error_message(&error));
3155 if (!dbus_message_iter_init(reply, &iter) ||
3156 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3157 log_error("Failed to parse reply.");
3162 dbus_message_iter_recurse(&iter, &sub);
3164 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3165 log_error("Failed to parse reply.");
3170 dbus_message_iter_get_basic(&sub, &id);
3178 dbus_message_unref(m);
3181 dbus_message_unref(reply);
3183 dbus_error_free(&error);
3188 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
3189 DBusMessage *m = NULL, *reply = NULL;
3197 dbus_error_init(&error);
3199 for (i = 1; i < n; i++) {
3200 const char *path = NULL;
3202 if (!(m = dbus_message_new_method_call(
3203 "org.freedesktop.systemd1",
3204 "/org/freedesktop/systemd1",
3205 "org.freedesktop.systemd1.Manager",
3207 log_error("Could not allocate message.");
3212 if (!dbus_message_append_args(m,
3213 DBUS_TYPE_STRING, &args[i],
3214 DBUS_TYPE_INVALID)) {
3215 log_error("Could not append arguments to message.");
3220 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3221 log_error("Failed to issue method call: %s", bus_error_message(&error));
3226 if (!dbus_message_get_args(reply, &error,
3227 DBUS_TYPE_OBJECT_PATH, &path,
3228 DBUS_TYPE_INVALID)) {
3229 log_error("Failed to parse reply: %s", bus_error_message(&error));
3234 dbus_message_unref(m);
3235 if (!(m = dbus_message_new_method_call(
3236 "org.freedesktop.systemd1",
3238 "org.freedesktop.systemd1.Snapshot",
3240 log_error("Could not allocate message.");
3245 dbus_message_unref(reply);
3246 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3247 log_error("Failed to issue method call: %s", bus_error_message(&error));
3252 dbus_message_unref(m);
3253 dbus_message_unref(reply);
3261 dbus_message_unref(m);
3264 dbus_message_unref(reply);
3266 dbus_error_free(&error);
3271 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
3272 DBusMessage *m = NULL, *reply = NULL;
3277 dbus_error_init(&error);
3279 if (arg_action == ACTION_RELOAD)
3281 else if (arg_action == ACTION_REEXEC)
3282 method = "Reexecute";
3284 assert(arg_action == ACTION_SYSTEMCTL);
3287 streq(args[0], "clear-jobs") ||
3288 streq(args[0], "cancel") ? "ClearJobs" :
3289 streq(args[0], "daemon-reexec") ? "Reexecute" :
3290 streq(args[0], "reset-failed") ? "ResetFailed" :
3291 streq(args[0], "halt") ? "Halt" :
3292 streq(args[0], "poweroff") ? "PowerOff" :
3293 streq(args[0], "reboot") ? "Reboot" :
3294 streq(args[0], "kexec") ? "KExec" :
3295 streq(args[0], "exit") ? "Exit" :
3296 /* "daemon-reload" */ "Reload";
3299 if (!(m = dbus_message_new_method_call(
3300 "org.freedesktop.systemd1",
3301 "/org/freedesktop/systemd1",
3302 "org.freedesktop.systemd1.Manager",
3304 log_error("Could not allocate message.");
3308 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3310 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3311 /* There's always a fallback possible for
3312 * legacy actions. */
3317 if (streq(method, "Reexecute") && dbus_error_has_name(&error, DBUS_ERROR_NO_REPLY)) {
3318 /* On reexecution, we expect a disconnect, not
3324 log_error("Failed to issue method call: %s", bus_error_message(&error));
3333 dbus_message_unref(m);
3336 dbus_message_unref(reply);
3338 dbus_error_free(&error);
3343 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3344 DBusMessage *m = NULL, *reply = NULL;
3350 dbus_error_init(&error);
3353 return daemon_reload(bus, args, n);
3355 for (i = 1; i < n; i++) {
3357 if (!(m = dbus_message_new_method_call(
3358 "org.freedesktop.systemd1",
3359 "/org/freedesktop/systemd1",
3360 "org.freedesktop.systemd1.Manager",
3361 "ResetFailedUnit"))) {
3362 log_error("Could not allocate message.");
3367 if (!dbus_message_append_args(m,
3368 DBUS_TYPE_STRING, args + i,
3369 DBUS_TYPE_INVALID)) {
3370 log_error("Could not append arguments to message.");
3375 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3376 log_error("Failed to issue method call: %s", bus_error_message(&error));
3381 dbus_message_unref(m);
3382 dbus_message_unref(reply);
3390 dbus_message_unref(m);
3393 dbus_message_unref(reply);
3395 dbus_error_free(&error);
3400 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3401 DBusMessage *m = NULL, *reply = NULL;
3403 DBusMessageIter iter, sub, sub2;
3406 *interface = "org.freedesktop.systemd1.Manager",
3407 *property = "Environment";
3409 dbus_error_init(&error);
3411 pager_open_if_enabled();
3413 if (!(m = dbus_message_new_method_call(
3414 "org.freedesktop.systemd1",
3415 "/org/freedesktop/systemd1",
3416 "org.freedesktop.DBus.Properties",
3418 log_error("Could not allocate message.");
3422 if (!dbus_message_append_args(m,
3423 DBUS_TYPE_STRING, &interface,
3424 DBUS_TYPE_STRING, &property,
3425 DBUS_TYPE_INVALID)) {
3426 log_error("Could not append arguments to message.");
3431 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3432 log_error("Failed to issue method call: %s", bus_error_message(&error));
3437 if (!dbus_message_iter_init(reply, &iter) ||
3438 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3439 log_error("Failed to parse reply.");
3444 dbus_message_iter_recurse(&iter, &sub);
3446 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3447 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3448 log_error("Failed to parse reply.");
3453 dbus_message_iter_recurse(&sub, &sub2);
3455 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3458 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3459 log_error("Failed to parse reply.");
3464 dbus_message_iter_get_basic(&sub2, &text);
3465 printf("%s\n", text);
3467 dbus_message_iter_next(&sub2);
3474 dbus_message_unref(m);
3477 dbus_message_unref(reply);
3479 dbus_error_free(&error);
3484 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3485 DBusMessage *m = NULL, *reply = NULL;
3489 DBusMessageIter iter, sub;
3492 dbus_error_init(&error);
3494 method = streq(args[0], "set-environment")
3496 : "UnsetEnvironment";
3498 if (!(m = dbus_message_new_method_call(
3499 "org.freedesktop.systemd1",
3500 "/org/freedesktop/systemd1",
3501 "org.freedesktop.systemd1.Manager",
3504 log_error("Could not allocate message.");
3508 dbus_message_iter_init_append(m, &iter);
3510 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3511 log_error("Could not append arguments to message.");
3516 for (i = 1; i < n; i++)
3517 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3518 log_error("Could not append arguments to message.");
3523 if (!dbus_message_iter_close_container(&iter, &sub)) {
3524 log_error("Could not append arguments to message.");
3529 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3530 log_error("Failed to issue method call: %s", bus_error_message(&error));
3539 dbus_message_unref(m);
3542 dbus_message_unref(reply);
3544 dbus_error_free(&error);
3557 static Hashmap *will_install = NULL, *have_installed = NULL;
3558 static Set *remove_symlinks_to = NULL;
3559 static unsigned n_symlinks = 0;
3561 static void install_info_free(InstallInfo *i) {
3566 strv_free(i->aliases);
3567 strv_free(i->wanted_by);
3571 static void install_info_hashmap_free(Hashmap *m) {
3574 while ((i = hashmap_steal_first(m)))
3575 install_info_free(i);
3580 static int install_info_add(const char *name) {
3584 assert(will_install);
3586 if (!unit_name_is_valid_no_type(name, true)) {
3587 log_warning("Unit name %s is not a valid unit name.", name);
3591 if (hashmap_get(have_installed, name) ||
3592 hashmap_get(will_install, name))
3595 if (!(i = new0(InstallInfo, 1))) {
3600 if (!(i->name = strdup(name))) {
3605 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3612 install_info_free(i);
3617 static int config_parse_also(
3618 const char *filename,
3620 const char *section,
3635 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3639 if (!(n = strndup(w, l)))
3642 if ((r = install_info_add(n)) < 0) {
3643 log_warning("Cannot install unit %s: %s", n, strerror(-r));
3654 static int mark_symlink_for_removal(const char *p) {
3659 assert(path_is_absolute(p));
3661 if (!remove_symlinks_to)
3664 if (!(n = strdup(p)))
3667 path_kill_slashes(n);
3669 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3671 return r == -EEXIST ? 0 : r;
3677 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3686 if (!(d = fdopendir(fd))) {
3687 close_nointr_nofail(fd);
3693 while ((de = readdir(d))) {
3694 bool is_dir = false, is_link = false;
3696 if (ignore_file(de->d_name))
3699 if (de->d_type == DT_LNK)
3701 else if (de->d_type == DT_DIR)
3703 else if (de->d_type == DT_UNKNOWN) {
3706 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3707 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3714 is_link = S_ISLNK(st.st_mode);
3715 is_dir = S_ISDIR(st.st_mode);
3723 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3724 log_error("Failed to open %s/%s: %m", root, de->d_name);
3731 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3732 log_error("Failed to allocate directory string.");
3733 close_nointr_nofail(nfd);
3738 /* This will close nfd, regardless whether it succeeds or not */
3739 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3745 } else if (is_link) {
3749 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3750 log_error("Failed to allocate symlink string.");
3755 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3756 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3764 if ((c = canonicalize_file_name(dest))) {
3765 /* This might fail if the destination
3766 * is already removed */
3772 path_kill_slashes(dest);
3773 if (set_get(remove_symlinks_to, dest)) {
3776 log_info("rm '%s'", p);
3778 if (unlink(p) < 0) {
3779 log_error("Cannot unlink symlink %s: %m", p);
3784 rmdir_parents(p, config_path);
3785 path_kill_slashes(p);
3787 if (!set_get(remove_symlinks_to, p)) {
3789 if ((r = mark_symlink_for_removal(p)) < 0) {
3808 static int remove_marked_symlinks(const char *config_path) {
3812 assert(config_path);
3814 if (set_size(remove_symlinks_to) <= 0)
3817 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3824 if ((cfd = dup(fd)) < 0) {
3829 /* This takes possession of cfd and closes it */
3830 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3836 close_nointr_nofail(fd);
3841 static int create_symlink(const char *verb, const char *orig_old_path, const char *new_path) {
3843 const char *old_path;
3846 old_path = orig_old_path+strlen(arg_root);
3848 old_path = orig_old_path;
3854 if (streq(verb, "enable")) {
3857 mkdir_parents(new_path, 0755);
3859 if (symlink(old_path, new_path) >= 0) {
3862 log_info("ln -s '%s' '%s'", old_path, new_path);
3867 if (errno != EEXIST) {
3868 log_error("Cannot link %s to %s: %m", old_path, new_path);
3872 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3874 if (errno == EINVAL) {
3875 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3879 log_error("readlink() failed: %s", strerror(-r));
3883 if (streq(dest, old_path)) {
3889 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3898 log_info("ln -s '%s' '%s'", old_path, new_path);
3900 if (symlink(old_path, new_path) >= 0)
3903 log_error("Cannot link %s to %s: %m", old_path, new_path);
3906 } else if (streq(verb, "disable")) {
3909 if ((r = mark_symlink_for_removal(old_path)) < 0)
3912 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3913 if (errno == ENOENT)
3916 if (errno == EINVAL) {
3917 log_warning("File %s not a symlink, ignoring.", old_path);
3921 log_error("readlink() failed: %s", strerror(-r));
3925 if (!streq(dest, old_path)) {
3926 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3933 if ((r = mark_symlink_for_removal(new_path)) < 0)
3937 log_info("rm '%s'", new_path);
3939 if (unlink(new_path) >= 0)
3942 log_error("Cannot unlink %s: %m", new_path);
3945 } else if (streq(verb, "is-enabled")) {
3948 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3950 if (errno == ENOENT || errno == EINVAL)
3953 log_error("readlink() failed: %s", strerror(-r));
3957 if (streq(dest, old_path)) {
3966 assert_not_reached("Unknown action.");
3969 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3971 char *alias_path = NULL;
3976 assert(config_path);
3978 STRV_FOREACH(s, i->aliases) {
3981 if (!(alias_path = path_make_absolute(*s, config_path))) {
3982 log_error("Out of memory");
3987 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3990 if (streq(verb, "disable"))
3991 rmdir_parents(alias_path, config_path);
4001 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
4003 char *alias_path = NULL;
4008 assert(config_path);
4010 STRV_FOREACH(s, i->wanted_by) {
4011 if (!unit_name_is_valid_no_type(*s, true)) {
4012 log_error("Invalid name %s.", *s);
4020 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
4021 log_error("Out of memory");
4026 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
4029 if (streq(verb, "disable"))
4030 rmdir_parents(alias_path, config_path);
4041 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
4043 const ConfigItem items[] = {
4044 { "Alias", config_parse_strv, 0, &i->aliases, "Install" },
4045 { "WantedBy", config_parse_strv, 0, &i->wanted_by, "Install" },
4046 { "Also", config_parse_also, 0, NULL, "Install" },
4048 { NULL, NULL, 0, NULL, NULL }
4052 char *filename = NULL;
4059 STRV_FOREACH(p, paths->unit_path) {
4061 char *path, *should_free;
4064 should_free = path = strappend(arg_root, *p);
4070 if (!(filename = path_make_absolute(i->name, path))) {
4071 log_error("Out of memory");
4078 /* Ensure that we don't follow symlinks */
4079 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
4080 if ((f = fdopen(fd, "re")))
4083 if (errno == ELOOP) {
4084 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
4089 if (errno != ENOENT) {
4090 log_error("Failed to open %s: %m", filename);
4100 #if (defined(TARGET_FEDORA) || defined(TARGET_MANDRIVA) || defined(TARGET_SUSE) || defined(TARGET_MEEGO) || defined(TARGET_ALTLINUX)) && defined (HAVE_SYSV_COMPAT)
4102 if (endswith(i->name, ".service")) {
4106 if (asprintf(&sysv, SYSTEM_SYSVINIT_PATH "/%s", i->name) < 0) {
4107 log_error("Out of memory");
4111 sysv[strlen(sysv) - sizeof(".service") + 1] = 0;
4115 tmp_path = strappend (arg_root, sysv);
4116 exists = access (tmp_path, F_OK) >= 0;
4119 exists = access(sysv, F_OK) >= 0;
4125 const char *argv[] = {
4133 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", i->name);
4135 argv[1] = file_name_from_path(sysv);
4137 streq(verb, "enable") ? "on" :
4138 streq(verb, "disable") ? "off" : "--level=5";
4140 argv[3] = strappend("--root=", arg_root);
4142 log_info("Executing %s %s %s %s", argv[0], argv[1], strempty(argv[2]), strempty(argv[3]));
4144 if ((pid = fork()) < 0) {
4145 log_error("Failed to fork: %m");
4148 } else if (pid == 0) {
4149 execv(argv[0], (char**) argv);
4150 _exit(EXIT_FAILURE);
4155 if ((r = wait_for_terminate(pid, &status)) < 0)
4158 if (status.si_code == CLD_EXITED) {
4160 if (streq(verb, "is-enabled"))
4161 return status.si_status == 0 ? 1 : 0;
4163 if (status.si_status == 0)
4166 return status.si_status == 0 ? 0 : -EINVAL;
4177 log_error("Couldn't find %s.", i->name);
4183 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
4188 /* Consider unit files stored in /lib and /usr always enabled
4189 * if they have no [Install] data. */
4190 if (streq(verb, "is-enabled") &&
4191 strv_isempty(i->aliases) &&
4192 strv_isempty(i->wanted_by) &&
4193 !path_startswith(filename, "/etc")) {
4198 n_symlinks += strv_length(i->aliases);
4199 n_symlinks += strv_length(i->wanted_by);
4203 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
4206 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
4209 if ((r = mark_symlink_for_removal(filename)) < 0)
4212 if ((r = remove_marked_symlinks(config_path)) < 0)
4218 static char *get_config_path(void) {
4221 if (arg_user && arg_global)
4222 ret = strdup(USER_CONFIG_UNIT_PATH);
4225 if (user_config_home(&ret) < 0)
4229 ret = strdup(SYSTEM_CONFIG_UNIT_PATH);
4232 p = strappend (arg_root, ret);
4239 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
4243 char *config_path = NULL;
4246 const char *verb = args[0];
4248 dbus_error_init(&error);
4251 if ((r = lookup_paths_init(&paths, arg_user ? MANAGER_USER : MANAGER_SYSTEM)) < 0) {
4252 log_error("Failed to determine lookup paths: %s", strerror(-r));
4256 if (!(config_path = get_config_path())) {
4257 log_error("Failed to determine config path");
4262 will_install = hashmap_new(string_hash_func, string_compare_func);
4263 have_installed = hashmap_new(string_hash_func, string_compare_func);
4265 if (!will_install || !have_installed) {
4266 log_error("Failed to allocate unit sets.");
4271 if (!arg_defaults && streq(verb, "disable"))
4272 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
4273 log_error("Failed to allocate symlink sets.");
4278 for (j = 1; j < n; j++)
4279 if ((r = install_info_add(args[j])) < 0) {
4280 log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
4286 while ((i = hashmap_first(will_install))) {
4289 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
4291 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
4299 /* In test mode and found something */
4305 if (streq(verb, "is-enabled"))
4306 r = r > 0 ? 0 : -ENOENT;
4308 if (n_symlinks <= 0)
4309 log_warning("Unit files contain no applicable installation information. Ignoring.");
4312 /* Don't try to reload anything if the user asked us to not do this */
4314 /* Don't try to reload anything when updating a unit globally */
4316 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
4317 (arg_user || sd_booted() > 0) &&
4318 /* Don't try to reload anything if we are running in a chroot environment */
4319 (arg_user || running_in_chroot() <= 0 || arg_root) ) {
4322 if ((q = daemon_reload(bus, args, n)) < 0)
4328 install_info_hashmap_free(will_install);
4329 install_info_hashmap_free(have_installed);
4331 set_free_free(remove_symlinks_to);
4333 lookup_paths_free(&paths);
4340 static int systemctl_help(void) {
4342 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4343 "Send control commands to or query the systemd manager.\n\n"
4344 " -h --help Show this help\n"
4345 " --version Show package version\n"
4346 " -t --type=TYPE List only units of a particular type\n"
4347 " -p --property=NAME Show only properties by this name\n"
4348 " -a --all Show all units/properties, including dead/empty ones\n"
4349 " --failed Show only failed units\n"
4350 " --full Don't ellipsize unit names on output\n"
4351 " --fail When queueing a new job, fail if conflicting jobs are\n"
4353 " --ignore-dependencies\n"
4354 " When queueing a new job, ignore all its dependencies\n"
4355 " --kill-mode=MODE How to send signal\n"
4356 " --kill-who=WHO Who to send signal to\n"
4357 " -s --signal=SIGNAL Which signal to send\n"
4358 " -H --host=[user@]host\n"
4359 " Show information for remote host\n"
4360 " -P --privileged Acquire privileges before execution\n"
4361 " -q --quiet Suppress output\n"
4362 " --no-block Do not wait until operation finished\n"
4363 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4364 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4366 " --no-pager Do not pipe output into a pager.\n"
4367 " --no-ask-password\n"
4368 " Do not ask for system passwords\n"
4369 " --order When generating graph for dot, show only order\n"
4370 " --require When generating graph for dot, show only requirement\n"
4371 " --root=path Use <root> as the root file system\n"
4372 " --system Connect to system manager\n"
4373 " --user Connect to user service manager\n"
4374 " --global Enable/disable unit files globally\n"
4375 " -f --force When enabling unit files, override existing symlinks\n"
4376 " When shutting down, execute action immediately\n"
4377 " --defaults When disabling unit files, remove default symlinks only\n\n"
4379 " list-units List units\n"
4380 " start [NAME...] Start (activate) one or more units\n"
4381 " stop [NAME...] Stop (deactivate) one or more units\n"
4382 " reload [NAME...] Reload one or more units\n"
4383 " restart [NAME...] Start or restart one or more units\n"
4384 " try-restart [NAME...] Restart one or more units if active\n"
4385 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4386 " otherwise start or restart\n"
4387 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4388 " otherwise restart if active\n"
4389 " isolate [NAME] Start one unit and stop all others\n"
4390 " kill [NAME...] Send signal to processes of a unit\n"
4391 " is-active [NAME...] Check whether units are active\n"
4392 " status [NAME...|PID...] Show runtime status of one or more units\n"
4393 " show [NAME...|JOB...] Show properties of one or more\n"
4394 " units/jobs or the manager\n"
4395 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4397 " enable [NAME...] Enable one or more unit files\n"
4398 " disable [NAME...] Disable one or more unit files\n"
4399 " is-enabled [NAME...] Check whether unit files are enabled\n"
4400 " load [NAME...] Load one or more units\n"
4401 " list-jobs List jobs\n"
4402 " cancel [JOB...] Cancel all, one, or more jobs\n"
4403 " monitor Monitor unit/job changes\n"
4404 " dump Dump server status\n"
4405 " dot Dump dependency graph for dot(1)\n"
4406 " snapshot [NAME] Create a snapshot\n"
4407 " delete [NAME...] Remove one or more snapshots\n"
4408 " daemon-reload Reload systemd manager configuration\n"
4409 " daemon-reexec Reexecute systemd manager\n"
4410 " show-environment Dump environment\n"
4411 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4412 " unset-environment [NAME...] Unset one or more environment variables\n"
4413 " default Enter system default mode\n"
4414 " rescue Enter system rescue mode\n"
4415 " emergency Enter system emergency mode\n"
4416 " halt Shut down and halt the system\n"
4417 " poweroff Shut down and power-off the system\n"
4418 " reboot Shut down and reboot the system\n"
4419 " kexec Shut down and reboot the system with kexec\n"
4420 " exit Ask for user instance termination\n",
4421 program_invocation_short_name);
4426 static int halt_help(void) {
4428 printf("%s [OPTIONS...]\n\n"
4429 "%s the system.\n\n"
4430 " --help Show this help\n"
4431 " --halt Halt the machine\n"
4432 " -p --poweroff Switch off the machine\n"
4433 " --reboot Reboot the machine\n"
4434 " -f --force Force immediate halt/power-off/reboot\n"
4435 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4436 " -d --no-wtmp Don't write wtmp record\n"
4437 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4438 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4439 program_invocation_short_name,
4440 arg_action == ACTION_REBOOT ? "Reboot" :
4441 arg_action == ACTION_POWEROFF ? "Power off" :
4447 static int shutdown_help(void) {
4449 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4450 "Shut down the system.\n\n"
4451 " --help Show this help\n"
4452 " -H --halt Halt the machine\n"
4453 " -P --poweroff Power-off the machine\n"
4454 " -r --reboot Reboot the machine\n"
4455 " -h Equivalent to --poweroff, overriden by --halt\n"
4456 " -k Don't halt/power-off/reboot, just send warnings\n"
4457 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4458 " -c Cancel a pending shutdown\n",
4459 program_invocation_short_name);
4464 static int telinit_help(void) {
4466 printf("%s [OPTIONS...] {COMMAND}\n\n"
4467 "Send control commands to the init daemon.\n\n"
4468 " --help Show this help\n"
4469 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4471 " 0 Power-off the machine\n"
4472 " 6 Reboot the machine\n"
4473 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4474 " 1, s, S Enter rescue mode\n"
4475 " q, Q Reload init daemon configuration\n"
4476 " u, U Reexecute init daemon\n",
4477 program_invocation_short_name);
4482 static int runlevel_help(void) {
4484 printf("%s [OPTIONS...]\n\n"
4485 "Prints the previous and current runlevel of the init system.\n\n"
4486 " --help Show this help\n",
4487 program_invocation_short_name);
4492 static int systemctl_parse_argv(int argc, char *argv[]) {
4496 ARG_IGNORE_DEPENDENCIES,
4512 ARG_NO_ASK_PASSWORD,
4516 static const struct option options[] = {
4517 { "help", no_argument, NULL, 'h' },
4518 { "version", no_argument, NULL, ARG_VERSION },
4519 { "type", required_argument, NULL, 't' },
4520 { "property", required_argument, NULL, 'p' },
4521 { "all", no_argument, NULL, 'a' },
4522 { "failed", no_argument, NULL, ARG_FAILED },
4523 { "full", no_argument, NULL, ARG_FULL },
4524 { "fail", no_argument, NULL, ARG_FAIL },
4525 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4526 { "user", no_argument, NULL, ARG_USER },
4527 { "system", no_argument, NULL, ARG_SYSTEM },
4528 { "global", no_argument, NULL, ARG_GLOBAL },
4529 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4530 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4531 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4532 { "quiet", no_argument, NULL, 'q' },
4533 { "order", no_argument, NULL, ARG_ORDER },
4534 { "require", no_argument, NULL, ARG_REQUIRE },
4535 { "root", required_argument, NULL, ARG_ROOT },
4536 { "force", no_argument, NULL, 'f' },
4537 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4538 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4539 { "kill-mode", required_argument, NULL, ARG_KILL_MODE },
4540 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4541 { "signal", required_argument, NULL, 's' },
4542 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4543 { "host", required_argument, NULL, 'H' },
4544 { "privileged",no_argument, NULL, 'P' },
4545 { NULL, 0, NULL, 0 }
4553 /* Only when running as systemctl we ask for passwords */
4554 arg_ask_password = true;
4556 while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:P", options, NULL)) >= 0) {
4565 puts(PACKAGE_STRING);
4567 puts(SYSTEMD_FEATURES);
4577 if (!(l = strv_append(arg_property, optarg)))
4580 strv_free(arg_property);
4583 /* If the user asked for a particular
4584 * property, show it to him, even if it is
4595 arg_job_mode = "fail";
4598 case ARG_IGNORE_DEPENDENCIES:
4599 arg_job_mode = "ignore-dependencies";
4611 arg_no_block = true;
4615 arg_no_pager = true;
4623 arg_dot = DOT_ORDER;
4627 arg_dot = DOT_REQUIRE;
4651 arg_no_reload = true;
4660 arg_defaults = true;
4664 arg_kill_who = optarg;
4668 arg_kill_mode = optarg;
4672 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4673 log_error("Failed to parse signal string %s.", optarg);
4678 case ARG_NO_ASK_PASSWORD:
4679 arg_ask_password = false;
4683 arg_transport = TRANSPORT_POLKIT;
4687 arg_transport = TRANSPORT_SSH;
4695 log_error("Unknown option code %c", c);
4700 if (arg_transport != TRANSPORT_NORMAL && arg_user) {
4701 log_error("Cannot access user instance remotely.");
4708 static int halt_parse_argv(int argc, char *argv[]) {
4717 static const struct option options[] = {
4718 { "help", no_argument, NULL, ARG_HELP },
4719 { "halt", no_argument, NULL, ARG_HALT },
4720 { "poweroff", no_argument, NULL, 'p' },
4721 { "reboot", no_argument, NULL, ARG_REBOOT },
4722 { "force", no_argument, NULL, 'f' },
4723 { "wtmp-only", no_argument, NULL, 'w' },
4724 { "no-wtmp", no_argument, NULL, 'd' },
4725 { "no-sync", no_argument, NULL, 'n' },
4726 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4727 { NULL, 0, NULL, 0 }
4735 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4736 if (runlevel == '0' || runlevel == '6')
4737 arg_immediate = true;
4739 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4747 arg_action = ACTION_HALT;
4751 if (arg_action != ACTION_REBOOT)
4752 arg_action = ACTION_POWEROFF;
4756 arg_action = ACTION_REBOOT;
4760 arg_immediate = true;
4781 /* Compatibility nops */
4788 log_error("Unknown option code %c", c);
4793 if (optind < argc) {
4794 log_error("Too many arguments.");
4801 static int parse_time_spec(const char *t, usec_t *_u) {
4805 if (streq(t, "now"))
4807 else if (!strchr(t, ':')) {
4810 if (safe_atou64(t, &u) < 0)
4813 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4822 hour = strtol(t, &e, 10);
4823 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4826 minute = strtol(e+1, &e, 10);
4827 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4830 n = now(CLOCK_REALTIME);
4831 s = (time_t) (n / USEC_PER_SEC);
4834 assert_se(localtime_r(&s, &tm));
4836 tm.tm_hour = (int) hour;
4837 tm.tm_min = (int) minute;
4840 assert_se(s = mktime(&tm));
4842 *_u = (usec_t) s * USEC_PER_SEC;
4845 *_u += USEC_PER_DAY;
4851 static bool kexec_loaded(void) {
4852 bool loaded = false;
4855 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4863 static int shutdown_parse_argv(int argc, char *argv[]) {
4870 static const struct option options[] = {
4871 { "help", no_argument, NULL, ARG_HELP },
4872 { "halt", no_argument, NULL, 'H' },
4873 { "poweroff", no_argument, NULL, 'P' },
4874 { "reboot", no_argument, NULL, 'r' },
4875 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4876 { NULL, 0, NULL, 0 }
4884 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4892 arg_action = ACTION_HALT;
4896 arg_action = ACTION_POWEROFF;
4901 arg_action = ACTION_KEXEC;
4903 arg_action = ACTION_REBOOT;
4907 if (arg_action != ACTION_HALT)
4908 arg_action = ACTION_POWEROFF;
4921 /* Compatibility nops */
4925 arg_action = ACTION_CANCEL_SHUTDOWN;
4932 log_error("Unknown option code %c", c);
4937 if (argc > optind) {
4938 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4939 log_error("Failed to parse time specification: %s", argv[optind]);
4943 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4945 /* We skip the time argument */
4946 if (argc > optind + 1)
4947 arg_wall = argv + optind + 1;
4954 static int telinit_parse_argv(int argc, char *argv[]) {
4961 static const struct option options[] = {
4962 { "help", no_argument, NULL, ARG_HELP },
4963 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4964 { NULL, 0, NULL, 0 }
4967 static const struct {
4971 { '0', ACTION_POWEROFF },
4972 { '6', ACTION_REBOOT },
4973 { '1', ACTION_RESCUE },
4974 { '2', ACTION_RUNLEVEL2 },
4975 { '3', ACTION_RUNLEVEL3 },
4976 { '4', ACTION_RUNLEVEL4 },
4977 { '5', ACTION_RUNLEVEL5 },
4978 { 's', ACTION_RESCUE },
4979 { 'S', ACTION_RESCUE },
4980 { 'q', ACTION_RELOAD },
4981 { 'Q', ACTION_RELOAD },
4982 { 'u', ACTION_REEXEC },
4983 { 'U', ACTION_REEXEC }
4992 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5007 log_error("Unknown option code %c", c);
5012 if (optind >= argc) {
5017 if (optind + 1 < argc) {
5018 log_error("Too many arguments.");
5022 if (strlen(argv[optind]) != 1) {
5023 log_error("Expected single character argument.");
5027 for (i = 0; i < ELEMENTSOF(table); i++)
5028 if (table[i].from == argv[optind][0])
5031 if (i >= ELEMENTSOF(table)) {
5032 log_error("Unknown command %s.", argv[optind]);
5036 arg_action = table[i].to;
5043 static int runlevel_parse_argv(int argc, char *argv[]) {
5049 static const struct option options[] = {
5050 { "help", no_argument, NULL, ARG_HELP },
5051 { NULL, 0, NULL, 0 }
5059 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5070 log_error("Unknown option code %c", c);
5075 if (optind < argc) {
5076 log_error("Too many arguments.");
5083 static int parse_argv(int argc, char *argv[]) {
5087 if (program_invocation_short_name) {
5089 if (strstr(program_invocation_short_name, "halt")) {
5090 arg_action = ACTION_HALT;
5091 return halt_parse_argv(argc, argv);
5092 } else if (strstr(program_invocation_short_name, "poweroff")) {
5093 arg_action = ACTION_POWEROFF;
5094 return halt_parse_argv(argc, argv);
5095 } else if (strstr(program_invocation_short_name, "reboot")) {
5097 arg_action = ACTION_KEXEC;
5099 arg_action = ACTION_REBOOT;
5100 return halt_parse_argv(argc, argv);
5101 } else if (strstr(program_invocation_short_name, "shutdown")) {
5102 arg_action = ACTION_POWEROFF;
5103 return shutdown_parse_argv(argc, argv);
5104 } else if (strstr(program_invocation_short_name, "init")) {
5106 if (sd_booted() > 0) {
5107 arg_action = ACTION_INVALID;
5108 return telinit_parse_argv(argc, argv);
5110 /* Hmm, so some other init system is
5111 * running, we need to forward this
5112 * request to it. For now we simply
5113 * guess that it is Upstart. */
5115 execv("/lib/upstart/telinit", argv);
5117 log_error("Couldn't find an alternative telinit implementation to spawn.");
5121 } else if (strstr(program_invocation_short_name, "runlevel")) {
5122 arg_action = ACTION_RUNLEVEL;
5123 return runlevel_parse_argv(argc, argv);
5127 arg_action = ACTION_SYSTEMCTL;
5128 return systemctl_parse_argv(argc, argv);
5131 static int action_to_runlevel(void) {
5133 static const char table[_ACTION_MAX] = {
5134 [ACTION_HALT] = '0',
5135 [ACTION_POWEROFF] = '0',
5136 [ACTION_REBOOT] = '6',
5137 [ACTION_RUNLEVEL2] = '2',
5138 [ACTION_RUNLEVEL3] = '3',
5139 [ACTION_RUNLEVEL4] = '4',
5140 [ACTION_RUNLEVEL5] = '5',
5141 [ACTION_RESCUE] = '1'
5144 assert(arg_action < _ACTION_MAX);
5146 return table[arg_action];
5149 static int talk_upstart(void) {
5150 DBusMessage *m = NULL, *reply = NULL;
5152 int previous, rl, r;
5154 env1_buf[] = "RUNLEVEL=X",
5155 env2_buf[] = "PREVLEVEL=X";
5156 char *env1 = env1_buf, *env2 = env2_buf;
5157 const char *emit = "runlevel";
5158 dbus_bool_t b_false = FALSE;
5159 DBusMessageIter iter, sub;
5160 DBusConnection *bus;
5162 dbus_error_init(&error);
5164 if (!(rl = action_to_runlevel()))
5167 if (utmp_get_runlevel(&previous, NULL) < 0)
5170 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
5171 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
5176 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
5181 if ((r = bus_check_peercred(bus)) < 0) {
5182 log_error("Failed to verify owner of bus.");
5186 if (!(m = dbus_message_new_method_call(
5187 "com.ubuntu.Upstart",
5188 "/com/ubuntu/Upstart",
5189 "com.ubuntu.Upstart0_6",
5192 log_error("Could not allocate message.");
5197 dbus_message_iter_init_append(m, &iter);
5199 env1_buf[sizeof(env1_buf)-2] = rl;
5200 env2_buf[sizeof(env2_buf)-2] = previous;
5202 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5203 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5204 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5205 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5206 !dbus_message_iter_close_container(&iter, &sub) ||
5207 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5208 log_error("Could not append arguments to message.");
5213 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5215 if (error_is_no_service(&error)) {
5220 log_error("Failed to issue method call: %s", bus_error_message(&error));
5229 dbus_message_unref(m);
5232 dbus_message_unref(reply);
5235 dbus_connection_flush(bus);
5236 dbus_connection_close(bus);
5237 dbus_connection_unref(bus);
5240 dbus_error_free(&error);
5245 static int talk_initctl(void) {
5246 struct init_request request;
5250 if (!(rl = action_to_runlevel()))
5254 request.magic = INIT_MAGIC;
5255 request.sleeptime = 0;
5256 request.cmd = INIT_CMD_RUNLVL;
5257 request.runlevel = rl;
5259 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5261 if (errno == ENOENT)
5264 log_error("Failed to open "INIT_FIFO": %m");
5269 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5270 close_nointr_nofail(fd);
5273 log_error("Failed to write to "INIT_FIFO": %m");
5274 return errno ? -errno : -EIO;
5280 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5282 static const struct {
5290 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
5292 { "list-units", LESS, 1, list_units },
5293 { "list-jobs", EQUAL, 1, list_jobs },
5294 { "clear-jobs", EQUAL, 1, daemon_reload },
5295 { "load", MORE, 2, load_unit },
5296 { "cancel", MORE, 2, cancel_job },
5297 { "start", MORE, 2, start_unit },
5298 { "stop", MORE, 2, start_unit },
5299 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5300 { "reload", MORE, 2, start_unit },
5301 { "restart", MORE, 2, start_unit },
5302 { "try-restart", MORE, 2, start_unit },
5303 { "reload-or-restart", MORE, 2, start_unit },
5304 { "reload-or-try-restart", MORE, 2, start_unit },
5305 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5306 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5307 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5308 { "isolate", EQUAL, 2, start_unit },
5309 { "kill", MORE, 2, kill_unit },
5310 { "is-active", MORE, 2, check_unit },
5311 { "check", MORE, 2, check_unit },
5312 { "show", MORE, 1, show },
5313 { "status", MORE, 2, show },
5314 { "monitor", EQUAL, 1, monitor },
5315 { "dump", EQUAL, 1, dump },
5316 { "dot", EQUAL, 1, dot },
5317 { "snapshot", LESS, 2, snapshot },
5318 { "delete", MORE, 2, delete_snapshot },
5319 { "daemon-reload", EQUAL, 1, daemon_reload },
5320 { "daemon-reexec", EQUAL, 1, daemon_reload },
5321 { "show-environment", EQUAL, 1, show_enviroment },
5322 { "set-environment", MORE, 2, set_environment },
5323 { "unset-environment", MORE, 2, set_environment },
5324 { "halt", EQUAL, 1, start_special },
5325 { "poweroff", EQUAL, 1, start_special },
5326 { "reboot", EQUAL, 1, start_special },
5327 { "kexec", EQUAL, 1, start_special },
5328 { "default", EQUAL, 1, start_special },
5329 { "rescue", EQUAL, 1, start_special },
5330 { "emergency", EQUAL, 1, start_special },
5331 { "exit", EQUAL, 1, start_special },
5332 { "reset-failed", MORE, 1, reset_failed },
5333 { "enable", MORE, 2, enable_unit },
5334 { "disable", MORE, 2, enable_unit },
5335 { "is-enabled", MORE, 2, enable_unit }
5345 left = argc - optind;
5348 /* Special rule: no arguments means "list-units" */
5351 if (streq(argv[optind], "help")) {
5356 for (i = 0; i < ELEMENTSOF(verbs); i++)
5357 if (streq(argv[optind], verbs[i].verb))
5360 if (i >= ELEMENTSOF(verbs)) {
5361 log_error("Unknown operation %s", argv[optind]);
5366 switch (verbs[i].argc_cmp) {
5369 if (left != verbs[i].argc) {
5370 log_error("Invalid number of arguments.");
5377 if (left < verbs[i].argc) {
5378 log_error("Too few arguments.");
5385 if (left > verbs[i].argc) {
5386 log_error("Too many arguments.");
5393 assert_not_reached("Unknown comparison operator.");
5396 /* Require a bus connection for all operations but
5398 if (!streq(verbs[i].verb, "enable") && !streq(verbs[i].verb, "disable")) {
5400 if (running_in_chroot() > 0) {
5401 log_info("Running in chroot, ignoring request.");
5406 log_error("Failed to get D-Bus connection: %s", error->message);
5411 return verbs[i].dispatch(bus, argv + optind, left);
5414 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
5416 struct msghdr msghdr;
5418 union sockaddr_union sockaddr;
5419 struct shutdownd_command c;
5424 c.dry_run = dry_run;
5428 strncpy(c.wall_message, message, sizeof(c.wall_message));
5430 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
5434 sockaddr.sa.sa_family = AF_UNIX;
5435 sockaddr.un.sun_path[0] = 0;
5436 strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5439 iovec.iov_base = (char*) &c;
5440 iovec.iov_len = sizeof(c);
5443 msghdr.msg_name = &sockaddr;
5444 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5446 msghdr.msg_iov = &iovec;
5447 msghdr.msg_iovlen = 1;
5449 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5450 close_nointr_nofail(fd);
5454 close_nointr_nofail(fd);
5458 static int reload_with_fallback(DBusConnection *bus) {
5461 /* First, try systemd via D-Bus. */
5462 if (daemon_reload(bus, NULL, 0) > 0)
5466 /* Nothing else worked, so let's try signals */
5467 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5469 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5470 log_error("kill() failed: %m");
5477 static int start_with_fallback(DBusConnection *bus) {
5480 /* First, try systemd via D-Bus. */
5481 if (start_unit(bus, NULL, 0) >= 0)
5485 /* Hmm, talking to systemd via D-Bus didn't work. Then
5486 * let's try to talk to Upstart via D-Bus. */
5487 if (talk_upstart() > 0)
5490 /* Nothing else worked, so let's try
5492 if (talk_initctl() > 0)
5495 log_error("Failed to talk to init daemon.");
5499 warn_wall(arg_action);
5503 static int halt_main(DBusConnection *bus) {
5506 if (geteuid() != 0) {
5507 log_error("Must be root.");
5513 char date[FORMAT_TIMESTAMP_MAX];
5515 m = strv_join(arg_wall, " ");
5516 r = send_shutdownd(arg_when,
5517 arg_action == ACTION_HALT ? 'H' :
5518 arg_action == ACTION_POWEROFF ? 'P' :
5526 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5528 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5529 format_timestamp(date, sizeof(date), arg_when));
5534 if (!arg_dry && !arg_immediate)
5535 return start_with_fallback(bus);
5538 if (sd_booted() > 0)
5539 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5540 else if ((r = utmp_put_shutdown(0)) < 0)
5541 log_warning("Failed to write utmp record: %s", strerror(-r));
5550 /* Make sure C-A-D is handled by the kernel from this
5552 reboot(RB_ENABLE_CAD);
5554 switch (arg_action) {
5557 log_info("Halting.");
5558 reboot(RB_HALT_SYSTEM);
5561 case ACTION_POWEROFF:
5562 log_info("Powering off.");
5563 reboot(RB_POWER_OFF);
5567 log_info("Rebooting.");
5568 reboot(RB_AUTOBOOT);
5572 assert_not_reached("Unknown halt action.");
5575 /* We should never reach this. */
5579 static int runlevel_main(void) {
5580 int r, runlevel, previous;
5582 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5583 printf("unknown\n");
5588 previous <= 0 ? 'N' : previous,
5589 runlevel <= 0 ? 'N' : runlevel);
5594 static void agent_close(void) {
5600 /* Inform agent that we are done */
5601 kill(agent_pid, SIGTERM);
5602 kill(agent_pid, SIGCONT);
5603 wait_for_terminate(agent_pid, &dummy);
5607 int main(int argc, char*argv[]) {
5608 int r, retval = EXIT_FAILURE;
5609 DBusConnection *bus = NULL;
5612 dbus_error_init(&error);
5614 log_parse_environment();
5617 if ((r = parse_argv(argc, argv)) < 0)
5620 retval = EXIT_SUCCESS;
5624 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5625 * let's shortcut this */
5626 if (arg_action == ACTION_RUNLEVEL) {
5627 r = runlevel_main();
5628 retval = r < 0 ? EXIT_FAILURE : r;
5632 if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5633 log_info("Running in chroot, ignoring request.");
5638 if (arg_transport == TRANSPORT_NORMAL)
5639 bus_connect(arg_user ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5640 else if (arg_transport == TRANSPORT_POLKIT) {
5641 bus_connect_system_polkit(&bus, &error);
5642 private_bus = false;
5643 } else if (arg_transport == TRANSPORT_SSH) {
5644 bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5645 private_bus = false;
5647 assert_not_reached("Uh, invalid transport...");
5649 switch (arg_action) {
5651 case ACTION_SYSTEMCTL:
5652 r = systemctl_main(bus, argc, argv, &error);
5656 case ACTION_POWEROFF:
5662 case ACTION_RUNLEVEL2:
5663 case ACTION_RUNLEVEL3:
5664 case ACTION_RUNLEVEL4:
5665 case ACTION_RUNLEVEL5:
5667 case ACTION_EMERGENCY:
5668 case ACTION_DEFAULT:
5669 r = start_with_fallback(bus);
5674 r = reload_with_fallback(bus);
5677 case ACTION_CANCEL_SHUTDOWN:
5678 r = send_shutdownd(0, 0, false, false, NULL);
5681 case ACTION_INVALID:
5682 case ACTION_RUNLEVEL:
5684 assert_not_reached("Unknown action");
5687 retval = r < 0 ? EXIT_FAILURE : r;
5692 dbus_connection_flush(bus);
5693 dbus_connection_close(bus);
5694 dbus_connection_unref(bus);
5697 dbus_error_free(&error);
5701 strv_free(arg_property);