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 int arg_signal = SIGTERM;
84 static const char *arg_root = NULL;
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"
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);
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);
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) {
2087 switch (dbus_message_iter_get_arg_type(iter)) {
2089 case DBUS_TYPE_STRING: {
2092 dbus_message_iter_get_basic(iter, &s);
2095 if (streq(name, "Id"))
2097 else if (streq(name, "LoadState"))
2099 else if (streq(name, "ActiveState"))
2100 i->active_state = s;
2101 else if (streq(name, "SubState"))
2103 else if (streq(name, "Description"))
2105 else if (streq(name, "FragmentPath"))
2107 #ifdef HAVE_SYSV_COMPAT
2108 else if (streq(name, "SysVPath")) {
2113 else if (streq(name, "DefaultControlGroup"))
2114 i->default_control_group = s;
2115 else if (streq(name, "StatusText"))
2117 else if (streq(name, "SysFSPath"))
2119 else if (streq(name, "Where"))
2121 else if (streq(name, "What"))
2123 else if (streq(name, "Following"))
2130 case DBUS_TYPE_BOOLEAN: {
2133 dbus_message_iter_get_basic(iter, &b);
2135 if (streq(name, "Accept"))
2137 else if (streq(name, "NeedDaemonReload"))
2138 i->need_daemon_reload = b;
2139 else if (streq(name, "ConditionResult"))
2140 i->condition_result = b;
2145 case DBUS_TYPE_UINT32: {
2148 dbus_message_iter_get_basic(iter, &u);
2150 if (streq(name, "MainPID")) {
2152 i->main_pid = (pid_t) u;
2155 } else if (streq(name, "ControlPID"))
2156 i->control_pid = (pid_t) u;
2157 else if (streq(name, "ExecMainPID")) {
2159 i->main_pid = (pid_t) u;
2160 } else if (streq(name, "NAccepted"))
2162 else if (streq(name, "NConnections"))
2163 i->n_connections = u;
2168 case DBUS_TYPE_INT32: {
2171 dbus_message_iter_get_basic(iter, &j);
2173 if (streq(name, "ExecMainCode"))
2174 i->exit_code = (int) j;
2175 else if (streq(name, "ExecMainStatus"))
2176 i->exit_status = (int) j;
2181 case DBUS_TYPE_UINT64: {
2184 dbus_message_iter_get_basic(iter, &u);
2186 if (streq(name, "ExecMainStartTimestamp"))
2187 i->start_timestamp = (usec_t) u;
2188 else if (streq(name, "ExecMainExitTimestamp"))
2189 i->exit_timestamp = (usec_t) u;
2190 else if (streq(name, "ActiveEnterTimestamp"))
2191 i->active_enter_timestamp = (usec_t) u;
2192 else if (streq(name, "InactiveEnterTimestamp"))
2193 i->inactive_enter_timestamp = (usec_t) u;
2194 else if (streq(name, "InactiveExitTimestamp"))
2195 i->inactive_exit_timestamp = (usec_t) u;
2196 else if (streq(name, "ActiveExitTimestamp"))
2197 i->active_exit_timestamp = (usec_t) u;
2198 else if (streq(name, "ConditionTimestamp"))
2199 i->condition_timestamp = (usec_t) u;
2204 case DBUS_TYPE_ARRAY: {
2206 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2207 startswith(name, "Exec")) {
2208 DBusMessageIter sub;
2210 dbus_message_iter_recurse(iter, &sub);
2211 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2212 ExecStatusInfo *info;
2215 if (!(info = new0(ExecStatusInfo, 1)))
2218 if (!(info->name = strdup(name))) {
2223 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2228 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2230 dbus_message_iter_next(&sub);
2241 static int print_property(const char *name, DBusMessageIter *iter) {
2245 /* This is a low-level property printer, see
2246 * print_status_info() for the nicer output */
2248 if (arg_property && !strv_find(arg_property, name))
2251 switch (dbus_message_iter_get_arg_type(iter)) {
2253 case DBUS_TYPE_STRUCT: {
2254 DBusMessageIter sub;
2255 dbus_message_iter_recurse(iter, &sub);
2257 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2260 dbus_message_iter_get_basic(&sub, &u);
2263 printf("%s=%u\n", name, (unsigned) u);
2265 printf("%s=\n", name);
2268 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2271 dbus_message_iter_get_basic(&sub, &s);
2273 if (arg_all || s[0])
2274 printf("%s=%s\n", name, s);
2282 case DBUS_TYPE_ARRAY:
2284 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
2285 DBusMessageIter sub, sub2;
2287 dbus_message_iter_recurse(iter, &sub);
2288 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2292 dbus_message_iter_recurse(&sub, &sub2);
2294 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
2295 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
2296 printf("EnvironmentFile=%s (ignore=%s)\n", path, yes_no(ignore));
2298 dbus_message_iter_next(&sub);
2303 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2304 DBusMessageIter sub, sub2;
2306 dbus_message_iter_recurse(iter, &sub);
2307 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2308 const char *type, *path;
2310 dbus_message_iter_recurse(&sub, &sub2);
2312 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2313 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2314 printf("%s=%s\n", type, path);
2316 dbus_message_iter_next(&sub);
2321 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2322 DBusMessageIter sub, sub2;
2324 dbus_message_iter_recurse(iter, &sub);
2325 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2327 uint64_t value, next_elapse;
2329 dbus_message_iter_recurse(&sub, &sub2);
2331 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2332 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2333 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2334 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2336 printf("%s={ value=%s ; next_elapse=%s }\n",
2338 format_timespan(timespan1, sizeof(timespan1), value),
2339 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2342 dbus_message_iter_next(&sub);
2347 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2348 DBusMessageIter sub;
2350 dbus_message_iter_recurse(iter, &sub);
2351 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2352 ExecStatusInfo info;
2355 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2356 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2359 t = strv_join(info.argv, " ");
2361 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2365 yes_no(info.ignore),
2366 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2367 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2368 (unsigned) info. pid,
2369 sigchld_code_to_string(info.code),
2371 info.code == CLD_EXITED ? "" : "/",
2372 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2378 strv_free(info.argv);
2380 dbus_message_iter_next(&sub);
2389 if (generic_print_property(name, iter, arg_all) > 0)
2393 printf("%s=[unprintable]\n", name);
2398 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2399 DBusMessage *m = NULL, *reply = NULL;
2400 const char *interface = "";
2403 DBusMessageIter iter, sub, sub2, sub3;
2404 UnitStatusInfo info;
2412 dbus_error_init(&error);
2414 if (!(m = dbus_message_new_method_call(
2415 "org.freedesktop.systemd1",
2417 "org.freedesktop.DBus.Properties",
2419 log_error("Could not allocate message.");
2424 if (!dbus_message_append_args(m,
2425 DBUS_TYPE_STRING, &interface,
2426 DBUS_TYPE_INVALID)) {
2427 log_error("Could not append arguments to message.");
2432 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2433 log_error("Failed to issue method call: %s", bus_error_message(&error));
2438 if (!dbus_message_iter_init(reply, &iter) ||
2439 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2440 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2441 log_error("Failed to parse reply.");
2446 dbus_message_iter_recurse(&iter, &sub);
2453 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2456 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2457 log_error("Failed to parse reply.");
2462 dbus_message_iter_recurse(&sub, &sub2);
2464 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2465 log_error("Failed to parse reply.");
2470 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2471 log_error("Failed to parse reply.");
2476 dbus_message_iter_recurse(&sub2, &sub3);
2478 if (show_properties)
2479 r = print_property(name, &sub3);
2481 r = status_property(name, &sub3, &info);
2484 log_error("Failed to parse reply.");
2489 dbus_message_iter_next(&sub);
2494 if (!show_properties)
2495 print_status_info(&info);
2497 if (!streq_ptr(info.active_state, "active") &&
2498 !streq_ptr(info.active_state, "reloading") &&
2499 streq(verb, "status"))
2500 /* According to LSB: "program not running" */
2503 while ((p = info.exec)) {
2504 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2505 exec_status_info_free(p);
2510 dbus_message_unref(m);
2513 dbus_message_unref(reply);
2515 dbus_error_free(&error);
2520 static int show(DBusConnection *bus, char **args, unsigned n) {
2521 DBusMessage *m = NULL, *reply = NULL;
2525 bool show_properties, new_line = false;
2530 dbus_error_init(&error);
2532 show_properties = !streq(args[0], "status");
2534 if (show_properties)
2535 pager_open_if_enabled();
2537 if (show_properties && n <= 1) {
2538 /* If not argument is specified inspect the manager
2541 ret = show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2545 for (i = 1; i < n; i++) {
2546 const char *path = NULL;
2549 if (safe_atou32(args[i], &id) < 0) {
2551 /* Interpret as unit name */
2553 if (!(m = dbus_message_new_method_call(
2554 "org.freedesktop.systemd1",
2555 "/org/freedesktop/systemd1",
2556 "org.freedesktop.systemd1.Manager",
2558 log_error("Could not allocate message.");
2563 if (!dbus_message_append_args(m,
2564 DBUS_TYPE_STRING, &args[i],
2565 DBUS_TYPE_INVALID)) {
2566 log_error("Could not append arguments to message.");
2571 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2573 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2574 log_error("Failed to issue method call: %s", bus_error_message(&error));
2579 dbus_error_free(&error);
2581 dbus_message_unref(m);
2582 if (!(m = dbus_message_new_method_call(
2583 "org.freedesktop.systemd1",
2584 "/org/freedesktop/systemd1",
2585 "org.freedesktop.systemd1.Manager",
2587 log_error("Could not allocate message.");
2592 if (!dbus_message_append_args(m,
2593 DBUS_TYPE_STRING, &args[i],
2594 DBUS_TYPE_INVALID)) {
2595 log_error("Could not append arguments to message.");
2600 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2601 log_error("Failed to issue method call: %s", bus_error_message(&error));
2603 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2604 ret = 4; /* According to LSB: "program or service status is unknown" */
2611 } else if (show_properties) {
2613 /* Interpret as job id */
2615 if (!(m = dbus_message_new_method_call(
2616 "org.freedesktop.systemd1",
2617 "/org/freedesktop/systemd1",
2618 "org.freedesktop.systemd1.Manager",
2620 log_error("Could not allocate message.");
2625 if (!dbus_message_append_args(m,
2626 DBUS_TYPE_UINT32, &id,
2627 DBUS_TYPE_INVALID)) {
2628 log_error("Could not append arguments to message.");
2633 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2634 log_error("Failed to issue method call: %s", bus_error_message(&error));
2640 /* Interpret as PID */
2642 if (!(m = dbus_message_new_method_call(
2643 "org.freedesktop.systemd1",
2644 "/org/freedesktop/systemd1",
2645 "org.freedesktop.systemd1.Manager",
2647 log_error("Could not allocate message.");
2652 if (!dbus_message_append_args(m,
2653 DBUS_TYPE_UINT32, &id,
2654 DBUS_TYPE_INVALID)) {
2655 log_error("Could not append arguments to message.");
2660 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2661 log_error("Failed to issue method call: %s", bus_error_message(&error));
2667 if (!dbus_message_get_args(reply, &error,
2668 DBUS_TYPE_OBJECT_PATH, &path,
2669 DBUS_TYPE_INVALID)) {
2670 log_error("Failed to parse reply: %s", bus_error_message(&error));
2675 if ((r = show_one(args[0], bus, path, show_properties, &new_line)) != 0)
2678 dbus_message_unref(m);
2679 dbus_message_unref(reply);
2685 dbus_message_unref(m);
2688 dbus_message_unref(reply);
2690 dbus_error_free(&error);
2695 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2697 DBusMessage *m = NULL, *reply = NULL;
2702 dbus_error_init(&error);
2704 log_debug("Got D-Bus request: %s.%s() on %s",
2705 dbus_message_get_interface(message),
2706 dbus_message_get_member(message),
2707 dbus_message_get_path(message));
2709 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2710 log_error("Warning! D-Bus connection terminated.");
2711 dbus_connection_close(connection);
2713 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2714 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2715 const char *id, *path;
2717 if (!dbus_message_get_args(message, &error,
2718 DBUS_TYPE_STRING, &id,
2719 DBUS_TYPE_OBJECT_PATH, &path,
2721 log_error("Failed to parse message: %s", bus_error_message(&error));
2722 else if (streq(dbus_message_get_member(message), "UnitNew"))
2723 printf("Unit %s added.\n", id);
2725 printf("Unit %s removed.\n", id);
2727 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew")) {
2731 if (!dbus_message_get_args(message, &error,
2732 DBUS_TYPE_UINT32, &id,
2733 DBUS_TYPE_OBJECT_PATH, &path,
2735 log_error("Failed to parse message: %s", bus_error_message(&error));
2737 printf("Job %u added.\n", id);
2740 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2742 const char *path, *result;
2744 if (!dbus_message_get_args(message, &error,
2745 DBUS_TYPE_UINT32, &id,
2746 DBUS_TYPE_OBJECT_PATH, &path,
2747 DBUS_TYPE_STRING, &result,
2749 log_error("Failed to parse message: %s", bus_error_message(&error));
2751 printf("Job %u removed (result=%s).\n", id, result);
2754 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2756 const char *path, *interface, *property = "Id";
2757 DBusMessageIter iter, sub;
2759 path = dbus_message_get_path(message);
2761 if (!dbus_message_get_args(message, &error,
2762 DBUS_TYPE_STRING, &interface,
2763 DBUS_TYPE_INVALID)) {
2764 log_error("Failed to parse message: %s", bus_error_message(&error));
2768 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2769 !streq(interface, "org.freedesktop.systemd1.Unit"))
2772 if (!(m = dbus_message_new_method_call(
2773 "org.freedesktop.systemd1",
2775 "org.freedesktop.DBus.Properties",
2777 log_error("Could not allocate message.");
2781 if (!dbus_message_append_args(m,
2782 DBUS_TYPE_STRING, &interface,
2783 DBUS_TYPE_STRING, &property,
2784 DBUS_TYPE_INVALID)) {
2785 log_error("Could not append arguments to message.");
2789 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2790 log_error("Failed to issue method call: %s", bus_error_message(&error));
2794 if (!dbus_message_iter_init(reply, &iter) ||
2795 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2796 log_error("Failed to parse reply.");
2800 dbus_message_iter_recurse(&iter, &sub);
2802 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2805 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2806 log_error("Failed to parse reply.");
2810 dbus_message_iter_get_basic(&sub, &id);
2811 printf("Unit %s changed.\n", id);
2815 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2816 log_error("Failed to parse reply.");
2820 dbus_message_iter_get_basic(&sub, &id);
2821 printf("Job %u changed.\n", id);
2827 dbus_message_unref(m);
2830 dbus_message_unref(reply);
2832 dbus_error_free(&error);
2833 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2837 dbus_message_unref(m);
2840 dbus_message_unref(reply);
2842 dbus_error_free(&error);
2843 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2846 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2847 DBusMessage *m = NULL, *reply = NULL;
2851 dbus_error_init(&error);
2854 dbus_bus_add_match(bus,
2856 "sender='org.freedesktop.systemd1',"
2857 "interface='org.freedesktop.systemd1.Manager',"
2858 "path='/org/freedesktop/systemd1'",
2861 if (dbus_error_is_set(&error)) {
2862 log_error("Failed to add match: %s", bus_error_message(&error));
2867 dbus_bus_add_match(bus,
2869 "sender='org.freedesktop.systemd1',"
2870 "interface='org.freedesktop.DBus.Properties',"
2871 "member='PropertiesChanged'",
2874 if (dbus_error_is_set(&error)) {
2875 log_error("Failed to add match: %s", bus_error_message(&error));
2881 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2882 log_error("Failed to add filter.");
2887 if (!(m = dbus_message_new_method_call(
2888 "org.freedesktop.systemd1",
2889 "/org/freedesktop/systemd1",
2890 "org.freedesktop.systemd1.Manager",
2892 log_error("Could not allocate message.");
2897 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2898 log_error("Failed to issue method call: %s", bus_error_message(&error));
2903 while (dbus_connection_read_write_dispatch(bus, -1))
2910 /* This is slightly dirty, since we don't undo the filter or the matches. */
2913 dbus_message_unref(m);
2916 dbus_message_unref(reply);
2918 dbus_error_free(&error);
2923 static int dump(DBusConnection *bus, char **args, unsigned n) {
2924 DBusMessage *m = NULL, *reply = NULL;
2929 dbus_error_init(&error);
2931 pager_open_if_enabled();
2933 if (!(m = dbus_message_new_method_call(
2934 "org.freedesktop.systemd1",
2935 "/org/freedesktop/systemd1",
2936 "org.freedesktop.systemd1.Manager",
2938 log_error("Could not allocate message.");
2942 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2943 log_error("Failed to issue method call: %s", bus_error_message(&error));
2948 if (!dbus_message_get_args(reply, &error,
2949 DBUS_TYPE_STRING, &text,
2950 DBUS_TYPE_INVALID)) {
2951 log_error("Failed to parse reply: %s", bus_error_message(&error));
2956 fputs(text, stdout);
2962 dbus_message_unref(m);
2965 dbus_message_unref(reply);
2967 dbus_error_free(&error);
2972 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2973 DBusMessage *m = NULL, *reply = NULL;
2976 const char *name = "", *path, *id;
2977 dbus_bool_t cleanup = FALSE;
2978 DBusMessageIter iter, sub;
2980 *interface = "org.freedesktop.systemd1.Unit",
2983 dbus_error_init(&error);
2985 if (!(m = dbus_message_new_method_call(
2986 "org.freedesktop.systemd1",
2987 "/org/freedesktop/systemd1",
2988 "org.freedesktop.systemd1.Manager",
2989 "CreateSnapshot"))) {
2990 log_error("Could not allocate message.");
2997 if (!dbus_message_append_args(m,
2998 DBUS_TYPE_STRING, &name,
2999 DBUS_TYPE_BOOLEAN, &cleanup,
3000 DBUS_TYPE_INVALID)) {
3001 log_error("Could not append arguments to 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 if (!dbus_message_get_args(reply, &error,
3013 DBUS_TYPE_OBJECT_PATH, &path,
3014 DBUS_TYPE_INVALID)) {
3015 log_error("Failed to parse reply: %s", bus_error_message(&error));
3020 dbus_message_unref(m);
3021 if (!(m = dbus_message_new_method_call(
3022 "org.freedesktop.systemd1",
3024 "org.freedesktop.DBus.Properties",
3026 log_error("Could not allocate message.");
3030 if (!dbus_message_append_args(m,
3031 DBUS_TYPE_STRING, &interface,
3032 DBUS_TYPE_STRING, &property,
3033 DBUS_TYPE_INVALID)) {
3034 log_error("Could not append arguments to message.");
3039 dbus_message_unref(reply);
3040 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3041 log_error("Failed to issue method call: %s", bus_error_message(&error));
3046 if (!dbus_message_iter_init(reply, &iter) ||
3047 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3048 log_error("Failed to parse reply.");
3053 dbus_message_iter_recurse(&iter, &sub);
3055 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3056 log_error("Failed to parse reply.");
3061 dbus_message_iter_get_basic(&sub, &id);
3069 dbus_message_unref(m);
3072 dbus_message_unref(reply);
3074 dbus_error_free(&error);
3079 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
3080 DBusMessage *m = NULL, *reply = NULL;
3088 dbus_error_init(&error);
3090 for (i = 1; i < n; i++) {
3091 const char *path = NULL;
3093 if (!(m = dbus_message_new_method_call(
3094 "org.freedesktop.systemd1",
3095 "/org/freedesktop/systemd1",
3096 "org.freedesktop.systemd1.Manager",
3098 log_error("Could not allocate message.");
3103 if (!dbus_message_append_args(m,
3104 DBUS_TYPE_STRING, &args[i],
3105 DBUS_TYPE_INVALID)) {
3106 log_error("Could not append arguments to message.");
3111 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3112 log_error("Failed to issue method call: %s", bus_error_message(&error));
3117 if (!dbus_message_get_args(reply, &error,
3118 DBUS_TYPE_OBJECT_PATH, &path,
3119 DBUS_TYPE_INVALID)) {
3120 log_error("Failed to parse reply: %s", bus_error_message(&error));
3125 dbus_message_unref(m);
3126 if (!(m = dbus_message_new_method_call(
3127 "org.freedesktop.systemd1",
3129 "org.freedesktop.systemd1.Snapshot",
3131 log_error("Could not allocate message.");
3136 dbus_message_unref(reply);
3137 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3138 log_error("Failed to issue method call: %s", bus_error_message(&error));
3143 dbus_message_unref(m);
3144 dbus_message_unref(reply);
3152 dbus_message_unref(m);
3155 dbus_message_unref(reply);
3157 dbus_error_free(&error);
3162 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
3163 DBusMessage *m = NULL, *reply = NULL;
3168 dbus_error_init(&error);
3170 if (arg_action == ACTION_RELOAD)
3172 else if (arg_action == ACTION_REEXEC)
3173 method = "Reexecute";
3175 assert(arg_action == ACTION_SYSTEMCTL);
3178 streq(args[0], "clear-jobs") ||
3179 streq(args[0], "cancel") ? "ClearJobs" :
3180 streq(args[0], "daemon-reexec") ? "Reexecute" :
3181 streq(args[0], "reset-failed") ? "ResetFailed" :
3182 streq(args[0], "halt") ? "Halt" :
3183 streq(args[0], "poweroff") ? "PowerOff" :
3184 streq(args[0], "reboot") ? "Reboot" :
3185 streq(args[0], "kexec") ? "KExec" :
3186 streq(args[0], "exit") ? "Exit" :
3187 /* "daemon-reload" */ "Reload";
3190 if (!(m = dbus_message_new_method_call(
3191 "org.freedesktop.systemd1",
3192 "/org/freedesktop/systemd1",
3193 "org.freedesktop.systemd1.Manager",
3195 log_error("Could not allocate message.");
3199 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3201 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3202 /* There's always a fallback possible for
3203 * legacy actions. */
3208 if (streq(method, "Reexecute") && dbus_error_has_name(&error, DBUS_ERROR_NO_REPLY)) {
3209 /* On reexecution, we expect a disconnect, not
3215 log_error("Failed to issue method call: %s", bus_error_message(&error));
3224 dbus_message_unref(m);
3227 dbus_message_unref(reply);
3229 dbus_error_free(&error);
3234 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3235 DBusMessage *m = NULL, *reply = NULL;
3241 dbus_error_init(&error);
3244 return daemon_reload(bus, args, n);
3246 for (i = 1; i < n; i++) {
3248 if (!(m = dbus_message_new_method_call(
3249 "org.freedesktop.systemd1",
3250 "/org/freedesktop/systemd1",
3251 "org.freedesktop.systemd1.Manager",
3252 "ResetFailedUnit"))) {
3253 log_error("Could not allocate message.");
3258 if (!dbus_message_append_args(m,
3259 DBUS_TYPE_STRING, args + i,
3260 DBUS_TYPE_INVALID)) {
3261 log_error("Could not append arguments to message.");
3266 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3267 log_error("Failed to issue method call: %s", bus_error_message(&error));
3272 dbus_message_unref(m);
3273 dbus_message_unref(reply);
3281 dbus_message_unref(m);
3284 dbus_message_unref(reply);
3286 dbus_error_free(&error);
3291 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3292 DBusMessage *m = NULL, *reply = NULL;
3294 DBusMessageIter iter, sub, sub2;
3297 *interface = "org.freedesktop.systemd1.Manager",
3298 *property = "Environment";
3300 dbus_error_init(&error);
3302 pager_open_if_enabled();
3304 if (!(m = dbus_message_new_method_call(
3305 "org.freedesktop.systemd1",
3306 "/org/freedesktop/systemd1",
3307 "org.freedesktop.DBus.Properties",
3309 log_error("Could not allocate message.");
3313 if (!dbus_message_append_args(m,
3314 DBUS_TYPE_STRING, &interface,
3315 DBUS_TYPE_STRING, &property,
3316 DBUS_TYPE_INVALID)) {
3317 log_error("Could not append arguments to message.");
3322 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3323 log_error("Failed to issue method call: %s", bus_error_message(&error));
3328 if (!dbus_message_iter_init(reply, &iter) ||
3329 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3330 log_error("Failed to parse reply.");
3335 dbus_message_iter_recurse(&iter, &sub);
3337 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3338 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3339 log_error("Failed to parse reply.");
3344 dbus_message_iter_recurse(&sub, &sub2);
3346 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3349 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3350 log_error("Failed to parse reply.");
3355 dbus_message_iter_get_basic(&sub2, &text);
3356 printf("%s\n", text);
3358 dbus_message_iter_next(&sub2);
3365 dbus_message_unref(m);
3368 dbus_message_unref(reply);
3370 dbus_error_free(&error);
3375 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3376 DBusMessage *m = NULL, *reply = NULL;
3380 DBusMessageIter iter, sub;
3383 dbus_error_init(&error);
3385 method = streq(args[0], "set-environment")
3387 : "UnsetEnvironment";
3389 if (!(m = dbus_message_new_method_call(
3390 "org.freedesktop.systemd1",
3391 "/org/freedesktop/systemd1",
3392 "org.freedesktop.systemd1.Manager",
3395 log_error("Could not allocate message.");
3399 dbus_message_iter_init_append(m, &iter);
3401 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3402 log_error("Could not append arguments to message.");
3407 for (i = 1; i < n; i++)
3408 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3409 log_error("Could not append arguments to message.");
3414 if (!dbus_message_iter_close_container(&iter, &sub)) {
3415 log_error("Could not append arguments to message.");
3420 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3421 log_error("Failed to issue method call: %s", bus_error_message(&error));
3430 dbus_message_unref(m);
3433 dbus_message_unref(reply);
3435 dbus_error_free(&error);
3448 static Hashmap *will_install = NULL, *have_installed = NULL;
3449 static Set *remove_symlinks_to = NULL;
3450 static unsigned n_symlinks = 0;
3452 static void install_info_free(InstallInfo *i) {
3457 strv_free(i->aliases);
3458 strv_free(i->wanted_by);
3462 static void install_info_hashmap_free(Hashmap *m) {
3465 while ((i = hashmap_steal_first(m)))
3466 install_info_free(i);
3471 static int install_info_add(const char *name) {
3475 assert(will_install);
3477 if (!unit_name_is_valid_no_type(name, true)) {
3478 log_warning("Unit name %s is not a valid unit name.", name);
3482 if (hashmap_get(have_installed, name) ||
3483 hashmap_get(will_install, name))
3486 if (!(i = new0(InstallInfo, 1))) {
3491 if (!(i->name = strdup(name))) {
3496 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3503 install_info_free(i);
3508 static int config_parse_also(
3509 const char *filename,
3511 const char *section,
3526 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3530 if (!(n = strndup(w, l)))
3533 if ((r = install_info_add(n)) < 0) {
3534 log_warning("Cannot install unit %s: %s", n, strerror(-r));
3545 static int mark_symlink_for_removal(const char *p) {
3550 assert(path_is_absolute(p));
3552 if (!remove_symlinks_to)
3555 if (!(n = strdup(p)))
3558 path_kill_slashes(n);
3560 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3562 return r == -EEXIST ? 0 : r;
3568 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3577 if (!(d = fdopendir(fd))) {
3578 close_nointr_nofail(fd);
3584 while ((de = readdir(d))) {
3585 bool is_dir = false, is_link = false;
3587 if (ignore_file(de->d_name))
3590 if (de->d_type == DT_LNK)
3592 else if (de->d_type == DT_DIR)
3594 else if (de->d_type == DT_UNKNOWN) {
3597 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3598 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3605 is_link = S_ISLNK(st.st_mode);
3606 is_dir = S_ISDIR(st.st_mode);
3614 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3615 log_error("Failed to open %s/%s: %m", root, de->d_name);
3622 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3623 log_error("Failed to allocate directory string.");
3624 close_nointr_nofail(nfd);
3629 /* This will close nfd, regardless whether it succeeds or not */
3630 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3636 } else if (is_link) {
3640 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3641 log_error("Failed to allocate symlink string.");
3646 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3647 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3655 if ((c = canonicalize_file_name(dest))) {
3656 /* This might fail if the destination
3657 * is already removed */
3663 path_kill_slashes(dest);
3664 if (set_get(remove_symlinks_to, dest)) {
3667 log_info("rm '%s'", p);
3669 if (unlink(p) < 0) {
3670 log_error("Cannot unlink symlink %s: %m", p);
3675 rmdir_parents(p, config_path);
3676 path_kill_slashes(p);
3678 if (!set_get(remove_symlinks_to, p)) {
3680 if ((r = mark_symlink_for_removal(p)) < 0) {
3699 static int remove_marked_symlinks(const char *config_path) {
3703 assert(config_path);
3705 if (set_size(remove_symlinks_to) <= 0)
3708 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3715 if ((cfd = dup(fd)) < 0) {
3720 /* This takes possession of cfd and closes it */
3721 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3727 close_nointr_nofail(fd);
3732 static int create_symlink(const char *verb, const char *orig_old_path, const char *new_path) {
3734 const char *old_path;
3737 old_path = orig_old_path+strlen(arg_root);
3739 old_path = orig_old_path;
3745 if (streq(verb, "enable")) {
3748 mkdir_parents(new_path, 0755);
3750 if (symlink(old_path, new_path) >= 0) {
3753 log_info("ln -s '%s' '%s'", old_path, new_path);
3758 if (errno != EEXIST) {
3759 log_error("Cannot link %s to %s: %m", old_path, new_path);
3763 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3765 if (errno == EINVAL) {
3766 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3770 log_error("readlink() failed: %s", strerror(-r));
3774 if (streq(dest, old_path)) {
3780 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3789 log_info("ln -s '%s' '%s'", old_path, new_path);
3791 if (symlink(old_path, new_path) >= 0)
3794 log_error("Cannot link %s to %s: %m", old_path, new_path);
3797 } else if (streq(verb, "disable")) {
3800 if ((r = mark_symlink_for_removal(old_path)) < 0)
3803 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3804 if (errno == ENOENT)
3807 if (errno == EINVAL) {
3808 log_warning("File %s not a symlink, ignoring.", old_path);
3812 log_error("readlink() failed: %s", strerror(-r));
3816 if (!streq(dest, old_path)) {
3817 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3824 if ((r = mark_symlink_for_removal(new_path)) < 0)
3828 log_info("rm '%s'", new_path);
3830 if (unlink(new_path) >= 0)
3833 log_error("Cannot unlink %s: %m", new_path);
3836 } else if (streq(verb, "is-enabled")) {
3839 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3841 if (errno == ENOENT || errno == EINVAL)
3844 log_error("readlink() failed: %s", strerror(-r));
3848 if (streq(dest, old_path)) {
3857 assert_not_reached("Unknown action.");
3860 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3862 char *alias_path = NULL;
3867 assert(config_path);
3869 STRV_FOREACH(s, i->aliases) {
3872 if (!(alias_path = path_make_absolute(*s, config_path))) {
3873 log_error("Out of memory");
3878 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3881 if (streq(verb, "disable"))
3882 rmdir_parents(alias_path, config_path);
3892 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3894 char *alias_path = NULL;
3899 assert(config_path);
3901 STRV_FOREACH(s, i->wanted_by) {
3902 if (!unit_name_is_valid_no_type(*s, true)) {
3903 log_error("Invalid name %s.", *s);
3911 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3912 log_error("Out of memory");
3917 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3920 if (streq(verb, "disable"))
3921 rmdir_parents(alias_path, config_path);
3932 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3934 const ConfigItem items[] = {
3935 { "Alias", config_parse_strv, 0, &i->aliases, "Install" },
3936 { "WantedBy", config_parse_strv, 0, &i->wanted_by, "Install" },
3937 { "Also", config_parse_also, 0, NULL, "Install" },
3939 { NULL, NULL, 0, NULL, NULL }
3943 char *filename = NULL;
3950 STRV_FOREACH(p, paths->unit_path) {
3952 char *path, *should_free;
3955 should_free = path = strappend(arg_root, *p);
3961 if (!(filename = path_make_absolute(i->name, path))) {
3962 log_error("Out of memory");
3969 /* Ensure that we don't follow symlinks */
3970 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3971 if ((f = fdopen(fd, "re")))
3974 if (errno == ELOOP) {
3975 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3980 if (errno != ENOENT) {
3981 log_error("Failed to open %s: %m", filename);
3991 #if (defined(TARGET_FEDORA) || defined(TARGET_MANDRIVA) || defined(TARGET_SUSE) || defined(TARGET_MEEGO) || defined(TARGET_ALTLINUX)) && defined (HAVE_SYSV_COMPAT)
3993 if (endswith(i->name, ".service")) {
3997 if (asprintf(&sysv, SYSTEM_SYSVINIT_PATH "/%s", i->name) < 0) {
3998 log_error("Out of memory");
4002 sysv[strlen(sysv) - sizeof(".service") + 1] = 0;
4006 tmp_path = strappend (arg_root, sysv);
4007 exists = access (tmp_path, F_OK) >= 0;
4010 exists = access(sysv, F_OK) >= 0;
4016 const char *argv[] = {
4024 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", i->name);
4026 argv[1] = file_name_from_path(sysv);
4028 streq(verb, "enable") ? "on" :
4029 streq(verb, "disable") ? "off" : "--level=5";
4031 argv[3] = strappend("--root=", arg_root);
4033 log_info("Executing %s %s %s %s", argv[0], argv[1], strempty(argv[2]), strempty(argv[3]));
4035 if ((pid = fork()) < 0) {
4036 log_error("Failed to fork: %m");
4039 } else if (pid == 0) {
4040 execv(argv[0], (char**) argv);
4041 _exit(EXIT_FAILURE);
4046 if ((r = wait_for_terminate(pid, &status)) < 0)
4049 if (status.si_code == CLD_EXITED) {
4051 if (streq(verb, "is-enabled"))
4052 return status.si_status == 0 ? 1 : 0;
4054 if (status.si_status == 0)
4057 return status.si_status == 0 ? 0 : -EINVAL;
4068 log_error("Couldn't find %s.", i->name);
4074 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
4079 /* Consider unit files stored in /lib and /usr always enabled
4080 * if they have no [Install] data. */
4081 if (streq(verb, "is-enabled") &&
4082 strv_isempty(i->aliases) &&
4083 strv_isempty(i->wanted_by) &&
4084 !path_startswith(filename, "/etc")) {
4089 n_symlinks += strv_length(i->aliases);
4090 n_symlinks += strv_length(i->wanted_by);
4094 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
4097 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
4100 if ((r = mark_symlink_for_removal(filename)) < 0)
4103 if ((r = remove_marked_symlinks(config_path)) < 0)
4109 static char *get_config_path(void) {
4112 if (arg_user && arg_global)
4113 ret = strdup(USER_CONFIG_UNIT_PATH);
4116 if (user_config_home(&ret) < 0)
4120 ret = strdup(SYSTEM_CONFIG_UNIT_PATH);
4123 p = strappend (arg_root, ret);
4130 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
4134 char *config_path = NULL;
4137 const char *verb = args[0];
4139 dbus_error_init(&error);
4142 if ((r = lookup_paths_init(&paths, arg_user ? MANAGER_USER : MANAGER_SYSTEM)) < 0) {
4143 log_error("Failed to determine lookup paths: %s", strerror(-r));
4147 if (!(config_path = get_config_path())) {
4148 log_error("Failed to determine config path");
4153 will_install = hashmap_new(string_hash_func, string_compare_func);
4154 have_installed = hashmap_new(string_hash_func, string_compare_func);
4156 if (!will_install || !have_installed) {
4157 log_error("Failed to allocate unit sets.");
4162 if (!arg_defaults && streq(verb, "disable"))
4163 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
4164 log_error("Failed to allocate symlink sets.");
4169 for (j = 1; j < n; j++)
4170 if ((r = install_info_add(args[j])) < 0) {
4171 log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
4177 while ((i = hashmap_first(will_install))) {
4180 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
4182 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
4190 /* In test mode and found something */
4196 if (streq(verb, "is-enabled"))
4197 r = r > 0 ? 0 : -ENOENT;
4199 if (n_symlinks <= 0)
4200 log_warning("Unit files contain no applicable installation information. Ignoring.");
4203 /* Don't try to reload anything if the user asked us to not do this */
4205 /* Don't try to reload anything when updating a unit globally */
4207 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
4208 (arg_user || sd_booted() > 0) &&
4209 /* Don't try to reload anything if we are running in a chroot environment */
4210 (arg_user || running_in_chroot() <= 0 || arg_root) ) {
4213 if ((q = daemon_reload(bus, args, n)) < 0)
4219 install_info_hashmap_free(will_install);
4220 install_info_hashmap_free(have_installed);
4222 set_free_free(remove_symlinks_to);
4224 lookup_paths_free(&paths);
4231 static int systemctl_help(void) {
4233 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4234 "Send control commands to or query the systemd manager.\n\n"
4235 " -h --help Show this help\n"
4236 " --version Show package version\n"
4237 " -t --type=TYPE List only units of a particular type\n"
4238 " -p --property=NAME Show only properties by this name\n"
4239 " -a --all Show all units/properties, including dead/empty ones\n"
4240 " --failed Show only failed units\n"
4241 " --full Don't ellipsize unit names on output\n"
4242 " --fail When queueing a new job, fail if conflicting jobs are\n"
4244 " --ignore-dependencies\n"
4245 " When queueing a new job, ignore all its dependencies\n"
4246 " --kill-who=WHO Who to send signal to\n"
4247 " -s --signal=SIGNAL Which signal to send\n"
4248 " -H --host=[USER@]HOST\n"
4249 " Show information for remote host\n"
4250 " -P --privileged Acquire privileges before execution\n"
4251 " -q --quiet Suppress output\n"
4252 " --no-block Do not wait until operation finished\n"
4253 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4254 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4256 " --no-pager Do not pipe output into a pager\n"
4257 " --no-ask-password\n"
4258 " Do not ask for system passwords\n"
4259 " --order When generating graph for dot, show only order\n"
4260 " --require When generating graph for dot, show only requirement\n"
4261 " --root=path Use <root> as the root file system\n"
4262 " --system Connect to system manager\n"
4263 " --user Connect to user service manager\n"
4264 " --global Enable/disable unit files globally\n"
4265 " -f --force When enabling unit files, override existing symlinks\n"
4266 " When shutting down, execute action immediately\n"
4267 " --defaults When disabling unit files, remove default symlinks only\n\n"
4269 " list-units List units\n"
4270 " start [NAME...] Start (activate) one or more units\n"
4271 " stop [NAME...] Stop (deactivate) one or more units\n"
4272 " reload [NAME...] Reload one or more units\n"
4273 " restart [NAME...] Start or restart one or more units\n"
4274 " try-restart [NAME...] Restart one or more units if active\n"
4275 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4276 " otherwise start or restart\n"
4277 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4278 " otherwise restart if active\n"
4279 " isolate [NAME] Start one unit and stop all others\n"
4280 " kill [NAME...] Send signal to processes of a unit\n"
4281 " is-active [NAME...] Check whether units are active\n"
4282 " status [NAME...|PID...] Show runtime status of one or more units\n"
4283 " show [NAME...|JOB...] Show properties of one or more\n"
4284 " units/jobs or the manager\n"
4285 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4287 " enable [NAME...] Enable one or more unit files\n"
4288 " disable [NAME...] Disable one or more unit files\n"
4289 " is-enabled [NAME...] Check whether unit files are enabled\n"
4290 " load [NAME...] Load one or more units\n"
4291 " list-jobs List jobs\n"
4292 " cancel [JOB...] Cancel all, one, or more jobs\n"
4293 " monitor Monitor unit/job changes\n"
4294 " dump Dump server status\n"
4295 " dot Dump dependency graph for dot(1)\n"
4296 " snapshot [NAME] Create a snapshot\n"
4297 " delete [NAME...] Remove one or more snapshots\n"
4298 " daemon-reload Reload systemd manager configuration\n"
4299 " daemon-reexec Reexecute systemd manager\n"
4300 " show-environment Dump environment\n"
4301 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4302 " unset-environment [NAME...] Unset one or more environment variables\n"
4303 " default Enter system default mode\n"
4304 " rescue Enter system rescue mode\n"
4305 " emergency Enter system emergency mode\n"
4306 " halt Shut down and halt the system\n"
4307 " poweroff Shut down and power-off the system\n"
4308 " reboot Shut down and reboot the system\n"
4309 " kexec Shut down and reboot the system with kexec\n"
4310 " exit Ask for user instance termination\n",
4311 program_invocation_short_name);
4316 static int halt_help(void) {
4318 printf("%s [OPTIONS...]\n\n"
4319 "%s the system.\n\n"
4320 " --help Show this help\n"
4321 " --halt Halt the machine\n"
4322 " -p --poweroff Switch off the machine\n"
4323 " --reboot Reboot the machine\n"
4324 " -f --force Force immediate halt/power-off/reboot\n"
4325 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4326 " -d --no-wtmp Don't write wtmp record\n"
4327 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4328 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4329 program_invocation_short_name,
4330 arg_action == ACTION_REBOOT ? "Reboot" :
4331 arg_action == ACTION_POWEROFF ? "Power off" :
4337 static int shutdown_help(void) {
4339 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4340 "Shut down the system.\n\n"
4341 " --help Show this help\n"
4342 " -H --halt Halt the machine\n"
4343 " -P --poweroff Power-off the machine\n"
4344 " -r --reboot Reboot the machine\n"
4345 " -h Equivalent to --poweroff, overriden by --halt\n"
4346 " -k Don't halt/power-off/reboot, just send warnings\n"
4347 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4348 " -c Cancel a pending shutdown\n",
4349 program_invocation_short_name);
4354 static int telinit_help(void) {
4356 printf("%s [OPTIONS...] {COMMAND}\n\n"
4357 "Send control commands to the init daemon.\n\n"
4358 " --help Show this help\n"
4359 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4361 " 0 Power-off the machine\n"
4362 " 6 Reboot the machine\n"
4363 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4364 " 1, s, S Enter rescue mode\n"
4365 " q, Q Reload init daemon configuration\n"
4366 " u, U Reexecute init daemon\n",
4367 program_invocation_short_name);
4372 static int runlevel_help(void) {
4374 printf("%s [OPTIONS...]\n\n"
4375 "Prints the previous and current runlevel of the init system.\n\n"
4376 " --help Show this help\n",
4377 program_invocation_short_name);
4382 static int systemctl_parse_argv(int argc, char *argv[]) {
4386 ARG_IGNORE_DEPENDENCIES,
4402 ARG_NO_ASK_PASSWORD,
4406 static const struct option options[] = {
4407 { "help", no_argument, NULL, 'h' },
4408 { "version", no_argument, NULL, ARG_VERSION },
4409 { "type", required_argument, NULL, 't' },
4410 { "property", required_argument, NULL, 'p' },
4411 { "all", no_argument, NULL, 'a' },
4412 { "failed", no_argument, NULL, ARG_FAILED },
4413 { "full", no_argument, NULL, ARG_FULL },
4414 { "fail", no_argument, NULL, ARG_FAIL },
4415 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4416 { "user", no_argument, NULL, ARG_USER },
4417 { "system", no_argument, NULL, ARG_SYSTEM },
4418 { "global", no_argument, NULL, ARG_GLOBAL },
4419 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4420 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4421 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4422 { "quiet", no_argument, NULL, 'q' },
4423 { "order", no_argument, NULL, ARG_ORDER },
4424 { "require", no_argument, NULL, ARG_REQUIRE },
4425 { "root", required_argument, NULL, ARG_ROOT },
4426 { "force", no_argument, NULL, 'f' },
4427 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4428 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4429 { "kill-mode", required_argument, NULL, ARG_KILL_MODE }, /* undocumented on purpose */
4430 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4431 { "signal", required_argument, NULL, 's' },
4432 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4433 { "host", required_argument, NULL, 'H' },
4434 { "privileged",no_argument, NULL, 'P' },
4435 { NULL, 0, NULL, 0 }
4443 /* Only when running as systemctl we ask for passwords */
4444 arg_ask_password = true;
4446 while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:P", options, NULL)) >= 0) {
4455 puts(PACKAGE_STRING);
4457 puts(SYSTEMD_FEATURES);
4467 if (!(l = strv_append(arg_property, optarg)))
4470 strv_free(arg_property);
4473 /* If the user asked for a particular
4474 * property, show it to him, even if it is
4485 arg_job_mode = "fail";
4488 case ARG_IGNORE_DEPENDENCIES:
4489 arg_job_mode = "ignore-dependencies";
4501 arg_no_block = true;
4505 arg_no_pager = true;
4513 arg_dot = DOT_ORDER;
4517 arg_dot = DOT_REQUIRE;
4541 arg_no_reload = true;
4550 arg_defaults = true;
4554 arg_kill_who = optarg;
4558 arg_kill_mode = optarg;
4562 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4563 log_error("Failed to parse signal string %s.", optarg);
4568 case ARG_NO_ASK_PASSWORD:
4569 arg_ask_password = false;
4573 arg_transport = TRANSPORT_POLKIT;
4577 arg_transport = TRANSPORT_SSH;
4585 log_error("Unknown option code %c", c);
4590 if (arg_transport != TRANSPORT_NORMAL && arg_user) {
4591 log_error("Cannot access user instance remotely.");
4598 static int halt_parse_argv(int argc, char *argv[]) {
4607 static const struct option options[] = {
4608 { "help", no_argument, NULL, ARG_HELP },
4609 { "halt", no_argument, NULL, ARG_HALT },
4610 { "poweroff", no_argument, NULL, 'p' },
4611 { "reboot", no_argument, NULL, ARG_REBOOT },
4612 { "force", no_argument, NULL, 'f' },
4613 { "wtmp-only", no_argument, NULL, 'w' },
4614 { "no-wtmp", no_argument, NULL, 'd' },
4615 { "no-sync", no_argument, NULL, 'n' },
4616 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4617 { NULL, 0, NULL, 0 }
4625 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4626 if (runlevel == '0' || runlevel == '6')
4627 arg_immediate = true;
4629 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4637 arg_action = ACTION_HALT;
4641 if (arg_action != ACTION_REBOOT)
4642 arg_action = ACTION_POWEROFF;
4646 arg_action = ACTION_REBOOT;
4650 arg_immediate = true;
4671 /* Compatibility nops */
4678 log_error("Unknown option code %c", c);
4683 if (optind < argc) {
4684 log_error("Too many arguments.");
4691 static int parse_time_spec(const char *t, usec_t *_u) {
4695 if (streq(t, "now"))
4697 else if (!strchr(t, ':')) {
4700 if (safe_atou64(t, &u) < 0)
4703 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4712 hour = strtol(t, &e, 10);
4713 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4716 minute = strtol(e+1, &e, 10);
4717 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4720 n = now(CLOCK_REALTIME);
4721 s = (time_t) (n / USEC_PER_SEC);
4724 assert_se(localtime_r(&s, &tm));
4726 tm.tm_hour = (int) hour;
4727 tm.tm_min = (int) minute;
4730 assert_se(s = mktime(&tm));
4732 *_u = (usec_t) s * USEC_PER_SEC;
4735 *_u += USEC_PER_DAY;
4741 static bool kexec_loaded(void) {
4742 bool loaded = false;
4745 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4753 static int shutdown_parse_argv(int argc, char *argv[]) {
4760 static const struct option options[] = {
4761 { "help", no_argument, NULL, ARG_HELP },
4762 { "halt", no_argument, NULL, 'H' },
4763 { "poweroff", no_argument, NULL, 'P' },
4764 { "reboot", no_argument, NULL, 'r' },
4765 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4766 { NULL, 0, NULL, 0 }
4774 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4782 arg_action = ACTION_HALT;
4786 arg_action = ACTION_POWEROFF;
4791 arg_action = ACTION_KEXEC;
4793 arg_action = ACTION_REBOOT;
4797 if (arg_action != ACTION_HALT)
4798 arg_action = ACTION_POWEROFF;
4811 /* Compatibility nops */
4815 arg_action = ACTION_CANCEL_SHUTDOWN;
4822 log_error("Unknown option code %c", c);
4827 if (argc > optind) {
4828 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4829 log_error("Failed to parse time specification: %s", argv[optind]);
4833 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4835 /* We skip the time argument */
4836 if (argc > optind + 1)
4837 arg_wall = argv + optind + 1;
4844 static int telinit_parse_argv(int argc, char *argv[]) {
4851 static const struct option options[] = {
4852 { "help", no_argument, NULL, ARG_HELP },
4853 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4854 { NULL, 0, NULL, 0 }
4857 static const struct {
4861 { '0', ACTION_POWEROFF },
4862 { '6', ACTION_REBOOT },
4863 { '1', ACTION_RESCUE },
4864 { '2', ACTION_RUNLEVEL2 },
4865 { '3', ACTION_RUNLEVEL3 },
4866 { '4', ACTION_RUNLEVEL4 },
4867 { '5', ACTION_RUNLEVEL5 },
4868 { 's', ACTION_RESCUE },
4869 { 'S', ACTION_RESCUE },
4870 { 'q', ACTION_RELOAD },
4871 { 'Q', ACTION_RELOAD },
4872 { 'u', ACTION_REEXEC },
4873 { 'U', ACTION_REEXEC }
4882 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4897 log_error("Unknown option code %c", c);
4902 if (optind >= argc) {
4907 if (optind + 1 < argc) {
4908 log_error("Too many arguments.");
4912 if (strlen(argv[optind]) != 1) {
4913 log_error("Expected single character argument.");
4917 for (i = 0; i < ELEMENTSOF(table); i++)
4918 if (table[i].from == argv[optind][0])
4921 if (i >= ELEMENTSOF(table)) {
4922 log_error("Unknown command %s.", argv[optind]);
4926 arg_action = table[i].to;
4933 static int runlevel_parse_argv(int argc, char *argv[]) {
4939 static const struct option options[] = {
4940 { "help", no_argument, NULL, ARG_HELP },
4941 { NULL, 0, NULL, 0 }
4949 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4960 log_error("Unknown option code %c", c);
4965 if (optind < argc) {
4966 log_error("Too many arguments.");
4973 static int parse_argv(int argc, char *argv[]) {
4977 if (program_invocation_short_name) {
4979 if (strstr(program_invocation_short_name, "halt")) {
4980 arg_action = ACTION_HALT;
4981 return halt_parse_argv(argc, argv);
4982 } else if (strstr(program_invocation_short_name, "poweroff")) {
4983 arg_action = ACTION_POWEROFF;
4984 return halt_parse_argv(argc, argv);
4985 } else if (strstr(program_invocation_short_name, "reboot")) {
4987 arg_action = ACTION_KEXEC;
4989 arg_action = ACTION_REBOOT;
4990 return halt_parse_argv(argc, argv);
4991 } else if (strstr(program_invocation_short_name, "shutdown")) {
4992 arg_action = ACTION_POWEROFF;
4993 return shutdown_parse_argv(argc, argv);
4994 } else if (strstr(program_invocation_short_name, "init")) {
4996 if (sd_booted() > 0) {
4997 arg_action = ACTION_INVALID;
4998 return telinit_parse_argv(argc, argv);
5000 /* Hmm, so some other init system is
5001 * running, we need to forward this
5002 * request to it. For now we simply
5003 * guess that it is Upstart. */
5005 execv("/lib/upstart/telinit", argv);
5007 log_error("Couldn't find an alternative telinit implementation to spawn.");
5011 } else if (strstr(program_invocation_short_name, "runlevel")) {
5012 arg_action = ACTION_RUNLEVEL;
5013 return runlevel_parse_argv(argc, argv);
5017 arg_action = ACTION_SYSTEMCTL;
5018 return systemctl_parse_argv(argc, argv);
5021 static int action_to_runlevel(void) {
5023 static const char table[_ACTION_MAX] = {
5024 [ACTION_HALT] = '0',
5025 [ACTION_POWEROFF] = '0',
5026 [ACTION_REBOOT] = '6',
5027 [ACTION_RUNLEVEL2] = '2',
5028 [ACTION_RUNLEVEL3] = '3',
5029 [ACTION_RUNLEVEL4] = '4',
5030 [ACTION_RUNLEVEL5] = '5',
5031 [ACTION_RESCUE] = '1'
5034 assert(arg_action < _ACTION_MAX);
5036 return table[arg_action];
5039 static int talk_upstart(void) {
5040 DBusMessage *m = NULL, *reply = NULL;
5042 int previous, rl, r;
5044 env1_buf[] = "RUNLEVEL=X",
5045 env2_buf[] = "PREVLEVEL=X";
5046 char *env1 = env1_buf, *env2 = env2_buf;
5047 const char *emit = "runlevel";
5048 dbus_bool_t b_false = FALSE;
5049 DBusMessageIter iter, sub;
5050 DBusConnection *bus;
5052 dbus_error_init(&error);
5054 if (!(rl = action_to_runlevel()))
5057 if (utmp_get_runlevel(&previous, NULL) < 0)
5060 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
5061 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
5066 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
5071 if ((r = bus_check_peercred(bus)) < 0) {
5072 log_error("Failed to verify owner of bus.");
5076 if (!(m = dbus_message_new_method_call(
5077 "com.ubuntu.Upstart",
5078 "/com/ubuntu/Upstart",
5079 "com.ubuntu.Upstart0_6",
5082 log_error("Could not allocate message.");
5087 dbus_message_iter_init_append(m, &iter);
5089 env1_buf[sizeof(env1_buf)-2] = rl;
5090 env2_buf[sizeof(env2_buf)-2] = previous;
5092 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5093 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5094 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5095 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5096 !dbus_message_iter_close_container(&iter, &sub) ||
5097 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5098 log_error("Could not append arguments to message.");
5103 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5105 if (error_is_no_service(&error)) {
5110 log_error("Failed to issue method call: %s", bus_error_message(&error));
5119 dbus_message_unref(m);
5122 dbus_message_unref(reply);
5125 dbus_connection_flush(bus);
5126 dbus_connection_close(bus);
5127 dbus_connection_unref(bus);
5130 dbus_error_free(&error);
5135 static int talk_initctl(void) {
5136 struct init_request request;
5140 if (!(rl = action_to_runlevel()))
5144 request.magic = INIT_MAGIC;
5145 request.sleeptime = 0;
5146 request.cmd = INIT_CMD_RUNLVL;
5147 request.runlevel = rl;
5149 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5151 if (errno == ENOENT)
5154 log_error("Failed to open "INIT_FIFO": %m");
5159 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5160 close_nointr_nofail(fd);
5163 log_error("Failed to write to "INIT_FIFO": %m");
5164 return errno ? -errno : -EIO;
5170 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5172 static const struct {
5180 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
5182 { "list-units", LESS, 1, list_units },
5183 { "list-jobs", EQUAL, 1, list_jobs },
5184 { "clear-jobs", EQUAL, 1, daemon_reload },
5185 { "load", MORE, 2, load_unit },
5186 { "cancel", MORE, 2, cancel_job },
5187 { "start", MORE, 2, start_unit },
5188 { "stop", MORE, 2, start_unit },
5189 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5190 { "reload", MORE, 2, start_unit },
5191 { "restart", MORE, 2, start_unit },
5192 { "try-restart", MORE, 2, start_unit },
5193 { "reload-or-restart", MORE, 2, start_unit },
5194 { "reload-or-try-restart", MORE, 2, start_unit },
5195 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5196 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5197 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5198 { "isolate", EQUAL, 2, start_unit },
5199 { "kill", MORE, 2, kill_unit },
5200 { "is-active", MORE, 2, check_unit },
5201 { "check", MORE, 2, check_unit },
5202 { "show", MORE, 1, show },
5203 { "status", MORE, 2, show },
5204 { "monitor", EQUAL, 1, monitor },
5205 { "dump", EQUAL, 1, dump },
5206 { "dot", EQUAL, 1, dot },
5207 { "snapshot", LESS, 2, snapshot },
5208 { "delete", MORE, 2, delete_snapshot },
5209 { "daemon-reload", EQUAL, 1, daemon_reload },
5210 { "daemon-reexec", EQUAL, 1, daemon_reload },
5211 { "show-environment", EQUAL, 1, show_enviroment },
5212 { "set-environment", MORE, 2, set_environment },
5213 { "unset-environment", MORE, 2, set_environment },
5214 { "halt", EQUAL, 1, start_special },
5215 { "poweroff", EQUAL, 1, start_special },
5216 { "reboot", EQUAL, 1, start_special },
5217 { "kexec", EQUAL, 1, start_special },
5218 { "default", EQUAL, 1, start_special },
5219 { "rescue", EQUAL, 1, start_special },
5220 { "emergency", EQUAL, 1, start_special },
5221 { "exit", EQUAL, 1, start_special },
5222 { "reset-failed", MORE, 1, reset_failed },
5223 { "enable", MORE, 2, enable_unit },
5224 { "disable", MORE, 2, enable_unit },
5225 { "is-enabled", MORE, 2, enable_unit }
5235 left = argc - optind;
5238 /* Special rule: no arguments means "list-units" */
5241 if (streq(argv[optind], "help")) {
5246 for (i = 0; i < ELEMENTSOF(verbs); i++)
5247 if (streq(argv[optind], verbs[i].verb))
5250 if (i >= ELEMENTSOF(verbs)) {
5251 log_error("Unknown operation %s", argv[optind]);
5256 switch (verbs[i].argc_cmp) {
5259 if (left != verbs[i].argc) {
5260 log_error("Invalid number of arguments.");
5267 if (left < verbs[i].argc) {
5268 log_error("Too few arguments.");
5275 if (left > verbs[i].argc) {
5276 log_error("Too many arguments.");
5283 assert_not_reached("Unknown comparison operator.");
5286 /* Require a bus connection for all operations but
5288 if (!streq(verbs[i].verb, "enable") && !streq(verbs[i].verb, "disable")) {
5290 if (running_in_chroot() > 0) {
5291 log_info("Running in chroot, ignoring request.");
5296 log_error("Failed to get D-Bus connection: %s", error->message);
5301 return verbs[i].dispatch(bus, argv + optind, left);
5304 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
5306 struct msghdr msghdr;
5308 union sockaddr_union sockaddr;
5309 struct shutdownd_command c;
5314 c.dry_run = dry_run;
5318 strncpy(c.wall_message, message, sizeof(c.wall_message));
5320 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
5324 sockaddr.sa.sa_family = AF_UNIX;
5325 sockaddr.un.sun_path[0] = 0;
5326 strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5329 iovec.iov_base = (char*) &c;
5330 iovec.iov_len = sizeof(c);
5333 msghdr.msg_name = &sockaddr;
5334 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5336 msghdr.msg_iov = &iovec;
5337 msghdr.msg_iovlen = 1;
5339 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5340 close_nointr_nofail(fd);
5344 close_nointr_nofail(fd);
5348 static int reload_with_fallback(DBusConnection *bus) {
5351 /* First, try systemd via D-Bus. */
5352 if (daemon_reload(bus, NULL, 0) > 0)
5356 /* Nothing else worked, so let's try signals */
5357 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5359 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5360 log_error("kill() failed: %m");
5367 static int start_with_fallback(DBusConnection *bus) {
5370 /* First, try systemd via D-Bus. */
5371 if (start_unit(bus, NULL, 0) >= 0)
5375 /* Hmm, talking to systemd via D-Bus didn't work. Then
5376 * let's try to talk to Upstart via D-Bus. */
5377 if (talk_upstart() > 0)
5380 /* Nothing else worked, so let's try
5382 if (talk_initctl() > 0)
5385 log_error("Failed to talk to init daemon.");
5389 warn_wall(arg_action);
5393 static int halt_main(DBusConnection *bus) {
5396 if (geteuid() != 0) {
5397 log_error("Must be root.");
5403 char date[FORMAT_TIMESTAMP_MAX];
5405 m = strv_join(arg_wall, " ");
5406 r = send_shutdownd(arg_when,
5407 arg_action == ACTION_HALT ? 'H' :
5408 arg_action == ACTION_POWEROFF ? 'P' :
5416 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5418 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5419 format_timestamp(date, sizeof(date), arg_when));
5424 if (!arg_dry && !arg_immediate)
5425 return start_with_fallback(bus);
5428 if (sd_booted() > 0)
5429 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5430 else if ((r = utmp_put_shutdown(0)) < 0)
5431 log_warning("Failed to write utmp record: %s", strerror(-r));
5440 /* Make sure C-A-D is handled by the kernel from this
5442 reboot(RB_ENABLE_CAD);
5444 switch (arg_action) {
5447 log_info("Halting.");
5448 reboot(RB_HALT_SYSTEM);
5451 case ACTION_POWEROFF:
5452 log_info("Powering off.");
5453 reboot(RB_POWER_OFF);
5457 log_info("Rebooting.");
5458 reboot(RB_AUTOBOOT);
5462 assert_not_reached("Unknown halt action.");
5465 /* We should never reach this. */
5469 static int runlevel_main(void) {
5470 int r, runlevel, previous;
5472 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5473 printf("unknown\n");
5478 previous <= 0 ? 'N' : previous,
5479 runlevel <= 0 ? 'N' : runlevel);
5484 static void agent_close(void) {
5490 /* Inform agent that we are done */
5491 kill(agent_pid, SIGTERM);
5492 kill(agent_pid, SIGCONT);
5493 wait_for_terminate(agent_pid, &dummy);
5497 int main(int argc, char*argv[]) {
5498 int r, retval = EXIT_FAILURE;
5499 DBusConnection *bus = NULL;
5502 dbus_error_init(&error);
5504 log_parse_environment();
5507 if ((r = parse_argv(argc, argv)) < 0)
5510 retval = EXIT_SUCCESS;
5514 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5515 * let's shortcut this */
5516 if (arg_action == ACTION_RUNLEVEL) {
5517 r = runlevel_main();
5518 retval = r < 0 ? EXIT_FAILURE : r;
5522 if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5523 log_info("Running in chroot, ignoring request.");
5528 if (arg_transport == TRANSPORT_NORMAL)
5529 bus_connect(arg_user ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5530 else if (arg_transport == TRANSPORT_POLKIT) {
5531 bus_connect_system_polkit(&bus, &error);
5532 private_bus = false;
5533 } else if (arg_transport == TRANSPORT_SSH) {
5534 bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5535 private_bus = false;
5537 assert_not_reached("Uh, invalid transport...");
5539 switch (arg_action) {
5541 case ACTION_SYSTEMCTL:
5542 r = systemctl_main(bus, argc, argv, &error);
5546 case ACTION_POWEROFF:
5552 case ACTION_RUNLEVEL2:
5553 case ACTION_RUNLEVEL3:
5554 case ACTION_RUNLEVEL4:
5555 case ACTION_RUNLEVEL5:
5557 case ACTION_EMERGENCY:
5558 case ACTION_DEFAULT:
5559 r = start_with_fallback(bus);
5564 r = reload_with_fallback(bus);
5567 case ACTION_CANCEL_SHUTDOWN:
5568 r = send_shutdownd(0, 0, false, false, NULL);
5571 case ACTION_INVALID:
5572 case ACTION_RUNLEVEL:
5574 assert_not_reached("Unknown action");
5577 retval = r < 0 ? EXIT_FAILURE : r;
5582 dbus_connection_flush(bus);
5583 dbus_connection_close(bus);
5584 dbus_connection_unref(bus);
5587 dbus_error_free(&error);
5591 strv_free(arg_property);