1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <sys/reboot.h>
28 #include <sys/ioctl.h>
32 #include <sys/socket.h>
35 #include <sys/prctl.h>
36 #include <dbus/dbus.h>
42 #include "utmp-wtmp.h"
46 #include "dbus-common.h"
47 #include "cgroup-show.h"
48 #include "cgroup-util.h"
50 #include "path-lookup.h"
51 #include "conf-parser.h"
52 #include "sd-daemon.h"
53 #include "shutdownd.h"
54 #include "exit-status.h"
55 #include "bus-errors.h"
57 #include "unit-name.h"
60 static const char *arg_type = NULL;
61 static char **arg_property = NULL;
62 static bool arg_all = false;
63 static const char *arg_job_mode = "replace";
64 static bool arg_user = false;
65 static bool arg_global = false;
66 static bool arg_immediate = false;
67 static bool arg_no_block = false;
68 static bool arg_no_pager = false;
69 static bool arg_no_wtmp = false;
70 static bool arg_no_sync = false;
71 static bool arg_no_wall = false;
72 static bool arg_no_reload = false;
73 static bool arg_dry = false;
74 static bool arg_quiet = false;
75 static bool arg_full = false;
76 static bool arg_force = false;
77 static bool arg_defaults = false;
78 static bool arg_ask_password = false;
79 static bool arg_failed = false;
80 static char **arg_wall = NULL;
81 static const char *arg_kill_who = NULL;
82 static const char *arg_kill_mode = NULL;
83 static const char *arg_root = NULL;
84 static int arg_signal = SIGTERM;
85 static usec_t arg_when = 0;
104 ACTION_CANCEL_SHUTDOWN,
106 } arg_action = ACTION_SYSTEMCTL;
112 static enum transport {
116 } arg_transport = TRANSPORT_NORMAL;
117 static const char *arg_host = NULL;
119 static bool private_bus = false;
121 static pid_t agent_pid = 0;
123 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
125 static void pager_open_if_enabled(void) {
130 static bool on_tty(void) {
133 /* Note that this is invoked relatively early, before we start
134 * the pager. That means the value we return reflects whether
135 * we originally were started on a tty, not if we currently
136 * are. But this is intended, since we want colour and so on
137 * when run in our own pager. */
139 if (_unlikely_(t < 0))
140 t = isatty(STDOUT_FILENO) > 0;
145 static void spawn_ask_password_agent(void) {
151 /* We check STDIN here, not STDOUT, since this is about input,
153 if (!isatty(STDIN_FILENO))
156 if (!arg_ask_password)
164 /* Spawns a temporary TTY agent, making sure it goes away when
167 if ((agent_pid = fork()) < 0)
170 if (agent_pid == 0) {
174 bool stdout_is_tty, stderr_is_tty;
176 /* Make sure the agent goes away when the parent dies */
177 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
180 /* Check whether our parent died before we were able
181 * to set the death signal */
182 if (getppid() != parent)
185 /* Don't leak fds to the agent */
186 close_all_fds(NULL, 0);
188 stdout_is_tty = isatty(STDOUT_FILENO);
189 stderr_is_tty = isatty(STDERR_FILENO);
191 if (!stdout_is_tty || !stderr_is_tty) {
192 /* Detach from stdout/stderr. and reopen
193 * /dev/tty for them. This is important to
194 * ensure that when systemctl is started via
195 * popen() or a similar call that expects to
196 * read EOF we actually do generate EOF and
197 * not delay this indefinitely by because we
198 * keep an unused copy of stdin around. */
199 if ((fd = open("/dev/tty", O_WRONLY)) < 0) {
200 log_error("Failed to open /dev/tty: %m");
205 dup2(fd, STDOUT_FILENO);
208 dup2(fd, STDERR_FILENO);
214 execl(SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, "--watch", NULL);
216 log_error("Unable to execute agent: %m");
221 static const char *ansi_highlight(bool b) {
226 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
229 static const char *ansi_highlight_green(bool b) {
234 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
237 static bool error_is_no_service(const DBusError *error) {
240 if (!dbus_error_is_set(error))
243 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
246 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
249 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
252 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
255 if (!dbus_error_is_set(error))
258 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
259 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
260 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
261 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
262 return EXIT_NOPERMISSION;
264 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
265 return EXIT_NOTINSTALLED;
267 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
268 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
269 return EXIT_NOTIMPLEMENTED;
271 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
272 return EXIT_NOTCONFIGURED;
280 static void warn_wall(enum action action) {
281 static const char *table[_ACTION_MAX] = {
282 [ACTION_HALT] = "The system is going down for system halt NOW!",
283 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
284 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
285 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
286 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
287 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
296 if (!(p = strv_join(arg_wall, " "))) {
297 log_error("Failed to join strings.");
313 utmp_wall(table[action], NULL);
318 const char *description;
319 const char *load_state;
320 const char *active_state;
321 const char *sub_state;
322 const char *following;
323 const char *unit_path;
325 const char *job_type;
326 const char *job_path;
329 static int compare_unit_info(const void *a, const void *b) {
331 const struct unit_info *u = a, *v = b;
333 d1 = strrchr(u->id, '.');
334 d2 = strrchr(v->id, '.');
339 if ((r = strcasecmp(d1, d2)) != 0)
343 return strcasecmp(u->id, v->id);
346 static bool output_show_unit(const struct unit_info *u) {
350 return streq(u->active_state, "failed");
352 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
353 streq(dot+1, arg_type))) &&
354 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0);
357 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
358 unsigned active_len, sub_len, job_len, n_shown = 0;
359 const struct unit_info *u;
361 active_len = sizeof("ACTIVE")-1;
362 sub_len = sizeof("SUB")-1;
363 job_len = sizeof("JOB")-1;
365 for (u = unit_infos; u < unit_infos + c; u++) {
366 if (!output_show_unit(u))
369 active_len = MAX(active_len, strlen(u->active_state));
370 sub_len = MAX(sub_len, strlen(u->sub_state));
372 job_len = MAX(job_len, strlen(u->job_type));
376 printf("%-25s %-6s %-*s %-*s %-*s", "UNIT", "LOAD",
377 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
378 if (columns() >= 80+12 || arg_full || !arg_no_pager)
379 printf(" %s\n", "DESCRIPTION");
384 for (u = unit_infos; u < unit_infos + c; u++) {
387 const char *on_loaded, *off_loaded;
388 const char *on_active, *off_active;
390 if (!output_show_unit(u))
395 if (!streq(u->load_state, "loaded") &&
396 !streq(u->load_state, "banned")) {
397 on_loaded = ansi_highlight(true);
398 off_loaded = ansi_highlight(false);
400 on_loaded = off_loaded = "";
402 if (streq(u->active_state, "failed")) {
403 on_active = ansi_highlight(true);
404 off_active = ansi_highlight(false);
406 on_active = off_active = "";
408 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
410 printf("%-25s %s%-6s%s %s%-*s %-*s%s%n",
412 on_loaded, u->load_state, off_loaded,
413 on_active, active_len, u->active_state,
414 sub_len, u->sub_state, off_active,
419 a -= strlen(on_loaded) + strlen(off_loaded);
420 a -= strlen(on_active) + strlen(off_active);
423 printf(" %-*s", job_len, u->job_type);
427 if (a + b + 1 < columns()) {
429 printf(" %-*s", job_len, "");
431 if (arg_full || !arg_no_pager)
432 printf(" %s", u->description);
434 printf(" %.*s", columns() - a - b - 1, u->description);
441 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
442 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
443 "SUB = The low-level unit activation state, values depend on unit type.\n"
444 "JOB = Pending job for the unit.\n");
447 printf("\n%u units listed.\n", n_shown);
449 printf("\n%u units listed. Pass --all to see inactive units, too.\n", n_shown);
453 static int list_units(DBusConnection *bus, char **args, unsigned n) {
454 DBusMessage *m = NULL, *reply = NULL;
457 DBusMessageIter iter, sub, sub2;
458 unsigned c = 0, n_units = 0;
459 struct unit_info *unit_infos = NULL;
461 dbus_error_init(&error);
465 pager_open_if_enabled();
467 if (!(m = dbus_message_new_method_call(
468 "org.freedesktop.systemd1",
469 "/org/freedesktop/systemd1",
470 "org.freedesktop.systemd1.Manager",
472 log_error("Could not allocate message.");
476 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
477 log_error("Failed to issue method call: %s", bus_error_message(&error));
482 if (!dbus_message_iter_init(reply, &iter) ||
483 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
484 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
485 log_error("Failed to parse reply.");
490 dbus_message_iter_recurse(&iter, &sub);
492 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
495 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
496 log_error("Failed to parse reply.");
504 n_units = MAX(2*c, 16);
505 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
508 log_error("Failed to allocate unit array.");
518 dbus_message_iter_recurse(&sub, &sub2);
520 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
521 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
522 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
523 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
524 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
525 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
526 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
527 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
528 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
529 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
530 log_error("Failed to parse reply.");
535 dbus_message_iter_next(&sub);
540 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
541 output_units_list(unit_infos, c);
548 dbus_message_unref(m);
551 dbus_message_unref(reply);
555 dbus_error_free(&error);
560 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
561 static const char * const colors[] = {
562 "Requires", "[color=\"black\"]",
563 "RequiresOverridable", "[color=\"black\"]",
564 "Requisite", "[color=\"darkblue\"]",
565 "RequisiteOverridable", "[color=\"darkblue\"]",
566 "Wants", "[color=\"darkgrey\"]",
567 "Conflicts", "[color=\"red\"]",
568 "ConflictedBy", "[color=\"red\"]",
569 "After", "[color=\"green\"]"
572 const char *c = NULL;
579 for (i = 0; i < ELEMENTSOF(colors); i += 2)
580 if (streq(colors[i], prop)) {
588 if (arg_dot != DOT_ALL)
589 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
592 switch (dbus_message_iter_get_arg_type(iter)) {
594 case DBUS_TYPE_ARRAY:
596 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
599 dbus_message_iter_recurse(iter, &sub);
601 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
604 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
605 dbus_message_iter_get_basic(&sub, &s);
606 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
608 dbus_message_iter_next(&sub);
618 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
619 DBusMessage *m = NULL, *reply = NULL;
620 const char *interface = "org.freedesktop.systemd1.Unit";
623 DBusMessageIter iter, sub, sub2, sub3;
628 dbus_error_init(&error);
630 if (!(m = dbus_message_new_method_call(
631 "org.freedesktop.systemd1",
633 "org.freedesktop.DBus.Properties",
635 log_error("Could not allocate message.");
640 if (!dbus_message_append_args(m,
641 DBUS_TYPE_STRING, &interface,
642 DBUS_TYPE_INVALID)) {
643 log_error("Could not append arguments to message.");
648 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
649 log_error("Failed to issue method call: %s", bus_error_message(&error));
654 if (!dbus_message_iter_init(reply, &iter) ||
655 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
656 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
657 log_error("Failed to parse reply.");
662 dbus_message_iter_recurse(&iter, &sub);
664 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
667 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
668 log_error("Failed to parse reply.");
673 dbus_message_iter_recurse(&sub, &sub2);
675 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
676 log_error("Failed to parse reply.");
681 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
682 log_error("Failed to parse reply.");
687 dbus_message_iter_recurse(&sub2, &sub3);
689 if (dot_one_property(name, prop, &sub3)) {
690 log_error("Failed to parse reply.");
695 dbus_message_iter_next(&sub);
702 dbus_message_unref(m);
705 dbus_message_unref(reply);
707 dbus_error_free(&error);
712 static int dot(DBusConnection *bus, char **args, unsigned n) {
713 DBusMessage *m = NULL, *reply = NULL;
716 DBusMessageIter iter, sub, sub2;
718 dbus_error_init(&error);
722 if (!(m = dbus_message_new_method_call(
723 "org.freedesktop.systemd1",
724 "/org/freedesktop/systemd1",
725 "org.freedesktop.systemd1.Manager",
727 log_error("Could not allocate message.");
731 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
732 log_error("Failed to issue method call: %s", bus_error_message(&error));
737 if (!dbus_message_iter_init(reply, &iter) ||
738 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
739 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
740 log_error("Failed to parse reply.");
745 printf("digraph systemd {\n");
747 dbus_message_iter_recurse(&iter, &sub);
748 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
749 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
751 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
752 log_error("Failed to parse reply.");
757 dbus_message_iter_recurse(&sub, &sub2);
759 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
760 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
761 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
762 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
763 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
764 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
765 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
766 log_error("Failed to parse reply.");
771 if ((r = dot_one(bus, id, unit_path)) < 0)
774 /* printf("\t\"%s\";\n", id); */
775 dbus_message_iter_next(&sub);
780 log_info(" Color legend: black = Requires\n"
781 " dark blue = Requisite\n"
782 " dark grey = Wants\n"
786 if (isatty(fileno(stdout)))
787 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
788 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
794 dbus_message_unref(m);
797 dbus_message_unref(reply);
799 dbus_error_free(&error);
804 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
805 DBusMessage *m = NULL, *reply = NULL;
808 DBusMessageIter iter, sub, sub2;
811 dbus_error_init(&error);
815 pager_open_if_enabled();
817 if (!(m = dbus_message_new_method_call(
818 "org.freedesktop.systemd1",
819 "/org/freedesktop/systemd1",
820 "org.freedesktop.systemd1.Manager",
822 log_error("Could not allocate message.");
826 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
827 log_error("Failed to issue method call: %s", bus_error_message(&error));
832 if (!dbus_message_iter_init(reply, &iter) ||
833 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
834 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
835 log_error("Failed to parse reply.");
840 dbus_message_iter_recurse(&iter, &sub);
842 if (isatty(STDOUT_FILENO))
843 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
845 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
846 const char *name, *type, *state, *job_path, *unit_path;
850 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
851 log_error("Failed to parse reply.");
856 dbus_message_iter_recurse(&sub, &sub2);
858 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
859 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
860 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
861 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
862 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
863 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
864 log_error("Failed to parse reply.");
869 e = arg_full ? NULL : ellipsize(name, 25, 33);
870 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
875 dbus_message_iter_next(&sub);
878 if (isatty(STDOUT_FILENO))
879 printf("\n%u jobs listed.\n", k);
885 dbus_message_unref(m);
888 dbus_message_unref(reply);
890 dbus_error_free(&error);
895 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
896 DBusMessage *m = NULL, *reply = NULL;
901 dbus_error_init(&error);
906 for (i = 1; i < n; i++) {
908 if (!(m = dbus_message_new_method_call(
909 "org.freedesktop.systemd1",
910 "/org/freedesktop/systemd1",
911 "org.freedesktop.systemd1.Manager",
913 log_error("Could not allocate message.");
918 if (!dbus_message_append_args(m,
919 DBUS_TYPE_STRING, &args[i],
920 DBUS_TYPE_INVALID)) {
921 log_error("Could not append arguments to message.");
926 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
927 log_error("Failed to issue method call: %s", bus_error_message(&error));
932 dbus_message_unref(m);
933 dbus_message_unref(reply);
942 dbus_message_unref(m);
945 dbus_message_unref(reply);
947 dbus_error_free(&error);
952 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
953 DBusMessage *m = NULL, *reply = NULL;
958 dbus_error_init(&error);
964 return daemon_reload(bus, args, n);
966 for (i = 1; i < n; i++) {
970 if (!(m = dbus_message_new_method_call(
971 "org.freedesktop.systemd1",
972 "/org/freedesktop/systemd1",
973 "org.freedesktop.systemd1.Manager",
975 log_error("Could not allocate message.");
980 if ((r = safe_atou(args[i], &id)) < 0) {
981 log_error("Failed to parse job id: %s", strerror(-r));
985 assert_cc(sizeof(uint32_t) == sizeof(id));
986 if (!dbus_message_append_args(m,
987 DBUS_TYPE_UINT32, &id,
988 DBUS_TYPE_INVALID)) {
989 log_error("Could not append arguments to message.");
994 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
995 log_error("Failed to issue method call: %s", bus_error_message(&error));
1000 if (!dbus_message_get_args(reply, &error,
1001 DBUS_TYPE_OBJECT_PATH, &path,
1002 DBUS_TYPE_INVALID)) {
1003 log_error("Failed to parse reply: %s", bus_error_message(&error));
1008 dbus_message_unref(m);
1009 if (!(m = dbus_message_new_method_call(
1010 "org.freedesktop.systemd1",
1012 "org.freedesktop.systemd1.Job",
1014 log_error("Could not allocate message.");
1019 dbus_message_unref(reply);
1020 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1021 log_error("Failed to issue method call: %s", bus_error_message(&error));
1026 dbus_message_unref(m);
1027 dbus_message_unref(reply);
1035 dbus_message_unref(m);
1038 dbus_message_unref(reply);
1040 dbus_error_free(&error);
1045 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1046 DBusMessage *m = NULL, *reply = NULL;
1047 dbus_bool_t b = FALSE;
1048 DBusMessageIter iter, sub;
1050 *interface = "org.freedesktop.systemd1.Unit",
1051 *property = "NeedDaemonReload",
1054 /* We ignore all errors here, since this is used to show a warning only */
1056 if (!(m = dbus_message_new_method_call(
1057 "org.freedesktop.systemd1",
1058 "/org/freedesktop/systemd1",
1059 "org.freedesktop.systemd1.Manager",
1063 if (!dbus_message_append_args(m,
1064 DBUS_TYPE_STRING, &unit,
1068 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1071 if (!dbus_message_get_args(reply, NULL,
1072 DBUS_TYPE_OBJECT_PATH, &path,
1076 dbus_message_unref(m);
1077 if (!(m = dbus_message_new_method_call(
1078 "org.freedesktop.systemd1",
1080 "org.freedesktop.DBus.Properties",
1084 if (!dbus_message_append_args(m,
1085 DBUS_TYPE_STRING, &interface,
1086 DBUS_TYPE_STRING, &property,
1087 DBUS_TYPE_INVALID)) {
1091 dbus_message_unref(reply);
1092 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1095 if (!dbus_message_iter_init(reply, &iter) ||
1096 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1099 dbus_message_iter_recurse(&iter, &sub);
1101 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1104 dbus_message_iter_get_basic(&sub, &b);
1108 dbus_message_unref(m);
1111 dbus_message_unref(reply);
1116 typedef struct WaitData {
1121 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1129 dbus_error_init(&error);
1131 log_debug("Got D-Bus request: %s.%s() on %s",
1132 dbus_message_get_interface(message),
1133 dbus_message_get_member(message),
1134 dbus_message_get_path(message));
1136 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1137 log_error("Warning! D-Bus connection terminated.");
1138 dbus_connection_close(connection);
1140 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1142 const char *path, *result;
1143 dbus_bool_t success = true;
1145 if (dbus_message_get_args(message, &error,
1146 DBUS_TYPE_UINT32, &id,
1147 DBUS_TYPE_OBJECT_PATH, &path,
1148 DBUS_TYPE_STRING, &result,
1149 DBUS_TYPE_INVALID)) {
1152 if ((p = set_remove(d->set, (char*) path)))
1156 d->result = strdup(result);
1161 dbus_error_free(&error);
1163 if (dbus_message_get_args(message, &error,
1164 DBUS_TYPE_UINT32, &id,
1165 DBUS_TYPE_OBJECT_PATH, &path,
1166 DBUS_TYPE_BOOLEAN, &success,
1167 DBUS_TYPE_INVALID)) {
1170 /* Compatibility with older systemd versions <
1171 * 19 during upgrades. This should be dropped
1174 if ((p = set_remove(d->set, (char*) path)))
1178 d->result = strdup("failed");
1184 log_error("Failed to parse message: %s", bus_error_message(&error));
1188 dbus_error_free(&error);
1189 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1192 static int enable_wait_for_jobs(DBusConnection *bus) {
1200 dbus_error_init(&error);
1201 dbus_bus_add_match(bus,
1203 "sender='org.freedesktop.systemd1',"
1204 "interface='org.freedesktop.systemd1.Manager',"
1205 "member='JobRemoved',"
1206 "path='/org/freedesktop/systemd1'",
1209 if (dbus_error_is_set(&error)) {
1210 log_error("Failed to add match: %s", bus_error_message(&error));
1211 dbus_error_free(&error);
1215 /* This is slightly dirty, since we don't undo the match registrations. */
1219 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1229 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1230 log_error("Failed to add filter.");
1235 while (!set_isempty(s) &&
1236 dbus_connection_read_write_dispatch(bus, -1))
1239 if (!arg_quiet && d.result) {
1240 if (streq(d.result, "timeout"))
1241 log_error("Job timed out.");
1242 else if (streq(d.result, "canceled"))
1243 log_error("Job canceled.");
1244 else if (streq(d.result, "dependency"))
1245 log_error("A dependency job failed. See system logs for details.");
1246 else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
1247 log_error("Job failed. See system logs and 'systemctl status' for details.");
1250 if (streq_ptr(d.result, "timeout"))
1252 else if (streq_ptr(d.result, "canceled"))
1254 else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
1262 /* This is slightly dirty, since we don't undo the filter registration. */
1267 static int start_unit_one(
1268 DBusConnection *bus,
1275 DBusMessage *m = NULL, *reply = NULL;
1284 assert(arg_no_block || s);
1286 if (!(m = dbus_message_new_method_call(
1287 "org.freedesktop.systemd1",
1288 "/org/freedesktop/systemd1",
1289 "org.freedesktop.systemd1.Manager",
1291 log_error("Could not allocate message.");
1296 if (!dbus_message_append_args(m,
1297 DBUS_TYPE_STRING, &name,
1298 DBUS_TYPE_STRING, &mode,
1299 DBUS_TYPE_INVALID)) {
1300 log_error("Could not append arguments to message.");
1305 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1307 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1308 /* There's always a fallback possible for
1309 * legacy actions. */
1314 log_error("Failed to issue method call: %s", bus_error_message(error));
1319 if (!dbus_message_get_args(reply, error,
1320 DBUS_TYPE_OBJECT_PATH, &path,
1321 DBUS_TYPE_INVALID)) {
1322 log_error("Failed to parse reply: %s", bus_error_message(error));
1327 if (need_daemon_reload(bus, name))
1328 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1329 arg_user ? "--user" : "--system");
1331 if (!arg_no_block) {
1334 if (!(p = strdup(path))) {
1335 log_error("Failed to duplicate path.");
1340 if ((r = set_put(s, p)) < 0) {
1342 log_error("Failed to add path to set.");
1351 dbus_message_unref(m);
1354 dbus_message_unref(reply);
1359 static enum action verb_to_action(const char *verb) {
1360 if (streq(verb, "halt"))
1362 else if (streq(verb, "poweroff"))
1363 return ACTION_POWEROFF;
1364 else if (streq(verb, "reboot"))
1365 return ACTION_REBOOT;
1366 else if (streq(verb, "kexec"))
1367 return ACTION_KEXEC;
1368 else if (streq(verb, "rescue"))
1369 return ACTION_RESCUE;
1370 else if (streq(verb, "emergency"))
1371 return ACTION_EMERGENCY;
1372 else if (streq(verb, "default"))
1373 return ACTION_DEFAULT;
1374 else if (streq(verb, "exit"))
1377 return ACTION_INVALID;
1380 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1382 static const char * const table[_ACTION_MAX] = {
1383 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1384 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1385 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1386 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1387 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1388 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1389 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1390 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1391 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1392 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1393 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1394 [ACTION_EXIT] = SPECIAL_EXIT_TARGET
1399 const char *method, *mode, *one_name;
1403 dbus_error_init(&error);
1407 spawn_ask_password_agent();
1409 if (arg_action == ACTION_SYSTEMCTL) {
1411 streq(args[0], "stop") ||
1412 streq(args[0], "condstop") ? "StopUnit" :
1413 streq(args[0], "reload") ? "ReloadUnit" :
1414 streq(args[0], "restart") ? "RestartUnit" :
1416 streq(args[0], "try-restart") ||
1417 streq(args[0], "condrestart") ? "TryRestartUnit" :
1419 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1421 streq(args[0], "reload-or-try-restart") ||
1422 streq(args[0], "condreload") ||
1424 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1428 (streq(args[0], "isolate") ||
1429 streq(args[0], "rescue") ||
1430 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1432 one_name = table[verb_to_action(args[0])];
1435 assert(arg_action < ELEMENTSOF(table));
1436 assert(table[arg_action]);
1438 method = "StartUnit";
1440 mode = (arg_action == ACTION_EMERGENCY ||
1441 arg_action == ACTION_RESCUE ||
1442 arg_action == ACTION_RUNLEVEL2 ||
1443 arg_action == ACTION_RUNLEVEL3 ||
1444 arg_action == ACTION_RUNLEVEL4 ||
1445 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1447 one_name = table[arg_action];
1450 if (!arg_no_block) {
1451 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1452 log_error("Could not watch jobs: %s", strerror(-ret));
1456 if (!(s = set_new(string_hash_func, string_compare_func))) {
1457 log_error("Failed to allocate set.");
1464 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1467 for (i = 1; i < n; i++)
1468 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1469 ret = translate_bus_error_to_exit_status(r, &error);
1470 dbus_error_free(&error);
1475 if ((r = wait_for_jobs(bus, s)) < 0) {
1484 dbus_error_free(&error);
1489 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1496 (streq(args[0], "halt") ||
1497 streq(args[0], "poweroff") ||
1498 streq(args[0], "reboot") ||
1499 streq(args[0], "kexec") ||
1500 streq(args[0], "exit")))
1501 return daemon_reload(bus, args, n);
1503 r = start_unit(bus, args, n);
1506 warn_wall(verb_to_action(args[0]));
1511 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1512 DBusMessage *m = NULL, *reply = NULL;
1514 *interface = "org.freedesktop.systemd1.Unit",
1515 *property = "ActiveState";
1516 int r = 3; /* According to LSB: "program is not running" */
1523 dbus_error_init(&error);
1525 for (i = 1; i < n; i++) {
1526 const char *path = NULL;
1528 DBusMessageIter iter, sub;
1530 if (!(m = dbus_message_new_method_call(
1531 "org.freedesktop.systemd1",
1532 "/org/freedesktop/systemd1",
1533 "org.freedesktop.systemd1.Manager",
1535 log_error("Could not allocate message.");
1540 if (!dbus_message_append_args(m,
1541 DBUS_TYPE_STRING, &args[i],
1542 DBUS_TYPE_INVALID)) {
1543 log_error("Could not append arguments to message.");
1548 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1550 /* Hmm, cannot figure out anything about this unit... */
1554 dbus_error_free(&error);
1555 dbus_message_unref(m);
1560 if (!dbus_message_get_args(reply, &error,
1561 DBUS_TYPE_OBJECT_PATH, &path,
1562 DBUS_TYPE_INVALID)) {
1563 log_error("Failed to parse reply: %s", bus_error_message(&error));
1568 dbus_message_unref(m);
1569 if (!(m = dbus_message_new_method_call(
1570 "org.freedesktop.systemd1",
1572 "org.freedesktop.DBus.Properties",
1574 log_error("Could not allocate message.");
1579 if (!dbus_message_append_args(m,
1580 DBUS_TYPE_STRING, &interface,
1581 DBUS_TYPE_STRING, &property,
1582 DBUS_TYPE_INVALID)) {
1583 log_error("Could not append arguments to message.");
1588 dbus_message_unref(reply);
1589 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1590 log_error("Failed to issue method call: %s", bus_error_message(&error));
1595 if (!dbus_message_iter_init(reply, &iter) ||
1596 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1597 log_error("Failed to parse reply.");
1602 dbus_message_iter_recurse(&iter, &sub);
1604 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1605 log_error("Failed to parse reply.");
1610 dbus_message_iter_get_basic(&sub, &state);
1615 if (streq(state, "active") || streq(state, "reloading"))
1618 dbus_message_unref(m);
1619 dbus_message_unref(reply);
1625 dbus_message_unref(m);
1628 dbus_message_unref(reply);
1630 dbus_error_free(&error);
1635 static int kill_unit(DBusConnection *bus, char **args, unsigned n) {
1636 DBusMessage *m = NULL, *reply = NULL;
1644 dbus_error_init(&error);
1647 arg_kill_who = "all";
1650 arg_kill_mode = streq(arg_kill_who, "all") ? "control-group" : "process";
1652 for (i = 1; i < n; i++) {
1654 if (!(m = dbus_message_new_method_call(
1655 "org.freedesktop.systemd1",
1656 "/org/freedesktop/systemd1",
1657 "org.freedesktop.systemd1.Manager",
1659 log_error("Could not allocate message.");
1664 if (!dbus_message_append_args(m,
1665 DBUS_TYPE_STRING, &args[i],
1666 DBUS_TYPE_STRING, &arg_kill_who,
1667 DBUS_TYPE_STRING, &arg_kill_mode,
1668 DBUS_TYPE_INT32, &arg_signal,
1669 DBUS_TYPE_INVALID)) {
1670 log_error("Could not append arguments to message.");
1675 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1676 log_error("Failed to issue method call: %s", bus_error_message(&error));
1677 dbus_error_free(&error);
1681 dbus_message_unref(m);
1684 dbus_message_unref(reply);
1690 dbus_message_unref(m);
1693 dbus_message_unref(reply);
1695 dbus_error_free(&error);
1700 typedef struct ExecStatusInfo {
1708 usec_t start_timestamp;
1709 usec_t exit_timestamp;
1714 LIST_FIELDS(struct ExecStatusInfo, exec);
1717 static void exec_status_info_free(ExecStatusInfo *i) {
1726 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1727 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
1728 DBusMessageIter sub2, sub3;
1732 int32_t code, status;
1738 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1741 dbus_message_iter_recurse(sub, &sub2);
1743 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1746 if (!(i->path = strdup(path)))
1749 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1750 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1754 dbus_message_iter_recurse(&sub2, &sub3);
1755 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1756 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1757 dbus_message_iter_next(&sub3);
1762 if (!(i->argv = new0(char*, n+1)))
1766 dbus_message_iter_recurse(&sub2, &sub3);
1767 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1770 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1771 dbus_message_iter_get_basic(&sub3, &s);
1772 dbus_message_iter_next(&sub3);
1774 if (!(i->argv[n++] = strdup(s)))
1778 if (!dbus_message_iter_next(&sub2) ||
1779 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1780 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1781 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
1782 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1783 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
1784 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1785 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1786 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1790 i->start_timestamp = (usec_t) start_timestamp;
1791 i->exit_timestamp = (usec_t) exit_timestamp;
1792 i->pid = (pid_t) pid;
1799 typedef struct UnitStatusInfo {
1801 const char *load_state;
1802 const char *active_state;
1803 const char *sub_state;
1805 const char *description;
1806 const char *following;
1809 const char *default_control_group;
1811 usec_t inactive_exit_timestamp;
1812 usec_t active_enter_timestamp;
1813 usec_t active_exit_timestamp;
1814 usec_t inactive_enter_timestamp;
1816 bool need_daemon_reload;
1821 const char *status_text;
1823 #ifdef HAVE_SYSV_COMPAT
1827 usec_t start_timestamp;
1828 usec_t exit_timestamp;
1830 int exit_code, exit_status;
1832 usec_t condition_timestamp;
1833 bool condition_result;
1836 unsigned n_accepted;
1837 unsigned n_connections;
1841 const char *sysfs_path;
1843 /* Mount, Automount */
1849 LIST_HEAD(ExecStatusInfo, exec);
1852 static void print_status_info(UnitStatusInfo *i) {
1854 const char *on, *off, *ss;
1856 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1857 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1861 /* This shows pretty information about a unit. See
1862 * print_property() for a low-level property printer */
1864 printf("%s", strna(i->id));
1866 if (i->description && !streq_ptr(i->id, i->description))
1867 printf(" - %s", i->description);
1872 printf("\t Follow: unit currently follows state of %s\n", i->following);
1874 if (streq_ptr(i->load_state, "failed") ||
1875 streq_ptr(i->load_state, "banned")) {
1876 on = ansi_highlight(true);
1877 off = ansi_highlight(false);
1882 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1884 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1886 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1888 if (streq_ptr(i->active_state, "failed")) {
1889 on = ansi_highlight(true);
1890 off = ansi_highlight(false);
1891 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1892 on = ansi_highlight_green(true);
1893 off = ansi_highlight_green(false);
1898 printf("\t Active: %s%s (%s)%s",
1900 strna(i->active_state),
1904 printf("\t Active: %s%s%s",
1906 strna(i->active_state),
1909 timestamp = (streq_ptr(i->active_state, "active") ||
1910 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1911 (streq_ptr(i->active_state, "inactive") ||
1912 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1913 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1914 i->active_exit_timestamp;
1916 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1917 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1920 printf(" since %s; %s\n", s2, s1);
1922 printf(" since %s\n", s2);
1926 if (!i->condition_result && i->condition_timestamp > 0) {
1927 s1 = format_timestamp_pretty(since1, sizeof(since1), i->condition_timestamp);
1928 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
1931 printf("\t start condition failed at %s; %s\n", s2, s1);
1933 printf("\t start condition failed at %s\n", s2);
1937 printf("\t Device: %s\n", i->sysfs_path);
1939 printf("\t Where: %s\n", i->where);
1941 printf("\t What: %s\n", i->what);
1944 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1946 LIST_FOREACH(exec, p, i->exec) {
1950 /* Only show exited processes here */
1954 t = strv_join(p->argv, " ");
1955 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
1958 #ifdef HAVE_SYSV_COMPAT
1960 good = is_clean_exit_lsb(p->code, p->status);
1963 good = is_clean_exit(p->code, p->status);
1966 on = ansi_highlight(true);
1967 off = ansi_highlight(false);
1971 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
1973 if (p->code == CLD_EXITED) {
1976 printf("status=%i", p->status);
1978 #ifdef HAVE_SYSV_COMPAT
1979 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1981 if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1986 printf("signal=%s", signal_to_string(p->status));
1988 printf(")%s\n", off);
1992 if (i->main_pid == p->pid &&
1993 i->start_timestamp == p->start_timestamp &&
1994 i->exit_timestamp == p->start_timestamp)
1995 /* Let's not show this twice */
1998 if (p->pid == i->control_pid)
2002 if (i->main_pid > 0 || i->control_pid > 0) {
2005 if (i->main_pid > 0) {
2006 printf("Main PID: %u", (unsigned) i->main_pid);
2010 get_process_name(i->main_pid, &t);
2015 } else if (i->exit_code > 0) {
2016 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2018 if (i->exit_code == CLD_EXITED) {
2021 printf("status=%i", i->exit_status);
2023 #ifdef HAVE_SYSV_COMPAT
2024 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
2026 if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
2031 printf("signal=%s", signal_to_string(i->exit_status));
2036 if (i->main_pid > 0 && i->control_pid > 0)
2039 if (i->control_pid > 0) {
2042 printf(" Control: %u", (unsigned) i->control_pid);
2044 get_process_name(i->control_pid, &t);
2055 printf("\t Status: \"%s\"\n", i->status_text);
2057 if (i->default_control_group) {
2060 printf("\t CGroup: %s\n", i->default_control_group);
2062 if (arg_transport != TRANSPORT_SSH) {
2063 if ((c = columns()) > 18)
2068 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
2072 if (i->need_daemon_reload)
2073 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2074 ansi_highlight(true),
2075 ansi_highlight(false),
2076 arg_user ? "--user" : "--system");
2079 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2081 switch (dbus_message_iter_get_arg_type(iter)) {
2083 case DBUS_TYPE_STRING: {
2086 dbus_message_iter_get_basic(iter, &s);
2089 if (streq(name, "Id"))
2091 else if (streq(name, "LoadState"))
2093 else if (streq(name, "ActiveState"))
2094 i->active_state = s;
2095 else if (streq(name, "SubState"))
2097 else if (streq(name, "Description"))
2099 else if (streq(name, "FragmentPath"))
2101 #ifdef HAVE_SYSV_COMPAT
2102 else if (streq(name, "SysVPath")) {
2107 else if (streq(name, "DefaultControlGroup"))
2108 i->default_control_group = s;
2109 else if (streq(name, "StatusText"))
2111 else if (streq(name, "SysFSPath"))
2113 else if (streq(name, "Where"))
2115 else if (streq(name, "What"))
2117 else if (streq(name, "Following"))
2124 case DBUS_TYPE_BOOLEAN: {
2127 dbus_message_iter_get_basic(iter, &b);
2129 if (streq(name, "Accept"))
2131 else if (streq(name, "NeedDaemonReload"))
2132 i->need_daemon_reload = b;
2133 else if (streq(name, "ConditionResult"))
2134 i->condition_result = b;
2139 case DBUS_TYPE_UINT32: {
2142 dbus_message_iter_get_basic(iter, &u);
2144 if (streq(name, "MainPID")) {
2146 i->main_pid = (pid_t) u;
2149 } else if (streq(name, "ControlPID"))
2150 i->control_pid = (pid_t) u;
2151 else if (streq(name, "ExecMainPID")) {
2153 i->main_pid = (pid_t) u;
2154 } else if (streq(name, "NAccepted"))
2156 else if (streq(name, "NConnections"))
2157 i->n_connections = u;
2162 case DBUS_TYPE_INT32: {
2165 dbus_message_iter_get_basic(iter, &j);
2167 if (streq(name, "ExecMainCode"))
2168 i->exit_code = (int) j;
2169 else if (streq(name, "ExecMainStatus"))
2170 i->exit_status = (int) j;
2175 case DBUS_TYPE_UINT64: {
2178 dbus_message_iter_get_basic(iter, &u);
2180 if (streq(name, "ExecMainStartTimestamp"))
2181 i->start_timestamp = (usec_t) u;
2182 else if (streq(name, "ExecMainExitTimestamp"))
2183 i->exit_timestamp = (usec_t) u;
2184 else if (streq(name, "ActiveEnterTimestamp"))
2185 i->active_enter_timestamp = (usec_t) u;
2186 else if (streq(name, "InactiveEnterTimestamp"))
2187 i->inactive_enter_timestamp = (usec_t) u;
2188 else if (streq(name, "InactiveExitTimestamp"))
2189 i->inactive_exit_timestamp = (usec_t) u;
2190 else if (streq(name, "ActiveExitTimestamp"))
2191 i->active_exit_timestamp = (usec_t) u;
2192 else if (streq(name, "ConditionTimestamp"))
2193 i->condition_timestamp = (usec_t) u;
2198 case DBUS_TYPE_ARRAY: {
2200 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2201 startswith(name, "Exec")) {
2202 DBusMessageIter sub;
2204 dbus_message_iter_recurse(iter, &sub);
2205 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2206 ExecStatusInfo *info;
2209 if (!(info = new0(ExecStatusInfo, 1)))
2212 if (!(info->name = strdup(name))) {
2217 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2222 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2224 dbus_message_iter_next(&sub);
2235 static int print_property(const char *name, DBusMessageIter *iter) {
2239 /* This is a low-level property printer, see
2240 * print_status_info() for the nicer output */
2242 if (arg_property && !strv_find(arg_property, name))
2245 switch (dbus_message_iter_get_arg_type(iter)) {
2247 case DBUS_TYPE_STRING: {
2249 dbus_message_iter_get_basic(iter, &s);
2251 if (arg_all || s[0])
2252 printf("%s=%s\n", name, s);
2257 case DBUS_TYPE_BOOLEAN: {
2259 dbus_message_iter_get_basic(iter, &b);
2260 printf("%s=%s\n", name, yes_no(b));
2265 case DBUS_TYPE_UINT64: {
2267 dbus_message_iter_get_basic(iter, &u);
2269 /* Yes, heuristics! But we can change this check
2270 * should it turn out to not be sufficient */
2272 if (endswith(name, "Timestamp")) {
2273 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
2275 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
2276 printf("%s=%s\n", name, strempty(t));
2277 } else if (strstr(name, "USec")) {
2278 char timespan[FORMAT_TIMESPAN_MAX];
2280 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
2282 printf("%s=%llu\n", name, (unsigned long long) u);
2287 case DBUS_TYPE_UINT32: {
2289 dbus_message_iter_get_basic(iter, &u);
2291 if (strstr(name, "UMask") || strstr(name, "Mode"))
2292 printf("%s=%04o\n", name, u);
2294 printf("%s=%u\n", name, (unsigned) u);
2299 case DBUS_TYPE_INT32: {
2301 dbus_message_iter_get_basic(iter, &i);
2303 printf("%s=%i\n", name, (int) i);
2307 case DBUS_TYPE_DOUBLE: {
2309 dbus_message_iter_get_basic(iter, &d);
2311 printf("%s=%g\n", name, d);
2315 case DBUS_TYPE_STRUCT: {
2316 DBusMessageIter sub;
2317 dbus_message_iter_recurse(iter, &sub);
2319 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2322 dbus_message_iter_get_basic(&sub, &u);
2325 printf("%s=%u\n", name, (unsigned) u);
2327 printf("%s=\n", name);
2330 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2333 dbus_message_iter_get_basic(&sub, &s);
2335 if (arg_all || s[0])
2336 printf("%s=%s\n", name, s);
2344 case DBUS_TYPE_ARRAY:
2346 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2347 DBusMessageIter sub;
2350 dbus_message_iter_recurse(iter, &sub);
2352 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2353 printf("%s=", name);
2355 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2358 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2359 dbus_message_iter_get_basic(&sub, &s);
2360 printf("%s%s", space ? " " : "", s);
2363 dbus_message_iter_next(&sub);
2371 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2372 DBusMessageIter sub;
2374 dbus_message_iter_recurse(iter, &sub);
2376 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2377 printf("%s=", name);
2379 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2382 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2383 dbus_message_iter_get_basic(&sub, &u);
2386 dbus_message_iter_next(&sub);
2394 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
2395 DBusMessageIter sub, sub2;
2397 dbus_message_iter_recurse(iter, &sub);
2398 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2402 dbus_message_iter_recurse(&sub, &sub2);
2404 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
2405 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
2406 printf("EnvironmentFile=%s (ignore=%s)\n", path, yes_no(ignore));
2408 dbus_message_iter_next(&sub);
2413 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2414 DBusMessageIter sub, sub2;
2416 dbus_message_iter_recurse(iter, &sub);
2417 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2418 const char *type, *path;
2420 dbus_message_iter_recurse(&sub, &sub2);
2422 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2423 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2424 printf("%s=%s\n", type, path);
2426 dbus_message_iter_next(&sub);
2431 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2432 DBusMessageIter sub, sub2;
2434 dbus_message_iter_recurse(iter, &sub);
2435 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2437 uint64_t value, next_elapse;
2439 dbus_message_iter_recurse(&sub, &sub2);
2441 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2442 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2443 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2444 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2446 printf("%s={ value=%s ; next_elapse=%s }\n",
2448 format_timespan(timespan1, sizeof(timespan1), value),
2449 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2452 dbus_message_iter_next(&sub);
2457 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2458 DBusMessageIter sub;
2460 dbus_message_iter_recurse(iter, &sub);
2461 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2462 ExecStatusInfo info;
2465 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2466 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2469 t = strv_join(info.argv, " ");
2471 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2475 yes_no(info.ignore),
2476 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2477 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2478 (unsigned) info. pid,
2479 sigchld_code_to_string(info.code),
2481 info.code == CLD_EXITED ? "" : "/",
2482 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2488 strv_free(info.argv);
2490 dbus_message_iter_next(&sub);
2500 printf("%s=[unprintable]\n", name);
2505 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2506 DBusMessage *m = NULL, *reply = NULL;
2507 const char *interface = "";
2510 DBusMessageIter iter, sub, sub2, sub3;
2511 UnitStatusInfo info;
2519 dbus_error_init(&error);
2521 if (!(m = dbus_message_new_method_call(
2522 "org.freedesktop.systemd1",
2524 "org.freedesktop.DBus.Properties",
2526 log_error("Could not allocate message.");
2531 if (!dbus_message_append_args(m,
2532 DBUS_TYPE_STRING, &interface,
2533 DBUS_TYPE_INVALID)) {
2534 log_error("Could not append arguments to message.");
2539 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2540 log_error("Failed to issue method call: %s", bus_error_message(&error));
2545 if (!dbus_message_iter_init(reply, &iter) ||
2546 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2547 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2548 log_error("Failed to parse reply.");
2553 dbus_message_iter_recurse(&iter, &sub);
2560 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2563 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2564 log_error("Failed to parse reply.");
2569 dbus_message_iter_recurse(&sub, &sub2);
2571 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2572 log_error("Failed to parse reply.");
2577 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2578 log_error("Failed to parse reply.");
2583 dbus_message_iter_recurse(&sub2, &sub3);
2585 if (show_properties)
2586 r = print_property(name, &sub3);
2588 r = status_property(name, &sub3, &info);
2591 log_error("Failed to parse reply.");
2596 dbus_message_iter_next(&sub);
2601 if (!show_properties)
2602 print_status_info(&info);
2604 if (!streq_ptr(info.active_state, "active") &&
2605 !streq_ptr(info.active_state, "reloading") &&
2606 streq(verb, "status"))
2607 /* According to LSB: "program not running" */
2610 while ((p = info.exec)) {
2611 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2612 exec_status_info_free(p);
2617 dbus_message_unref(m);
2620 dbus_message_unref(reply);
2622 dbus_error_free(&error);
2627 static int show(DBusConnection *bus, char **args, unsigned n) {
2628 DBusMessage *m = NULL, *reply = NULL;
2632 bool show_properties, new_line = false;
2637 dbus_error_init(&error);
2639 show_properties = !streq(args[0], "status");
2641 if (show_properties)
2642 pager_open_if_enabled();
2644 if (show_properties && n <= 1) {
2645 /* If not argument is specified inspect the manager
2648 ret = show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2652 for (i = 1; i < n; i++) {
2653 const char *path = NULL;
2656 if (safe_atou32(args[i], &id) < 0) {
2658 /* Interpret as unit name */
2660 if (!(m = dbus_message_new_method_call(
2661 "org.freedesktop.systemd1",
2662 "/org/freedesktop/systemd1",
2663 "org.freedesktop.systemd1.Manager",
2665 log_error("Could not allocate message.");
2670 if (!dbus_message_append_args(m,
2671 DBUS_TYPE_STRING, &args[i],
2672 DBUS_TYPE_INVALID)) {
2673 log_error("Could not append arguments to message.");
2678 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2680 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2681 log_error("Failed to issue method call: %s", bus_error_message(&error));
2686 dbus_error_free(&error);
2688 dbus_message_unref(m);
2689 if (!(m = dbus_message_new_method_call(
2690 "org.freedesktop.systemd1",
2691 "/org/freedesktop/systemd1",
2692 "org.freedesktop.systemd1.Manager",
2694 log_error("Could not allocate message.");
2699 if (!dbus_message_append_args(m,
2700 DBUS_TYPE_STRING, &args[i],
2701 DBUS_TYPE_INVALID)) {
2702 log_error("Could not append arguments to message.");
2707 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2708 log_error("Failed to issue method call: %s", bus_error_message(&error));
2710 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2711 ret = 4; /* According to LSB: "program or service status is unknown" */
2718 } else if (show_properties) {
2720 /* Interpret as job id */
2722 if (!(m = dbus_message_new_method_call(
2723 "org.freedesktop.systemd1",
2724 "/org/freedesktop/systemd1",
2725 "org.freedesktop.systemd1.Manager",
2727 log_error("Could not allocate message.");
2732 if (!dbus_message_append_args(m,
2733 DBUS_TYPE_UINT32, &id,
2734 DBUS_TYPE_INVALID)) {
2735 log_error("Could not append arguments to message.");
2740 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2741 log_error("Failed to issue method call: %s", bus_error_message(&error));
2747 /* Interpret as PID */
2749 if (!(m = dbus_message_new_method_call(
2750 "org.freedesktop.systemd1",
2751 "/org/freedesktop/systemd1",
2752 "org.freedesktop.systemd1.Manager",
2754 log_error("Could not allocate message.");
2759 if (!dbus_message_append_args(m,
2760 DBUS_TYPE_UINT32, &id,
2761 DBUS_TYPE_INVALID)) {
2762 log_error("Could not append arguments to message.");
2767 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2768 log_error("Failed to issue method call: %s", bus_error_message(&error));
2774 if (!dbus_message_get_args(reply, &error,
2775 DBUS_TYPE_OBJECT_PATH, &path,
2776 DBUS_TYPE_INVALID)) {
2777 log_error("Failed to parse reply: %s", bus_error_message(&error));
2782 if ((r = show_one(args[0], bus, path, show_properties, &new_line)) != 0)
2785 dbus_message_unref(m);
2786 dbus_message_unref(reply);
2792 dbus_message_unref(m);
2795 dbus_message_unref(reply);
2797 dbus_error_free(&error);
2802 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2804 DBusMessage *m = NULL, *reply = NULL;
2809 dbus_error_init(&error);
2811 log_debug("Got D-Bus request: %s.%s() on %s",
2812 dbus_message_get_interface(message),
2813 dbus_message_get_member(message),
2814 dbus_message_get_path(message));
2816 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2817 log_error("Warning! D-Bus connection terminated.");
2818 dbus_connection_close(connection);
2820 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2821 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2822 const char *id, *path;
2824 if (!dbus_message_get_args(message, &error,
2825 DBUS_TYPE_STRING, &id,
2826 DBUS_TYPE_OBJECT_PATH, &path,
2828 log_error("Failed to parse message: %s", bus_error_message(&error));
2829 else if (streq(dbus_message_get_member(message), "UnitNew"))
2830 printf("Unit %s added.\n", id);
2832 printf("Unit %s removed.\n", id);
2834 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew")) {
2838 if (!dbus_message_get_args(message, &error,
2839 DBUS_TYPE_UINT32, &id,
2840 DBUS_TYPE_OBJECT_PATH, &path,
2842 log_error("Failed to parse message: %s", bus_error_message(&error));
2844 printf("Job %u added.\n", id);
2847 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2849 const char *path, *result;
2851 if (!dbus_message_get_args(message, &error,
2852 DBUS_TYPE_UINT32, &id,
2853 DBUS_TYPE_OBJECT_PATH, &path,
2854 DBUS_TYPE_STRING, &result,
2856 log_error("Failed to parse message: %s", bus_error_message(&error));
2858 printf("Job %u removed (result=%s).\n", id, result);
2861 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2863 const char *path, *interface, *property = "Id";
2864 DBusMessageIter iter, sub;
2866 path = dbus_message_get_path(message);
2868 if (!dbus_message_get_args(message, &error,
2869 DBUS_TYPE_STRING, &interface,
2870 DBUS_TYPE_INVALID)) {
2871 log_error("Failed to parse message: %s", bus_error_message(&error));
2875 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2876 !streq(interface, "org.freedesktop.systemd1.Unit"))
2879 if (!(m = dbus_message_new_method_call(
2880 "org.freedesktop.systemd1",
2882 "org.freedesktop.DBus.Properties",
2884 log_error("Could not allocate message.");
2888 if (!dbus_message_append_args(m,
2889 DBUS_TYPE_STRING, &interface,
2890 DBUS_TYPE_STRING, &property,
2891 DBUS_TYPE_INVALID)) {
2892 log_error("Could not append arguments to message.");
2896 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2897 log_error("Failed to issue method call: %s", bus_error_message(&error));
2901 if (!dbus_message_iter_init(reply, &iter) ||
2902 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2903 log_error("Failed to parse reply.");
2907 dbus_message_iter_recurse(&iter, &sub);
2909 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2912 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2913 log_error("Failed to parse reply.");
2917 dbus_message_iter_get_basic(&sub, &id);
2918 printf("Unit %s changed.\n", id);
2922 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2923 log_error("Failed to parse reply.");
2927 dbus_message_iter_get_basic(&sub, &id);
2928 printf("Job %u changed.\n", id);
2934 dbus_message_unref(m);
2937 dbus_message_unref(reply);
2939 dbus_error_free(&error);
2940 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2944 dbus_message_unref(m);
2947 dbus_message_unref(reply);
2949 dbus_error_free(&error);
2950 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2953 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2954 DBusMessage *m = NULL, *reply = NULL;
2958 dbus_error_init(&error);
2961 dbus_bus_add_match(bus,
2963 "sender='org.freedesktop.systemd1',"
2964 "interface='org.freedesktop.systemd1.Manager',"
2965 "path='/org/freedesktop/systemd1'",
2968 if (dbus_error_is_set(&error)) {
2969 log_error("Failed to add match: %s", bus_error_message(&error));
2974 dbus_bus_add_match(bus,
2976 "sender='org.freedesktop.systemd1',"
2977 "interface='org.freedesktop.DBus.Properties',"
2978 "member='PropertiesChanged'",
2981 if (dbus_error_is_set(&error)) {
2982 log_error("Failed to add match: %s", bus_error_message(&error));
2988 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2989 log_error("Failed to add filter.");
2994 if (!(m = dbus_message_new_method_call(
2995 "org.freedesktop.systemd1",
2996 "/org/freedesktop/systemd1",
2997 "org.freedesktop.systemd1.Manager",
2999 log_error("Could not allocate message.");
3004 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3005 log_error("Failed to issue method call: %s", bus_error_message(&error));
3010 while (dbus_connection_read_write_dispatch(bus, -1))
3017 /* This is slightly dirty, since we don't undo the filter or the matches. */
3020 dbus_message_unref(m);
3023 dbus_message_unref(reply);
3025 dbus_error_free(&error);
3030 static int dump(DBusConnection *bus, char **args, unsigned n) {
3031 DBusMessage *m = NULL, *reply = NULL;
3036 dbus_error_init(&error);
3038 pager_open_if_enabled();
3040 if (!(m = dbus_message_new_method_call(
3041 "org.freedesktop.systemd1",
3042 "/org/freedesktop/systemd1",
3043 "org.freedesktop.systemd1.Manager",
3045 log_error("Could not allocate message.");
3049 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3050 log_error("Failed to issue method call: %s", bus_error_message(&error));
3055 if (!dbus_message_get_args(reply, &error,
3056 DBUS_TYPE_STRING, &text,
3057 DBUS_TYPE_INVALID)) {
3058 log_error("Failed to parse reply: %s", bus_error_message(&error));
3063 fputs(text, stdout);
3069 dbus_message_unref(m);
3072 dbus_message_unref(reply);
3074 dbus_error_free(&error);
3079 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
3080 DBusMessage *m = NULL, *reply = NULL;
3083 const char *name = "", *path, *id;
3084 dbus_bool_t cleanup = FALSE;
3085 DBusMessageIter iter, sub;
3087 *interface = "org.freedesktop.systemd1.Unit",
3090 dbus_error_init(&error);
3092 if (!(m = dbus_message_new_method_call(
3093 "org.freedesktop.systemd1",
3094 "/org/freedesktop/systemd1",
3095 "org.freedesktop.systemd1.Manager",
3096 "CreateSnapshot"))) {
3097 log_error("Could not allocate message.");
3104 if (!dbus_message_append_args(m,
3105 DBUS_TYPE_STRING, &name,
3106 DBUS_TYPE_BOOLEAN, &cleanup,
3107 DBUS_TYPE_INVALID)) {
3108 log_error("Could not append arguments to message.");
3113 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3114 log_error("Failed to issue method call: %s", bus_error_message(&error));
3119 if (!dbus_message_get_args(reply, &error,
3120 DBUS_TYPE_OBJECT_PATH, &path,
3121 DBUS_TYPE_INVALID)) {
3122 log_error("Failed to parse reply: %s", bus_error_message(&error));
3127 dbus_message_unref(m);
3128 if (!(m = dbus_message_new_method_call(
3129 "org.freedesktop.systemd1",
3131 "org.freedesktop.DBus.Properties",
3133 log_error("Could not allocate message.");
3137 if (!dbus_message_append_args(m,
3138 DBUS_TYPE_STRING, &interface,
3139 DBUS_TYPE_STRING, &property,
3140 DBUS_TYPE_INVALID)) {
3141 log_error("Could not append arguments to message.");
3146 dbus_message_unref(reply);
3147 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3148 log_error("Failed to issue method call: %s", bus_error_message(&error));
3153 if (!dbus_message_iter_init(reply, &iter) ||
3154 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3155 log_error("Failed to parse reply.");
3160 dbus_message_iter_recurse(&iter, &sub);
3162 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3163 log_error("Failed to parse reply.");
3168 dbus_message_iter_get_basic(&sub, &id);
3176 dbus_message_unref(m);
3179 dbus_message_unref(reply);
3181 dbus_error_free(&error);
3186 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
3187 DBusMessage *m = NULL, *reply = NULL;
3195 dbus_error_init(&error);
3197 for (i = 1; i < n; i++) {
3198 const char *path = NULL;
3200 if (!(m = dbus_message_new_method_call(
3201 "org.freedesktop.systemd1",
3202 "/org/freedesktop/systemd1",
3203 "org.freedesktop.systemd1.Manager",
3205 log_error("Could not allocate message.");
3210 if (!dbus_message_append_args(m,
3211 DBUS_TYPE_STRING, &args[i],
3212 DBUS_TYPE_INVALID)) {
3213 log_error("Could not append arguments to message.");
3218 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3219 log_error("Failed to issue method call: %s", bus_error_message(&error));
3224 if (!dbus_message_get_args(reply, &error,
3225 DBUS_TYPE_OBJECT_PATH, &path,
3226 DBUS_TYPE_INVALID)) {
3227 log_error("Failed to parse reply: %s", bus_error_message(&error));
3232 dbus_message_unref(m);
3233 if (!(m = dbus_message_new_method_call(
3234 "org.freedesktop.systemd1",
3236 "org.freedesktop.systemd1.Snapshot",
3238 log_error("Could not allocate message.");
3243 dbus_message_unref(reply);
3244 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3245 log_error("Failed to issue method call: %s", bus_error_message(&error));
3250 dbus_message_unref(m);
3251 dbus_message_unref(reply);
3259 dbus_message_unref(m);
3262 dbus_message_unref(reply);
3264 dbus_error_free(&error);
3269 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
3270 DBusMessage *m = NULL, *reply = NULL;
3275 dbus_error_init(&error);
3277 if (arg_action == ACTION_RELOAD)
3279 else if (arg_action == ACTION_REEXEC)
3280 method = "Reexecute";
3282 assert(arg_action == ACTION_SYSTEMCTL);
3285 streq(args[0], "clear-jobs") ||
3286 streq(args[0], "cancel") ? "ClearJobs" :
3287 streq(args[0], "daemon-reexec") ? "Reexecute" :
3288 streq(args[0], "reset-failed") ? "ResetFailed" :
3289 streq(args[0], "halt") ? "Halt" :
3290 streq(args[0], "poweroff") ? "PowerOff" :
3291 streq(args[0], "reboot") ? "Reboot" :
3292 streq(args[0], "kexec") ? "KExec" :
3293 streq(args[0], "exit") ? "Exit" :
3294 /* "daemon-reload" */ "Reload";
3297 if (!(m = dbus_message_new_method_call(
3298 "org.freedesktop.systemd1",
3299 "/org/freedesktop/systemd1",
3300 "org.freedesktop.systemd1.Manager",
3302 log_error("Could not allocate message.");
3306 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3308 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3309 /* There's always a fallback possible for
3310 * legacy actions. */
3315 if (streq(method, "Reexecute") && dbus_error_has_name(&error, DBUS_ERROR_NO_REPLY)) {
3316 /* On reexecution, we expect a disconnect, not
3322 log_error("Failed to issue method call: %s", bus_error_message(&error));
3331 dbus_message_unref(m);
3334 dbus_message_unref(reply);
3336 dbus_error_free(&error);
3341 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3342 DBusMessage *m = NULL, *reply = NULL;
3348 dbus_error_init(&error);
3351 return daemon_reload(bus, args, n);
3353 for (i = 1; i < n; i++) {
3355 if (!(m = dbus_message_new_method_call(
3356 "org.freedesktop.systemd1",
3357 "/org/freedesktop/systemd1",
3358 "org.freedesktop.systemd1.Manager",
3359 "ResetFailedUnit"))) {
3360 log_error("Could not allocate message.");
3365 if (!dbus_message_append_args(m,
3366 DBUS_TYPE_STRING, args + i,
3367 DBUS_TYPE_INVALID)) {
3368 log_error("Could not append arguments to message.");
3373 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3374 log_error("Failed to issue method call: %s", bus_error_message(&error));
3379 dbus_message_unref(m);
3380 dbus_message_unref(reply);
3388 dbus_message_unref(m);
3391 dbus_message_unref(reply);
3393 dbus_error_free(&error);
3398 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3399 DBusMessage *m = NULL, *reply = NULL;
3401 DBusMessageIter iter, sub, sub2;
3404 *interface = "org.freedesktop.systemd1.Manager",
3405 *property = "Environment";
3407 dbus_error_init(&error);
3409 pager_open_if_enabled();
3411 if (!(m = dbus_message_new_method_call(
3412 "org.freedesktop.systemd1",
3413 "/org/freedesktop/systemd1",
3414 "org.freedesktop.DBus.Properties",
3416 log_error("Could not allocate message.");
3420 if (!dbus_message_append_args(m,
3421 DBUS_TYPE_STRING, &interface,
3422 DBUS_TYPE_STRING, &property,
3423 DBUS_TYPE_INVALID)) {
3424 log_error("Could not append arguments to message.");
3429 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3430 log_error("Failed to issue method call: %s", bus_error_message(&error));
3435 if (!dbus_message_iter_init(reply, &iter) ||
3436 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3437 log_error("Failed to parse reply.");
3442 dbus_message_iter_recurse(&iter, &sub);
3444 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3445 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3446 log_error("Failed to parse reply.");
3451 dbus_message_iter_recurse(&sub, &sub2);
3453 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3456 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3457 log_error("Failed to parse reply.");
3462 dbus_message_iter_get_basic(&sub2, &text);
3463 printf("%s\n", text);
3465 dbus_message_iter_next(&sub2);
3472 dbus_message_unref(m);
3475 dbus_message_unref(reply);
3477 dbus_error_free(&error);
3482 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3483 DBusMessage *m = NULL, *reply = NULL;
3487 DBusMessageIter iter, sub;
3490 dbus_error_init(&error);
3492 method = streq(args[0], "set-environment")
3494 : "UnsetEnvironment";
3496 if (!(m = dbus_message_new_method_call(
3497 "org.freedesktop.systemd1",
3498 "/org/freedesktop/systemd1",
3499 "org.freedesktop.systemd1.Manager",
3502 log_error("Could not allocate message.");
3506 dbus_message_iter_init_append(m, &iter);
3508 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3509 log_error("Could not append arguments to message.");
3514 for (i = 1; i < n; i++)
3515 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3516 log_error("Could not append arguments to message.");
3521 if (!dbus_message_iter_close_container(&iter, &sub)) {
3522 log_error("Could not append arguments to message.");
3527 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3528 log_error("Failed to issue method call: %s", bus_error_message(&error));
3537 dbus_message_unref(m);
3540 dbus_message_unref(reply);
3542 dbus_error_free(&error);
3555 static Hashmap *will_install = NULL, *have_installed = NULL;
3556 static Set *remove_symlinks_to = NULL;
3557 static unsigned n_symlinks = 0;
3559 static void install_info_free(InstallInfo *i) {
3564 strv_free(i->aliases);
3565 strv_free(i->wanted_by);
3569 static void install_info_hashmap_free(Hashmap *m) {
3572 while ((i = hashmap_steal_first(m)))
3573 install_info_free(i);
3578 static int install_info_add(const char *name) {
3582 assert(will_install);
3584 if (!unit_name_is_valid_no_type(name, true)) {
3585 log_warning("Unit name %s is not a valid unit name.", name);
3589 if (hashmap_get(have_installed, name) ||
3590 hashmap_get(will_install, name))
3593 if (!(i = new0(InstallInfo, 1))) {
3598 if (!(i->name = strdup(name))) {
3603 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3610 install_info_free(i);
3615 static int config_parse_also(
3616 const char *filename,
3618 const char *section,
3633 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3637 if (!(n = strndup(w, l)))
3640 if ((r = install_info_add(n)) < 0) {
3641 log_warning("Cannot install unit %s: %s", n, strerror(-r));
3652 static int mark_symlink_for_removal(const char *p) {
3657 assert(path_is_absolute(p));
3659 if (!remove_symlinks_to)
3662 if (!(n = strdup(p)))
3665 path_kill_slashes(n);
3667 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3669 return r == -EEXIST ? 0 : r;
3675 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3684 if (!(d = fdopendir(fd))) {
3685 close_nointr_nofail(fd);
3691 while ((de = readdir(d))) {
3692 bool is_dir = false, is_link = false;
3694 if (ignore_file(de->d_name))
3697 if (de->d_type == DT_LNK)
3699 else if (de->d_type == DT_DIR)
3701 else if (de->d_type == DT_UNKNOWN) {
3704 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3705 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3712 is_link = S_ISLNK(st.st_mode);
3713 is_dir = S_ISDIR(st.st_mode);
3721 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3722 log_error("Failed to open %s/%s: %m", root, de->d_name);
3729 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3730 log_error("Failed to allocate directory string.");
3731 close_nointr_nofail(nfd);
3736 /* This will close nfd, regardless whether it succeeds or not */
3737 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3743 } else if (is_link) {
3747 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3748 log_error("Failed to allocate symlink string.");
3753 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3754 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3762 if ((c = canonicalize_file_name(dest))) {
3763 /* This might fail if the destination
3764 * is already removed */
3770 path_kill_slashes(dest);
3771 if (set_get(remove_symlinks_to, dest)) {
3774 log_info("rm '%s'", p);
3776 if (unlink(p) < 0) {
3777 log_error("Cannot unlink symlink %s: %m", p);
3782 rmdir_parents(p, config_path);
3783 path_kill_slashes(p);
3785 if (!set_get(remove_symlinks_to, p)) {
3787 if ((r = mark_symlink_for_removal(p)) < 0) {
3806 static int remove_marked_symlinks(const char *config_path) {
3810 assert(config_path);
3812 if (set_size(remove_symlinks_to) <= 0)
3815 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3822 if ((cfd = dup(fd)) < 0) {
3827 /* This takes possession of cfd and closes it */
3828 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3834 close_nointr_nofail(fd);
3839 static int create_symlink(const char *verb, const char *orig_old_path, const char *new_path) {
3841 const char *old_path;
3844 old_path = orig_old_path+strlen(arg_root);
3846 old_path = orig_old_path;
3852 if (streq(verb, "enable")) {
3855 mkdir_parents(new_path, 0755);
3857 if (symlink(old_path, new_path) >= 0) {
3860 log_info("ln -s '%s' '%s'", old_path, new_path);
3865 if (errno != EEXIST) {
3866 log_error("Cannot link %s to %s: %m", old_path, new_path);
3870 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3872 if (errno == EINVAL) {
3873 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3877 log_error("readlink() failed: %s", strerror(-r));
3881 if (streq(dest, old_path)) {
3887 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3896 log_info("ln -s '%s' '%s'", old_path, new_path);
3898 if (symlink(old_path, new_path) >= 0)
3901 log_error("Cannot link %s to %s: %m", old_path, new_path);
3904 } else if (streq(verb, "disable")) {
3907 if ((r = mark_symlink_for_removal(old_path)) < 0)
3910 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3911 if (errno == ENOENT)
3914 if (errno == EINVAL) {
3915 log_warning("File %s not a symlink, ignoring.", old_path);
3919 log_error("readlink() failed: %s", strerror(-r));
3923 if (!streq(dest, old_path)) {
3924 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3931 if ((r = mark_symlink_for_removal(new_path)) < 0)
3935 log_info("rm '%s'", new_path);
3937 if (unlink(new_path) >= 0)
3940 log_error("Cannot unlink %s: %m", new_path);
3943 } else if (streq(verb, "is-enabled")) {
3946 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3948 if (errno == ENOENT || errno == EINVAL)
3951 log_error("readlink() failed: %s", strerror(-r));
3955 if (streq(dest, old_path)) {
3964 assert_not_reached("Unknown action.");
3967 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3969 char *alias_path = NULL;
3974 assert(config_path);
3976 STRV_FOREACH(s, i->aliases) {
3979 if (!(alias_path = path_make_absolute(*s, config_path))) {
3980 log_error("Out of memory");
3985 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3988 if (streq(verb, "disable"))
3989 rmdir_parents(alias_path, config_path);
3999 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
4001 char *alias_path = NULL;
4006 assert(config_path);
4008 STRV_FOREACH(s, i->wanted_by) {
4009 if (!unit_name_is_valid_no_type(*s, true)) {
4010 log_error("Invalid name %s.", *s);
4018 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
4019 log_error("Out of memory");
4024 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
4027 if (streq(verb, "disable"))
4028 rmdir_parents(alias_path, config_path);
4039 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
4041 const ConfigItem items[] = {
4042 { "Alias", config_parse_strv, 0, &i->aliases, "Install" },
4043 { "WantedBy", config_parse_strv, 0, &i->wanted_by, "Install" },
4044 { "Also", config_parse_also, 0, NULL, "Install" },
4046 { NULL, NULL, 0, NULL, NULL }
4050 char *filename = NULL;
4057 STRV_FOREACH(p, paths->unit_path) {
4059 char *path, *should_free;
4062 should_free = path = strappend(arg_root, *p);
4068 if (!(filename = path_make_absolute(i->name, path))) {
4069 log_error("Out of memory");
4076 /* Ensure that we don't follow symlinks */
4077 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
4078 if ((f = fdopen(fd, "re")))
4081 if (errno == ELOOP) {
4082 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
4087 if (errno != ENOENT) {
4088 log_error("Failed to open %s: %m", filename);
4098 #if (defined(TARGET_FEDORA) || defined(TARGET_MANDRIVA) || defined(TARGET_SUSE) || defined(TARGET_MEEGO) || defined(TARGET_ALTLINUX)) && defined (HAVE_SYSV_COMPAT)
4100 if (endswith(i->name, ".service")) {
4104 if (asprintf(&sysv, SYSTEM_SYSVINIT_PATH "/%s", i->name) < 0) {
4105 log_error("Out of memory");
4109 sysv[strlen(sysv) - sizeof(".service") + 1] = 0;
4113 tmp_path = strappend (arg_root, sysv);
4114 exists = access (tmp_path, F_OK) >= 0;
4117 exists = access(sysv, F_OK) >= 0;
4123 const char *argv[] = {
4131 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", i->name);
4133 argv[1] = file_name_from_path(sysv);
4135 streq(verb, "enable") ? "on" :
4136 streq(verb, "disable") ? "off" : "--level=5";
4138 argv[3] = strappend("--root=", arg_root);
4140 log_info("Executing %s %s %s %s", argv[0], argv[1], strempty(argv[2]), strempty(argv[3]));
4142 if ((pid = fork()) < 0) {
4143 log_error("Failed to fork: %m");
4146 } else if (pid == 0) {
4147 execv(argv[0], (char**) argv);
4148 _exit(EXIT_FAILURE);
4153 if ((r = wait_for_terminate(pid, &status)) < 0)
4156 if (status.si_code == CLD_EXITED) {
4158 if (streq(verb, "is-enabled"))
4159 return status.si_status == 0 ? 1 : 0;
4161 if (status.si_status == 0)
4164 return status.si_status == 0 ? 0 : -EINVAL;
4175 log_error("Couldn't find %s.", i->name);
4181 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
4186 /* Consider unit files stored in /lib and /usr always enabled
4187 * if they have no [Install] data. */
4188 if (streq(verb, "is-enabled") &&
4189 strv_isempty(i->aliases) &&
4190 strv_isempty(i->wanted_by) &&
4191 !path_startswith(filename, "/etc")) {
4196 n_symlinks += strv_length(i->aliases);
4197 n_symlinks += strv_length(i->wanted_by);
4201 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
4204 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
4207 if ((r = mark_symlink_for_removal(filename)) < 0)
4210 if ((r = remove_marked_symlinks(config_path)) < 0)
4216 static char *get_config_path(void) {
4219 if (arg_user && arg_global)
4220 ret = strdup(USER_CONFIG_UNIT_PATH);
4223 if (user_config_home(&ret) < 0)
4227 ret = strdup(SYSTEM_CONFIG_UNIT_PATH);
4230 p = strappend (arg_root, ret);
4237 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
4241 char *config_path = NULL;
4244 const char *verb = args[0];
4246 dbus_error_init(&error);
4249 if ((r = lookup_paths_init(&paths, arg_user ? MANAGER_USER : MANAGER_SYSTEM)) < 0) {
4250 log_error("Failed to determine lookup paths: %s", strerror(-r));
4254 if (!(config_path = get_config_path())) {
4255 log_error("Failed to determine config path");
4260 will_install = hashmap_new(string_hash_func, string_compare_func);
4261 have_installed = hashmap_new(string_hash_func, string_compare_func);
4263 if (!will_install || !have_installed) {
4264 log_error("Failed to allocate unit sets.");
4269 if (!arg_defaults && streq(verb, "disable"))
4270 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
4271 log_error("Failed to allocate symlink sets.");
4276 for (j = 1; j < n; j++)
4277 if ((r = install_info_add(args[j])) < 0) {
4278 log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
4284 while ((i = hashmap_first(will_install))) {
4287 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
4289 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
4297 /* In test mode and found something */
4303 if (streq(verb, "is-enabled"))
4304 r = r > 0 ? 0 : -ENOENT;
4306 if (n_symlinks <= 0)
4307 log_warning("Unit files contain no applicable installation information. Ignoring.");
4310 /* Don't try to reload anything if the user asked us to not do this */
4312 /* Don't try to reload anything when updating a unit globally */
4314 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
4315 (arg_user || sd_booted() > 0) &&
4316 /* Don't try to reload anything if we are running in a chroot environment */
4317 (arg_user || running_in_chroot() <= 0 || arg_root) ) {
4320 if ((q = daemon_reload(bus, args, n)) < 0)
4326 install_info_hashmap_free(will_install);
4327 install_info_hashmap_free(have_installed);
4329 set_free_free(remove_symlinks_to);
4331 lookup_paths_free(&paths);
4338 static int systemctl_help(void) {
4340 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4341 "Send control commands to or query the systemd manager.\n\n"
4342 " -h --help Show this help\n"
4343 " --version Show package version\n"
4344 " -t --type=TYPE List only units of a particular type\n"
4345 " -p --property=NAME Show only properties by this name\n"
4346 " -a --all Show all units/properties, including dead/empty ones\n"
4347 " --failed Show only failed units\n"
4348 " --full Don't ellipsize unit names on output\n"
4349 " --fail When queueing a new job, fail if conflicting jobs are\n"
4351 " --ignore-dependencies\n"
4352 " When queueing a new job, ignore all its dependencies\n"
4353 " --kill-mode=MODE How to send signal\n"
4354 " --kill-who=WHO Who to send signal to\n"
4355 " -s --signal=SIGNAL Which signal to send\n"
4356 " -H --host=[user@]host\n"
4357 " Show information for remote host\n"
4358 " -P --privileged Acquire privileges before execution\n"
4359 " -q --quiet Suppress output\n"
4360 " --no-block Do not wait until operation finished\n"
4361 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4362 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4364 " --no-pager Do not pipe output into a pager.\n"
4365 " --no-ask-password\n"
4366 " Do not ask for system passwords\n"
4367 " --order When generating graph for dot, show only order\n"
4368 " --require When generating graph for dot, show only requirement\n"
4369 " --root=path Use <root> as the root file system\n"
4370 " --system Connect to system manager\n"
4371 " --user Connect to user service manager\n"
4372 " --global Enable/disable unit files globally\n"
4373 " -f --force When enabling unit files, override existing symlinks\n"
4374 " When shutting down, execute action immediately\n"
4375 " --defaults When disabling unit files, remove default symlinks only\n\n"
4377 " list-units List units\n"
4378 " start [NAME...] Start (activate) one or more units\n"
4379 " stop [NAME...] Stop (deactivate) one or more units\n"
4380 " reload [NAME...] Reload one or more units\n"
4381 " restart [NAME...] Start or restart one or more units\n"
4382 " try-restart [NAME...] Restart one or more units if active\n"
4383 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4384 " otherwise start or restart\n"
4385 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4386 " otherwise restart if active\n"
4387 " isolate [NAME] Start one unit and stop all others\n"
4388 " kill [NAME...] Send signal to processes of a unit\n"
4389 " is-active [NAME...] Check whether units are active\n"
4390 " status [NAME...|PID...] Show runtime status of one or more units\n"
4391 " show [NAME...|JOB...] Show properties of one or more\n"
4392 " units/jobs or the manager\n"
4393 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4395 " enable [NAME...] Enable one or more unit files\n"
4396 " disable [NAME...] Disable one or more unit files\n"
4397 " is-enabled [NAME...] Check whether unit files are enabled\n"
4398 " load [NAME...] Load one or more units\n"
4399 " list-jobs List jobs\n"
4400 " cancel [JOB...] Cancel all, one, or more jobs\n"
4401 " monitor Monitor unit/job changes\n"
4402 " dump Dump server status\n"
4403 " dot Dump dependency graph for dot(1)\n"
4404 " snapshot [NAME] Create a snapshot\n"
4405 " delete [NAME...] Remove one or more snapshots\n"
4406 " daemon-reload Reload systemd manager configuration\n"
4407 " daemon-reexec Reexecute systemd manager\n"
4408 " show-environment Dump environment\n"
4409 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4410 " unset-environment [NAME...] Unset one or more environment variables\n"
4411 " default Enter system default mode\n"
4412 " rescue Enter system rescue mode\n"
4413 " emergency Enter system emergency mode\n"
4414 " halt Shut down and halt the system\n"
4415 " poweroff Shut down and power-off the system\n"
4416 " reboot Shut down and reboot the system\n"
4417 " kexec Shut down and reboot the system with kexec\n"
4418 " exit Ask for user instance termination\n",
4419 program_invocation_short_name);
4424 static int halt_help(void) {
4426 printf("%s [OPTIONS...]\n\n"
4427 "%s the system.\n\n"
4428 " --help Show this help\n"
4429 " --halt Halt the machine\n"
4430 " -p --poweroff Switch off the machine\n"
4431 " --reboot Reboot the machine\n"
4432 " -f --force Force immediate halt/power-off/reboot\n"
4433 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4434 " -d --no-wtmp Don't write wtmp record\n"
4435 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4436 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4437 program_invocation_short_name,
4438 arg_action == ACTION_REBOOT ? "Reboot" :
4439 arg_action == ACTION_POWEROFF ? "Power off" :
4445 static int shutdown_help(void) {
4447 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4448 "Shut down the system.\n\n"
4449 " --help Show this help\n"
4450 " -H --halt Halt the machine\n"
4451 " -P --poweroff Power-off the machine\n"
4452 " -r --reboot Reboot the machine\n"
4453 " -h Equivalent to --poweroff, overriden by --halt\n"
4454 " -k Don't halt/power-off/reboot, just send warnings\n"
4455 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4456 " -c Cancel a pending shutdown\n",
4457 program_invocation_short_name);
4462 static int telinit_help(void) {
4464 printf("%s [OPTIONS...] {COMMAND}\n\n"
4465 "Send control commands to the init daemon.\n\n"
4466 " --help Show this help\n"
4467 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4469 " 0 Power-off the machine\n"
4470 " 6 Reboot the machine\n"
4471 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4472 " 1, s, S Enter rescue mode\n"
4473 " q, Q Reload init daemon configuration\n"
4474 " u, U Reexecute init daemon\n",
4475 program_invocation_short_name);
4480 static int runlevel_help(void) {
4482 printf("%s [OPTIONS...]\n\n"
4483 "Prints the previous and current runlevel of the init system.\n\n"
4484 " --help Show this help\n",
4485 program_invocation_short_name);
4490 static int systemctl_parse_argv(int argc, char *argv[]) {
4494 ARG_IGNORE_DEPENDENCIES,
4510 ARG_NO_ASK_PASSWORD,
4514 static const struct option options[] = {
4515 { "help", no_argument, NULL, 'h' },
4516 { "version", no_argument, NULL, ARG_VERSION },
4517 { "type", required_argument, NULL, 't' },
4518 { "property", required_argument, NULL, 'p' },
4519 { "all", no_argument, NULL, 'a' },
4520 { "failed", no_argument, NULL, ARG_FAILED },
4521 { "full", no_argument, NULL, ARG_FULL },
4522 { "fail", no_argument, NULL, ARG_FAIL },
4523 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4524 { "user", no_argument, NULL, ARG_USER },
4525 { "system", no_argument, NULL, ARG_SYSTEM },
4526 { "global", no_argument, NULL, ARG_GLOBAL },
4527 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4528 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4529 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4530 { "quiet", no_argument, NULL, 'q' },
4531 { "order", no_argument, NULL, ARG_ORDER },
4532 { "require", no_argument, NULL, ARG_REQUIRE },
4533 { "root", required_argument, NULL, ARG_ROOT },
4534 { "force", no_argument, NULL, 'f' },
4535 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4536 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4537 { "kill-mode", required_argument, NULL, ARG_KILL_MODE },
4538 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4539 { "signal", required_argument, NULL, 's' },
4540 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4541 { "host", required_argument, NULL, 'H' },
4542 { "privileged",no_argument, NULL, 'P' },
4543 { NULL, 0, NULL, 0 }
4551 /* Only when running as systemctl we ask for passwords */
4552 arg_ask_password = true;
4554 while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:P", options, NULL)) >= 0) {
4563 puts(PACKAGE_STRING);
4565 puts(SYSTEMD_FEATURES);
4575 if (!(l = strv_append(arg_property, optarg)))
4578 strv_free(arg_property);
4581 /* If the user asked for a particular
4582 * property, show it to him, even if it is
4593 arg_job_mode = "fail";
4596 case ARG_IGNORE_DEPENDENCIES:
4597 arg_job_mode = "ignore-dependencies";
4609 arg_no_block = true;
4613 arg_no_pager = true;
4621 arg_dot = DOT_ORDER;
4625 arg_dot = DOT_REQUIRE;
4649 arg_no_reload = true;
4658 arg_defaults = true;
4662 arg_kill_who = optarg;
4666 arg_kill_mode = optarg;
4670 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4671 log_error("Failed to parse signal string %s.", optarg);
4676 case ARG_NO_ASK_PASSWORD:
4677 arg_ask_password = false;
4681 arg_transport = TRANSPORT_POLKIT;
4685 arg_transport = TRANSPORT_SSH;
4693 log_error("Unknown option code %c", c);
4698 if (arg_transport != TRANSPORT_NORMAL && arg_user) {
4699 log_error("Cannot access user instance remotely.");
4706 static int halt_parse_argv(int argc, char *argv[]) {
4715 static const struct option options[] = {
4716 { "help", no_argument, NULL, ARG_HELP },
4717 { "halt", no_argument, NULL, ARG_HALT },
4718 { "poweroff", no_argument, NULL, 'p' },
4719 { "reboot", no_argument, NULL, ARG_REBOOT },
4720 { "force", no_argument, NULL, 'f' },
4721 { "wtmp-only", no_argument, NULL, 'w' },
4722 { "no-wtmp", no_argument, NULL, 'd' },
4723 { "no-sync", no_argument, NULL, 'n' },
4724 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4725 { NULL, 0, NULL, 0 }
4733 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4734 if (runlevel == '0' || runlevel == '6')
4735 arg_immediate = true;
4737 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4745 arg_action = ACTION_HALT;
4749 if (arg_action != ACTION_REBOOT)
4750 arg_action = ACTION_POWEROFF;
4754 arg_action = ACTION_REBOOT;
4758 arg_immediate = true;
4779 /* Compatibility nops */
4786 log_error("Unknown option code %c", c);
4791 if (optind < argc) {
4792 log_error("Too many arguments.");
4799 static int parse_time_spec(const char *t, usec_t *_u) {
4803 if (streq(t, "now"))
4805 else if (!strchr(t, ':')) {
4808 if (safe_atou64(t, &u) < 0)
4811 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4820 hour = strtol(t, &e, 10);
4821 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4824 minute = strtol(e+1, &e, 10);
4825 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4828 n = now(CLOCK_REALTIME);
4829 s = (time_t) (n / USEC_PER_SEC);
4832 assert_se(localtime_r(&s, &tm));
4834 tm.tm_hour = (int) hour;
4835 tm.tm_min = (int) minute;
4838 assert_se(s = mktime(&tm));
4840 *_u = (usec_t) s * USEC_PER_SEC;
4843 *_u += USEC_PER_DAY;
4849 static bool kexec_loaded(void) {
4850 bool loaded = false;
4853 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4861 static int shutdown_parse_argv(int argc, char *argv[]) {
4868 static const struct option options[] = {
4869 { "help", no_argument, NULL, ARG_HELP },
4870 { "halt", no_argument, NULL, 'H' },
4871 { "poweroff", no_argument, NULL, 'P' },
4872 { "reboot", no_argument, NULL, 'r' },
4873 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4874 { NULL, 0, NULL, 0 }
4882 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4890 arg_action = ACTION_HALT;
4894 arg_action = ACTION_POWEROFF;
4899 arg_action = ACTION_KEXEC;
4901 arg_action = ACTION_REBOOT;
4905 if (arg_action != ACTION_HALT)
4906 arg_action = ACTION_POWEROFF;
4919 /* Compatibility nops */
4923 arg_action = ACTION_CANCEL_SHUTDOWN;
4930 log_error("Unknown option code %c", c);
4935 if (argc > optind) {
4936 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4937 log_error("Failed to parse time specification: %s", argv[optind]);
4941 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4943 /* We skip the time argument */
4944 if (argc > optind + 1)
4945 arg_wall = argv + optind + 1;
4952 static int telinit_parse_argv(int argc, char *argv[]) {
4959 static const struct option options[] = {
4960 { "help", no_argument, NULL, ARG_HELP },
4961 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4962 { NULL, 0, NULL, 0 }
4965 static const struct {
4969 { '0', ACTION_POWEROFF },
4970 { '6', ACTION_REBOOT },
4971 { '1', ACTION_RESCUE },
4972 { '2', ACTION_RUNLEVEL2 },
4973 { '3', ACTION_RUNLEVEL3 },
4974 { '4', ACTION_RUNLEVEL4 },
4975 { '5', ACTION_RUNLEVEL5 },
4976 { 's', ACTION_RESCUE },
4977 { 'S', ACTION_RESCUE },
4978 { 'q', ACTION_RELOAD },
4979 { 'Q', ACTION_RELOAD },
4980 { 'u', ACTION_REEXEC },
4981 { 'U', ACTION_REEXEC }
4990 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5005 log_error("Unknown option code %c", c);
5010 if (optind >= argc) {
5015 if (optind + 1 < argc) {
5016 log_error("Too many arguments.");
5020 if (strlen(argv[optind]) != 1) {
5021 log_error("Expected single character argument.");
5025 for (i = 0; i < ELEMENTSOF(table); i++)
5026 if (table[i].from == argv[optind][0])
5029 if (i >= ELEMENTSOF(table)) {
5030 log_error("Unknown command %s.", argv[optind]);
5034 arg_action = table[i].to;
5041 static int runlevel_parse_argv(int argc, char *argv[]) {
5047 static const struct option options[] = {
5048 { "help", no_argument, NULL, ARG_HELP },
5049 { NULL, 0, NULL, 0 }
5057 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5068 log_error("Unknown option code %c", c);
5073 if (optind < argc) {
5074 log_error("Too many arguments.");
5081 static int parse_argv(int argc, char *argv[]) {
5085 if (program_invocation_short_name) {
5087 if (strstr(program_invocation_short_name, "halt")) {
5088 arg_action = ACTION_HALT;
5089 return halt_parse_argv(argc, argv);
5090 } else if (strstr(program_invocation_short_name, "poweroff")) {
5091 arg_action = ACTION_POWEROFF;
5092 return halt_parse_argv(argc, argv);
5093 } else if (strstr(program_invocation_short_name, "reboot")) {
5095 arg_action = ACTION_KEXEC;
5097 arg_action = ACTION_REBOOT;
5098 return halt_parse_argv(argc, argv);
5099 } else if (strstr(program_invocation_short_name, "shutdown")) {
5100 arg_action = ACTION_POWEROFF;
5101 return shutdown_parse_argv(argc, argv);
5102 } else if (strstr(program_invocation_short_name, "init")) {
5104 if (sd_booted() > 0) {
5105 arg_action = ACTION_INVALID;
5106 return telinit_parse_argv(argc, argv);
5108 /* Hmm, so some other init system is
5109 * running, we need to forward this
5110 * request to it. For now we simply
5111 * guess that it is Upstart. */
5113 execv("/lib/upstart/telinit", argv);
5115 log_error("Couldn't find an alternative telinit implementation to spawn.");
5119 } else if (strstr(program_invocation_short_name, "runlevel")) {
5120 arg_action = ACTION_RUNLEVEL;
5121 return runlevel_parse_argv(argc, argv);
5125 arg_action = ACTION_SYSTEMCTL;
5126 return systemctl_parse_argv(argc, argv);
5129 static int action_to_runlevel(void) {
5131 static const char table[_ACTION_MAX] = {
5132 [ACTION_HALT] = '0',
5133 [ACTION_POWEROFF] = '0',
5134 [ACTION_REBOOT] = '6',
5135 [ACTION_RUNLEVEL2] = '2',
5136 [ACTION_RUNLEVEL3] = '3',
5137 [ACTION_RUNLEVEL4] = '4',
5138 [ACTION_RUNLEVEL5] = '5',
5139 [ACTION_RESCUE] = '1'
5142 assert(arg_action < _ACTION_MAX);
5144 return table[arg_action];
5147 static int talk_upstart(void) {
5148 DBusMessage *m = NULL, *reply = NULL;
5150 int previous, rl, r;
5152 env1_buf[] = "RUNLEVEL=X",
5153 env2_buf[] = "PREVLEVEL=X";
5154 char *env1 = env1_buf, *env2 = env2_buf;
5155 const char *emit = "runlevel";
5156 dbus_bool_t b_false = FALSE;
5157 DBusMessageIter iter, sub;
5158 DBusConnection *bus;
5160 dbus_error_init(&error);
5162 if (!(rl = action_to_runlevel()))
5165 if (utmp_get_runlevel(&previous, NULL) < 0)
5168 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
5169 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
5174 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
5179 if ((r = bus_check_peercred(bus)) < 0) {
5180 log_error("Failed to verify owner of bus.");
5184 if (!(m = dbus_message_new_method_call(
5185 "com.ubuntu.Upstart",
5186 "/com/ubuntu/Upstart",
5187 "com.ubuntu.Upstart0_6",
5190 log_error("Could not allocate message.");
5195 dbus_message_iter_init_append(m, &iter);
5197 env1_buf[sizeof(env1_buf)-2] = rl;
5198 env2_buf[sizeof(env2_buf)-2] = previous;
5200 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5201 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5202 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5203 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5204 !dbus_message_iter_close_container(&iter, &sub) ||
5205 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5206 log_error("Could not append arguments to message.");
5211 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5213 if (error_is_no_service(&error)) {
5218 log_error("Failed to issue method call: %s", bus_error_message(&error));
5227 dbus_message_unref(m);
5230 dbus_message_unref(reply);
5233 dbus_connection_flush(bus);
5234 dbus_connection_close(bus);
5235 dbus_connection_unref(bus);
5238 dbus_error_free(&error);
5243 static int talk_initctl(void) {
5244 struct init_request request;
5248 if (!(rl = action_to_runlevel()))
5252 request.magic = INIT_MAGIC;
5253 request.sleeptime = 0;
5254 request.cmd = INIT_CMD_RUNLVL;
5255 request.runlevel = rl;
5257 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5259 if (errno == ENOENT)
5262 log_error("Failed to open "INIT_FIFO": %m");
5267 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5268 close_nointr_nofail(fd);
5271 log_error("Failed to write to "INIT_FIFO": %m");
5272 return errno ? -errno : -EIO;
5278 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5280 static const struct {
5288 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
5290 { "list-units", LESS, 1, list_units },
5291 { "list-jobs", EQUAL, 1, list_jobs },
5292 { "clear-jobs", EQUAL, 1, daemon_reload },
5293 { "load", MORE, 2, load_unit },
5294 { "cancel", MORE, 2, cancel_job },
5295 { "start", MORE, 2, start_unit },
5296 { "stop", MORE, 2, start_unit },
5297 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5298 { "reload", MORE, 2, start_unit },
5299 { "restart", MORE, 2, start_unit },
5300 { "try-restart", MORE, 2, start_unit },
5301 { "reload-or-restart", MORE, 2, start_unit },
5302 { "reload-or-try-restart", MORE, 2, start_unit },
5303 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5304 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5305 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5306 { "isolate", EQUAL, 2, start_unit },
5307 { "kill", MORE, 2, kill_unit },
5308 { "is-active", MORE, 2, check_unit },
5309 { "check", MORE, 2, check_unit },
5310 { "show", MORE, 1, show },
5311 { "status", MORE, 2, show },
5312 { "monitor", EQUAL, 1, monitor },
5313 { "dump", EQUAL, 1, dump },
5314 { "dot", EQUAL, 1, dot },
5315 { "snapshot", LESS, 2, snapshot },
5316 { "delete", MORE, 2, delete_snapshot },
5317 { "daemon-reload", EQUAL, 1, daemon_reload },
5318 { "daemon-reexec", EQUAL, 1, daemon_reload },
5319 { "show-environment", EQUAL, 1, show_enviroment },
5320 { "set-environment", MORE, 2, set_environment },
5321 { "unset-environment", MORE, 2, set_environment },
5322 { "halt", EQUAL, 1, start_special },
5323 { "poweroff", EQUAL, 1, start_special },
5324 { "reboot", EQUAL, 1, start_special },
5325 { "kexec", EQUAL, 1, start_special },
5326 { "default", EQUAL, 1, start_special },
5327 { "rescue", EQUAL, 1, start_special },
5328 { "emergency", EQUAL, 1, start_special },
5329 { "exit", EQUAL, 1, start_special },
5330 { "reset-failed", MORE, 1, reset_failed },
5331 { "enable", MORE, 2, enable_unit },
5332 { "disable", MORE, 2, enable_unit },
5333 { "is-enabled", MORE, 2, enable_unit }
5343 left = argc - optind;
5346 /* Special rule: no arguments means "list-units" */
5349 if (streq(argv[optind], "help")) {
5354 for (i = 0; i < ELEMENTSOF(verbs); i++)
5355 if (streq(argv[optind], verbs[i].verb))
5358 if (i >= ELEMENTSOF(verbs)) {
5359 log_error("Unknown operation %s", argv[optind]);
5364 switch (verbs[i].argc_cmp) {
5367 if (left != verbs[i].argc) {
5368 log_error("Invalid number of arguments.");
5375 if (left < verbs[i].argc) {
5376 log_error("Too few arguments.");
5383 if (left > verbs[i].argc) {
5384 log_error("Too many arguments.");
5391 assert_not_reached("Unknown comparison operator.");
5394 /* Require a bus connection for all operations but
5396 if (!streq(verbs[i].verb, "enable") && !streq(verbs[i].verb, "disable")) {
5398 if (running_in_chroot() > 0) {
5399 log_info("Running in chroot, ignoring request.");
5404 log_error("Failed to get D-Bus connection: %s", error->message);
5409 return verbs[i].dispatch(bus, argv + optind, left);
5412 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
5414 struct msghdr msghdr;
5416 union sockaddr_union sockaddr;
5417 struct shutdownd_command c;
5422 c.dry_run = dry_run;
5426 strncpy(c.wall_message, message, sizeof(c.wall_message));
5428 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
5432 sockaddr.sa.sa_family = AF_UNIX;
5433 sockaddr.un.sun_path[0] = 0;
5434 strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5437 iovec.iov_base = (char*) &c;
5438 iovec.iov_len = sizeof(c);
5441 msghdr.msg_name = &sockaddr;
5442 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5444 msghdr.msg_iov = &iovec;
5445 msghdr.msg_iovlen = 1;
5447 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5448 close_nointr_nofail(fd);
5452 close_nointr_nofail(fd);
5456 static int reload_with_fallback(DBusConnection *bus) {
5459 /* First, try systemd via D-Bus. */
5460 if (daemon_reload(bus, NULL, 0) > 0)
5464 /* Nothing else worked, so let's try signals */
5465 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5467 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5468 log_error("kill() failed: %m");
5475 static int start_with_fallback(DBusConnection *bus) {
5478 /* First, try systemd via D-Bus. */
5479 if (start_unit(bus, NULL, 0) >= 0)
5483 /* Hmm, talking to systemd via D-Bus didn't work. Then
5484 * let's try to talk to Upstart via D-Bus. */
5485 if (talk_upstart() > 0)
5488 /* Nothing else worked, so let's try
5490 if (talk_initctl() > 0)
5493 log_error("Failed to talk to init daemon.");
5497 warn_wall(arg_action);
5501 static int halt_main(DBusConnection *bus) {
5504 if (geteuid() != 0) {
5505 log_error("Must be root.");
5511 char date[FORMAT_TIMESTAMP_MAX];
5513 m = strv_join(arg_wall, " ");
5514 r = send_shutdownd(arg_when,
5515 arg_action == ACTION_HALT ? 'H' :
5516 arg_action == ACTION_POWEROFF ? 'P' :
5524 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5526 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5527 format_timestamp(date, sizeof(date), arg_when));
5532 if (!arg_dry && !arg_immediate)
5533 return start_with_fallback(bus);
5536 if (sd_booted() > 0)
5537 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5538 else if ((r = utmp_put_shutdown(0)) < 0)
5539 log_warning("Failed to write utmp record: %s", strerror(-r));
5548 /* Make sure C-A-D is handled by the kernel from this
5550 reboot(RB_ENABLE_CAD);
5552 switch (arg_action) {
5555 log_info("Halting.");
5556 reboot(RB_HALT_SYSTEM);
5559 case ACTION_POWEROFF:
5560 log_info("Powering off.");
5561 reboot(RB_POWER_OFF);
5565 log_info("Rebooting.");
5566 reboot(RB_AUTOBOOT);
5570 assert_not_reached("Unknown halt action.");
5573 /* We should never reach this. */
5577 static int runlevel_main(void) {
5578 int r, runlevel, previous;
5580 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5581 printf("unknown\n");
5586 previous <= 0 ? 'N' : previous,
5587 runlevel <= 0 ? 'N' : runlevel);
5592 static void agent_close(void) {
5598 /* Inform agent that we are done */
5599 kill(agent_pid, SIGTERM);
5600 kill(agent_pid, SIGCONT);
5601 wait_for_terminate(agent_pid, &dummy);
5605 int main(int argc, char*argv[]) {
5606 int r, retval = EXIT_FAILURE;
5607 DBusConnection *bus = NULL;
5610 dbus_error_init(&error);
5612 log_parse_environment();
5615 if ((r = parse_argv(argc, argv)) < 0)
5618 retval = EXIT_SUCCESS;
5622 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5623 * let's shortcut this */
5624 if (arg_action == ACTION_RUNLEVEL) {
5625 r = runlevel_main();
5626 retval = r < 0 ? EXIT_FAILURE : r;
5630 if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5631 log_info("Running in chroot, ignoring request.");
5636 if (arg_transport == TRANSPORT_NORMAL)
5637 bus_connect(arg_user ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5638 else if (arg_transport == TRANSPORT_POLKIT) {
5639 bus_connect_system_polkit(&bus, &error);
5640 private_bus = false;
5641 } else if (arg_transport == TRANSPORT_SSH) {
5642 bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5643 private_bus = false;
5645 assert_not_reached("Uh, invalid transport...");
5647 switch (arg_action) {
5649 case ACTION_SYSTEMCTL:
5650 r = systemctl_main(bus, argc, argv, &error);
5654 case ACTION_POWEROFF:
5660 case ACTION_RUNLEVEL2:
5661 case ACTION_RUNLEVEL3:
5662 case ACTION_RUNLEVEL4:
5663 case ACTION_RUNLEVEL5:
5665 case ACTION_EMERGENCY:
5666 case ACTION_DEFAULT:
5667 r = start_with_fallback(bus);
5672 r = reload_with_fallback(bus);
5675 case ACTION_CANCEL_SHUTDOWN:
5676 r = send_shutdownd(0, 0, false, false, NULL);
5679 case ACTION_INVALID:
5680 case ACTION_RUNLEVEL:
5682 assert_not_reached("Unknown action");
5685 retval = r < 0 ? EXIT_FAILURE : r;
5690 dbus_connection_flush(bus);
5691 dbus_connection_close(bus);
5692 dbus_connection_unref(bus);
5695 dbus_error_free(&error);
5699 strv_free(arg_property);