1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <sys/reboot.h>
28 #include <sys/ioctl.h>
32 #include <sys/socket.h>
35 #include <sys/prctl.h>
37 #include <dbus/dbus.h>
43 #include "utmp-wtmp.h"
47 #include "dbus-common.h"
48 #include "cgroup-show.h"
49 #include "cgroup-util.h"
51 #include "path-lookup.h"
52 #include "conf-parser.h"
53 #include "sd-daemon.h"
54 #include "shutdownd.h"
55 #include "exit-status.h"
56 #include "bus-errors.h"
58 #include "unit-name.h"
60 static const char *arg_type = NULL;
61 static char **arg_property = NULL;
62 static bool arg_all = false;
63 static const char *arg_job_mode = "replace";
64 static bool arg_user = false;
65 static bool arg_global = false;
66 static bool arg_immediate = false;
67 static bool arg_no_block = false;
68 static bool arg_no_pager = false;
69 static bool arg_no_wtmp = false;
70 static bool arg_no_sync = false;
71 static bool arg_no_wall = false;
72 static bool arg_no_reload = false;
73 static bool arg_dry = false;
74 static bool arg_quiet = false;
75 static bool arg_full = false;
76 static bool arg_force = false;
77 static bool arg_defaults = false;
78 static bool arg_ask_password = false;
79 static bool arg_failed = false;
80 static char **arg_wall = NULL;
81 static const char *arg_kill_who = NULL;
82 static const char *arg_kill_mode = NULL;
83 static int arg_signal = SIGTERM;
84 static usec_t arg_when = 0;
103 ACTION_CANCEL_SHUTDOWN,
105 } arg_action = ACTION_SYSTEMCTL;
112 static bool private_bus = false;
114 static pid_t pager_pid = 0;
115 static pid_t agent_pid = 0;
117 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
118 static void pager_open(void);
120 static bool on_tty(void) {
123 /* Note that this is invoked relatively early, before we start
124 * the pager. That means the value we return reflects whether
125 * we originally were started on a tty, not if we currently
126 * are. But this is intended, since we want colour and so on
127 * when run in our own pager. */
129 if (_unlikely_(t < 0))
130 t = isatty(STDOUT_FILENO) > 0;
135 static void spawn_ask_password_agent(void) {
141 /* We check STDIN here, not STDOUT, since this is about input,
143 if (!isatty(STDIN_FILENO))
146 if (!arg_ask_password)
154 /* Spawns a temporary TTY agent, making sure it goes away when
157 if ((agent_pid = fork()) < 0)
160 if (agent_pid == 0) {
164 bool stdout_is_tty, stderr_is_tty;
166 /* Make sure the agent goes away when the parent dies */
167 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
170 /* Check whether our parent died before we were able
171 * to set the death signal */
172 if (getppid() != parent)
175 /* Don't leak fds to the agent */
176 close_all_fds(NULL, 0);
178 stdout_is_tty = isatty(STDOUT_FILENO);
179 stderr_is_tty = isatty(STDERR_FILENO);
181 if (!stdout_is_tty || !stderr_is_tty) {
182 /* Detach from stdout/stderr. and reopen
183 * /dev/tty for them. This is important to
184 * ensure that when systemctl is started via
185 * popen() or a similar call that expects to
186 * read EOF we actually do generate EOF and
187 * not delay this indefinitely by because we
188 * keep an unused copy of stdin around. */
189 if ((fd = open("/dev/tty", O_WRONLY)) < 0) {
190 log_error("Failed to open /dev/tty: %m");
195 dup2(fd, STDOUT_FILENO);
198 dup2(fd, STDERR_FILENO);
204 execl(SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, "--watch", NULL);
206 log_error("Unable to execute agent: %m");
211 static const char *ansi_highlight(bool b) {
216 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
219 static const char *ansi_highlight_green(bool b) {
224 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
227 static bool error_is_no_service(const DBusError *error) {
230 if (!dbus_error_is_set(error))
233 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
236 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
239 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
242 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
245 if (!dbus_error_is_set(error))
248 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
249 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
250 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
251 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
252 return EXIT_NOPERMISSION;
254 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
255 return EXIT_NOTINSTALLED;
257 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
258 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
259 return EXIT_NOTIMPLEMENTED;
261 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
262 return EXIT_NOTCONFIGURED;
270 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
275 if (dbus_message_iter_get_arg_type(iter) != type)
278 dbus_message_iter_get_basic(iter, data);
280 if (!dbus_message_iter_next(iter) != !next)
286 static void warn_wall(enum action action) {
287 static const char *table[_ACTION_MAX] = {
288 [ACTION_HALT] = "The system is going down for system halt NOW!",
289 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
290 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
291 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
292 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
293 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
302 if (!(p = strv_join(arg_wall, " "))) {
303 log_error("Failed to join strings.");
319 utmp_wall(table[action], NULL);
324 const char *description;
325 const char *load_state;
326 const char *active_state;
327 const char *sub_state;
328 const char *following;
329 const char *unit_path;
331 const char *job_type;
332 const char *job_path;
335 static int compare_unit_info(const void *a, const void *b) {
337 const struct unit_info *u = a, *v = b;
339 d1 = strrchr(u->id, '.');
340 d2 = strrchr(v->id, '.');
345 if ((r = strcasecmp(d1, d2)) != 0)
349 return strcasecmp(u->id, v->id);
352 static bool output_show_unit(const struct unit_info *u) {
356 return streq(u->active_state, "failed");
358 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
359 streq(dot+1, arg_type))) &&
360 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0);
363 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
364 unsigned active_len, sub_len, job_len, n_shown = 0;
365 const struct unit_info *u;
367 active_len = sizeof("ACTIVE")-1;
368 sub_len = sizeof("SUB")-1;
369 job_len = sizeof("JOB")-1;
371 for (u = unit_infos; u < unit_infos + c; u++) {
372 if (!output_show_unit(u))
375 active_len = MAX(active_len, strlen(u->active_state));
376 sub_len = MAX(sub_len, strlen(u->sub_state));
378 job_len = MAX(job_len, strlen(u->job_type));
382 printf("%-25s %-6s %-*s %-*s %-*s", "UNIT", "LOAD",
383 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
384 if (columns() >= 80+12 || arg_full)
385 printf(" %s\n", "DESCRIPTION");
390 for (u = unit_infos; u < unit_infos + c; u++) {
393 const char *on_loaded, *off_loaded;
394 const char *on_active, *off_active;
396 if (!output_show_unit(u))
401 if (!streq(u->load_state, "loaded") &&
402 !streq(u->load_state, "banned")) {
403 on_loaded = ansi_highlight(true);
404 off_loaded = ansi_highlight(false);
406 on_loaded = off_loaded = "";
408 if (streq(u->active_state, "failed")) {
409 on_active = ansi_highlight(true);
410 off_active = ansi_highlight(false);
412 on_active = off_active = "";
414 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
416 printf("%-25s %s%-6s%s %s%-*s %-*s%s%n",
418 on_loaded, u->load_state, off_loaded,
419 on_active, active_len, u->active_state,
420 sub_len, u->sub_state, off_active,
425 a -= strlen(on_loaded) + strlen(off_loaded);
426 a -= strlen(on_active) + strlen(off_active);
429 printf(" %-*s", job_len, u->job_type);
433 if (a + b + 1 < columns()) {
435 printf(" %-*s", job_len, "");
438 printf(" %s", u->description);
440 printf(" %.*s", columns() - a - b - 1, u->description);
447 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
448 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
449 "SUB = The low-level unit activation state, values depend on unit type.\n"
450 "JOB = Pending job for the unit.\n");
453 printf("\n%u units listed.\n", n_shown);
455 printf("\n%u units listed. Pass --all to see inactive units, too.\n", n_shown);
459 static int list_units(DBusConnection *bus, char **args, unsigned n) {
460 DBusMessage *m = NULL, *reply = NULL;
463 DBusMessageIter iter, sub, sub2;
464 unsigned c = 0, n_units = 0;
465 struct unit_info *unit_infos = NULL;
467 dbus_error_init(&error);
473 if (!(m = dbus_message_new_method_call(
474 "org.freedesktop.systemd1",
475 "/org/freedesktop/systemd1",
476 "org.freedesktop.systemd1.Manager",
478 log_error("Could not allocate message.");
482 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
483 log_error("Failed to issue method call: %s", bus_error_message(&error));
488 if (!dbus_message_iter_init(reply, &iter) ||
489 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
490 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
491 log_error("Failed to parse reply.");
496 dbus_message_iter_recurse(&iter, &sub);
498 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
501 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
502 log_error("Failed to parse reply.");
510 n_units = MAX(2*c, 16);
511 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
514 log_error("Failed to allocate unit array.");
524 dbus_message_iter_recurse(&sub, &sub2);
526 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
527 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
528 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
529 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
530 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
531 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
532 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
533 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
534 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
535 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
536 log_error("Failed to parse reply.");
541 dbus_message_iter_next(&sub);
546 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
547 output_units_list(unit_infos, c);
554 dbus_message_unref(m);
557 dbus_message_unref(reply);
561 dbus_error_free(&error);
566 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
567 static const char * const colors[] = {
568 "Requires", "[color=\"black\"]",
569 "RequiresOverridable", "[color=\"black\"]",
570 "Requisite", "[color=\"darkblue\"]",
571 "RequisiteOverridable", "[color=\"darkblue\"]",
572 "Wants", "[color=\"darkgrey\"]",
573 "Conflicts", "[color=\"red\"]",
574 "ConflictedBy", "[color=\"red\"]",
575 "After", "[color=\"green\"]"
578 const char *c = NULL;
585 for (i = 0; i < ELEMENTSOF(colors); i += 2)
586 if (streq(colors[i], prop)) {
594 if (arg_dot != DOT_ALL)
595 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
598 switch (dbus_message_iter_get_arg_type(iter)) {
600 case DBUS_TYPE_ARRAY:
602 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
605 dbus_message_iter_recurse(iter, &sub);
607 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
610 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
611 dbus_message_iter_get_basic(&sub, &s);
612 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
614 dbus_message_iter_next(&sub);
624 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
625 DBusMessage *m = NULL, *reply = NULL;
626 const char *interface = "org.freedesktop.systemd1.Unit";
629 DBusMessageIter iter, sub, sub2, sub3;
634 dbus_error_init(&error);
636 if (!(m = dbus_message_new_method_call(
637 "org.freedesktop.systemd1",
639 "org.freedesktop.DBus.Properties",
641 log_error("Could not allocate message.");
646 if (!dbus_message_append_args(m,
647 DBUS_TYPE_STRING, &interface,
648 DBUS_TYPE_INVALID)) {
649 log_error("Could not append arguments to message.");
654 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
655 log_error("Failed to issue method call: %s", bus_error_message(&error));
660 if (!dbus_message_iter_init(reply, &iter) ||
661 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
662 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
663 log_error("Failed to parse reply.");
668 dbus_message_iter_recurse(&iter, &sub);
670 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
673 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
674 log_error("Failed to parse reply.");
679 dbus_message_iter_recurse(&sub, &sub2);
681 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
682 log_error("Failed to parse reply.");
687 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
688 log_error("Failed to parse reply.");
693 dbus_message_iter_recurse(&sub2, &sub3);
695 if (dot_one_property(name, prop, &sub3)) {
696 log_error("Failed to parse reply.");
701 dbus_message_iter_next(&sub);
708 dbus_message_unref(m);
711 dbus_message_unref(reply);
713 dbus_error_free(&error);
718 static int dot(DBusConnection *bus, char **args, unsigned n) {
719 DBusMessage *m = NULL, *reply = NULL;
722 DBusMessageIter iter, sub, sub2;
724 dbus_error_init(&error);
728 if (!(m = dbus_message_new_method_call(
729 "org.freedesktop.systemd1",
730 "/org/freedesktop/systemd1",
731 "org.freedesktop.systemd1.Manager",
733 log_error("Could not allocate message.");
737 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
738 log_error("Failed to issue method call: %s", bus_error_message(&error));
743 if (!dbus_message_iter_init(reply, &iter) ||
744 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
745 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
746 log_error("Failed to parse reply.");
751 printf("digraph systemd {\n");
753 dbus_message_iter_recurse(&iter, &sub);
754 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
755 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
757 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
758 log_error("Failed to parse reply.");
763 dbus_message_iter_recurse(&sub, &sub2);
765 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
766 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
767 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
768 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
769 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
770 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
771 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
772 log_error("Failed to parse reply.");
777 if ((r = dot_one(bus, id, unit_path)) < 0)
780 /* printf("\t\"%s\";\n", id); */
781 dbus_message_iter_next(&sub);
786 log_info(" Color legend: black = Requires\n"
787 " dark blue = Requisite\n"
788 " dark grey = Wants\n"
792 if (isatty(fileno(stdout)))
793 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
794 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
800 dbus_message_unref(m);
803 dbus_message_unref(reply);
805 dbus_error_free(&error);
810 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
811 DBusMessage *m = NULL, *reply = NULL;
814 DBusMessageIter iter, sub, sub2;
817 dbus_error_init(&error);
823 if (!(m = dbus_message_new_method_call(
824 "org.freedesktop.systemd1",
825 "/org/freedesktop/systemd1",
826 "org.freedesktop.systemd1.Manager",
828 log_error("Could not allocate message.");
832 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
833 log_error("Failed to issue method call: %s", bus_error_message(&error));
838 if (!dbus_message_iter_init(reply, &iter) ||
839 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
840 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
841 log_error("Failed to parse reply.");
846 dbus_message_iter_recurse(&iter, &sub);
848 if (isatty(STDOUT_FILENO))
849 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
851 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
852 const char *name, *type, *state, *job_path, *unit_path;
856 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
857 log_error("Failed to parse reply.");
862 dbus_message_iter_recurse(&sub, &sub2);
864 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
865 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
866 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
867 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
868 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
869 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
870 log_error("Failed to parse reply.");
875 e = arg_full ? NULL : ellipsize(name, 25, 33);
876 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
881 dbus_message_iter_next(&sub);
884 if (isatty(STDOUT_FILENO))
885 printf("\n%u jobs listed.\n", k);
891 dbus_message_unref(m);
894 dbus_message_unref(reply);
896 dbus_error_free(&error);
901 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
902 DBusMessage *m = NULL, *reply = NULL;
907 dbus_error_init(&error);
912 for (i = 1; i < n; i++) {
914 if (!(m = dbus_message_new_method_call(
915 "org.freedesktop.systemd1",
916 "/org/freedesktop/systemd1",
917 "org.freedesktop.systemd1.Manager",
919 log_error("Could not allocate message.");
924 if (!dbus_message_append_args(m,
925 DBUS_TYPE_STRING, &args[i],
926 DBUS_TYPE_INVALID)) {
927 log_error("Could not append arguments to message.");
932 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
933 log_error("Failed to issue method call: %s", bus_error_message(&error));
938 dbus_message_unref(m);
939 dbus_message_unref(reply);
948 dbus_message_unref(m);
951 dbus_message_unref(reply);
953 dbus_error_free(&error);
958 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
959 DBusMessage *m = NULL, *reply = NULL;
964 dbus_error_init(&error);
970 return daemon_reload(bus, args, n);
972 for (i = 1; i < n; i++) {
976 if (!(m = dbus_message_new_method_call(
977 "org.freedesktop.systemd1",
978 "/org/freedesktop/systemd1",
979 "org.freedesktop.systemd1.Manager",
981 log_error("Could not allocate message.");
986 if ((r = safe_atou(args[i], &id)) < 0) {
987 log_error("Failed to parse job id: %s", strerror(-r));
991 assert_cc(sizeof(uint32_t) == sizeof(id));
992 if (!dbus_message_append_args(m,
993 DBUS_TYPE_UINT32, &id,
994 DBUS_TYPE_INVALID)) {
995 log_error("Could not append arguments to message.");
1000 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1001 log_error("Failed to issue method call: %s", bus_error_message(&error));
1006 if (!dbus_message_get_args(reply, &error,
1007 DBUS_TYPE_OBJECT_PATH, &path,
1008 DBUS_TYPE_INVALID)) {
1009 log_error("Failed to parse reply: %s", bus_error_message(&error));
1014 dbus_message_unref(m);
1015 if (!(m = dbus_message_new_method_call(
1016 "org.freedesktop.systemd1",
1018 "org.freedesktop.systemd1.Job",
1020 log_error("Could not allocate message.");
1025 dbus_message_unref(reply);
1026 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1027 log_error("Failed to issue method call: %s", bus_error_message(&error));
1032 dbus_message_unref(m);
1033 dbus_message_unref(reply);
1041 dbus_message_unref(m);
1044 dbus_message_unref(reply);
1046 dbus_error_free(&error);
1051 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1052 DBusMessage *m = NULL, *reply = NULL;
1053 dbus_bool_t b = FALSE;
1054 DBusMessageIter iter, sub;
1056 *interface = "org.freedesktop.systemd1.Unit",
1057 *property = "NeedDaemonReload",
1060 /* We ignore all errors here, since this is used to show a warning only */
1062 if (!(m = dbus_message_new_method_call(
1063 "org.freedesktop.systemd1",
1064 "/org/freedesktop/systemd1",
1065 "org.freedesktop.systemd1.Manager",
1069 if (!dbus_message_append_args(m,
1070 DBUS_TYPE_STRING, &unit,
1074 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1077 if (!dbus_message_get_args(reply, NULL,
1078 DBUS_TYPE_OBJECT_PATH, &path,
1082 dbus_message_unref(m);
1083 if (!(m = dbus_message_new_method_call(
1084 "org.freedesktop.systemd1",
1086 "org.freedesktop.DBus.Properties",
1090 if (!dbus_message_append_args(m,
1091 DBUS_TYPE_STRING, &interface,
1092 DBUS_TYPE_STRING, &property,
1093 DBUS_TYPE_INVALID)) {
1097 dbus_message_unref(reply);
1098 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1101 if (!dbus_message_iter_init(reply, &iter) ||
1102 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1105 dbus_message_iter_recurse(&iter, &sub);
1107 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1110 dbus_message_iter_get_basic(&sub, &b);
1114 dbus_message_unref(m);
1117 dbus_message_unref(reply);
1122 typedef struct WaitData {
1127 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1135 dbus_error_init(&error);
1137 log_debug("Got D-Bus request: %s.%s() on %s",
1138 dbus_message_get_interface(message),
1139 dbus_message_get_member(message),
1140 dbus_message_get_path(message));
1142 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1143 log_error("Warning! D-Bus connection terminated.");
1144 dbus_connection_close(connection);
1146 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1148 const char *path, *result;
1149 dbus_bool_t success = true;
1151 if (dbus_message_get_args(message, &error,
1152 DBUS_TYPE_UINT32, &id,
1153 DBUS_TYPE_OBJECT_PATH, &path,
1154 DBUS_TYPE_STRING, &result,
1155 DBUS_TYPE_INVALID)) {
1158 if ((p = set_remove(d->set, (char*) path)))
1162 d->result = strdup(result);
1167 dbus_error_free(&error);
1169 if (dbus_message_get_args(message, &error,
1170 DBUS_TYPE_UINT32, &id,
1171 DBUS_TYPE_OBJECT_PATH, &path,
1172 DBUS_TYPE_BOOLEAN, &success,
1173 DBUS_TYPE_INVALID)) {
1176 /* Compatibility with older systemd versions <
1177 * 19 during upgrades. This should be dropped
1180 if ((p = set_remove(d->set, (char*) path)))
1184 d->result = strdup("failed");
1190 log_error("Failed to parse message: %s", bus_error_message(&error));
1194 dbus_error_free(&error);
1195 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1198 static int enable_wait_for_jobs(DBusConnection *bus) {
1206 dbus_error_init(&error);
1207 dbus_bus_add_match(bus,
1209 "sender='org.freedesktop.systemd1',"
1210 "interface='org.freedesktop.systemd1.Manager',"
1211 "member='JobRemoved',"
1212 "path='/org/freedesktop/systemd1'",
1215 if (dbus_error_is_set(&error)) {
1216 log_error("Failed to add match: %s", bus_error_message(&error));
1217 dbus_error_free(&error);
1221 /* This is slightly dirty, since we don't undo the match registrations. */
1225 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1235 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1236 log_error("Failed to add filter.");
1241 while (!set_isempty(s) &&
1242 dbus_connection_read_write_dispatch(bus, -1))
1245 if (!arg_quiet && d.result) {
1246 if (streq(d.result, "timeout"))
1247 log_error("Job timed out.");
1248 else if (streq(d.result, "canceled"))
1249 log_error("Job canceled.");
1250 else if (streq(d.result, "dependency"))
1251 log_error("A dependency job failed. See system logs for details.");
1252 else if (!streq(d.result, "done"))
1253 log_error("Job failed. See system logs and 'systemctl status' for details.");
1256 if (streq_ptr(d.result, "timeout"))
1258 else if (streq_ptr(d.result, "canceled"))
1260 else if (!streq_ptr(d.result, "done"))
1268 /* This is slightly dirty, since we don't undo the filter registration. */
1273 static int start_unit_one(
1274 DBusConnection *bus,
1281 DBusMessage *m = NULL, *reply = NULL;
1290 assert(arg_no_block || s);
1292 if (!(m = dbus_message_new_method_call(
1293 "org.freedesktop.systemd1",
1294 "/org/freedesktop/systemd1",
1295 "org.freedesktop.systemd1.Manager",
1297 log_error("Could not allocate message.");
1302 if (!dbus_message_append_args(m,
1303 DBUS_TYPE_STRING, &name,
1304 DBUS_TYPE_STRING, &mode,
1305 DBUS_TYPE_INVALID)) {
1306 log_error("Could not append arguments to message.");
1311 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1313 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1314 /* There's always a fallback possible for
1315 * legacy actions. */
1320 log_error("Failed to issue method call: %s", bus_error_message(error));
1325 if (!dbus_message_get_args(reply, error,
1326 DBUS_TYPE_OBJECT_PATH, &path,
1327 DBUS_TYPE_INVALID)) {
1328 log_error("Failed to parse reply: %s", bus_error_message(error));
1333 if (need_daemon_reload(bus, name))
1334 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1335 arg_user ? "--user" : "--system");
1337 if (!arg_no_block) {
1340 if (!(p = strdup(path))) {
1341 log_error("Failed to duplicate path.");
1346 if ((r = set_put(s, p)) < 0) {
1348 log_error("Failed to add path to set.");
1357 dbus_message_unref(m);
1360 dbus_message_unref(reply);
1365 static enum action verb_to_action(const char *verb) {
1366 if (streq(verb, "halt"))
1368 else if (streq(verb, "poweroff"))
1369 return ACTION_POWEROFF;
1370 else if (streq(verb, "reboot"))
1371 return ACTION_REBOOT;
1372 else if (streq(verb, "kexec"))
1373 return ACTION_KEXEC;
1374 else if (streq(verb, "rescue"))
1375 return ACTION_RESCUE;
1376 else if (streq(verb, "emergency"))
1377 return ACTION_EMERGENCY;
1378 else if (streq(verb, "default"))
1379 return ACTION_DEFAULT;
1380 else if (streq(verb, "exit"))
1383 return ACTION_INVALID;
1386 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1388 static const char * const table[_ACTION_MAX] = {
1389 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1390 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1391 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1392 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1393 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1394 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1395 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1396 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1397 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1398 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1399 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1400 [ACTION_EXIT] = SPECIAL_EXIT_TARGET
1405 const char *method, *mode, *one_name;
1409 dbus_error_init(&error);
1413 spawn_ask_password_agent();
1415 if (arg_action == ACTION_SYSTEMCTL) {
1417 streq(args[0], "stop") ? "StopUnit" :
1418 streq(args[0], "reload") ? "ReloadUnit" :
1419 streq(args[0], "restart") ? "RestartUnit" :
1420 streq(args[0], "try-restart") ||
1421 streq(args[0], "condrestart") ? "TryRestartUnit" :
1422 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1423 streq(args[0], "reload-or-try-restart") ||
1424 streq(args[0], "condreload") ||
1425 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1429 (streq(args[0], "isolate") ||
1430 streq(args[0], "rescue") ||
1431 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1433 one_name = table[verb_to_action(args[0])];
1436 assert(arg_action < ELEMENTSOF(table));
1437 assert(table[arg_action]);
1439 method = "StartUnit";
1441 mode = (arg_action == ACTION_EMERGENCY ||
1442 arg_action == ACTION_RESCUE ||
1443 arg_action == ACTION_RUNLEVEL2 ||
1444 arg_action == ACTION_RUNLEVEL3 ||
1445 arg_action == ACTION_RUNLEVEL4 ||
1446 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1448 one_name = table[arg_action];
1451 if (!arg_no_block) {
1452 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1453 log_error("Could not watch jobs: %s", strerror(-ret));
1457 if (!(s = set_new(string_hash_func, string_compare_func))) {
1458 log_error("Failed to allocate set.");
1465 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1468 for (i = 1; i < n; i++)
1469 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1470 ret = translate_bus_error_to_exit_status(r, &error);
1471 dbus_error_free(&error);
1476 if ((r = wait_for_jobs(bus, s)) < 0) {
1485 dbus_error_free(&error);
1490 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1497 (streq(args[0], "halt") ||
1498 streq(args[0], "poweroff") ||
1499 streq(args[0], "reboot") ||
1500 streq(args[0], "kexec") ||
1501 streq(args[0], "exit")))
1502 return daemon_reload(bus, args, n);
1504 r = start_unit(bus, args, n);
1507 warn_wall(verb_to_action(args[0]));
1512 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1513 DBusMessage *m = NULL, *reply = NULL;
1515 *interface = "org.freedesktop.systemd1.Unit",
1516 *property = "ActiveState";
1517 int r = 3; /* According to LSB: "program is not running" */
1524 dbus_error_init(&error);
1526 for (i = 1; i < n; i++) {
1527 const char *path = NULL;
1529 DBusMessageIter iter, sub;
1531 if (!(m = dbus_message_new_method_call(
1532 "org.freedesktop.systemd1",
1533 "/org/freedesktop/systemd1",
1534 "org.freedesktop.systemd1.Manager",
1536 log_error("Could not allocate message.");
1541 if (!dbus_message_append_args(m,
1542 DBUS_TYPE_STRING, &args[i],
1543 DBUS_TYPE_INVALID)) {
1544 log_error("Could not append arguments to message.");
1549 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1551 /* Hmm, cannot figure out anything about this unit... */
1555 dbus_error_free(&error);
1556 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;
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, &exit_timestamp, true) < 0 ||
1782 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1783 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1784 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1788 i->start_timestamp = (usec_t) start_timestamp;
1789 i->exit_timestamp = (usec_t) exit_timestamp;
1790 i->pid = (pid_t) pid;
1797 typedef struct UnitStatusInfo {
1799 const char *load_state;
1800 const char *active_state;
1801 const char *sub_state;
1803 const char *description;
1804 const char *following;
1807 const char *default_control_group;
1809 usec_t inactive_exit_timestamp;
1810 usec_t active_enter_timestamp;
1811 usec_t active_exit_timestamp;
1812 usec_t inactive_enter_timestamp;
1814 bool need_daemon_reload;
1819 const char *status_text;
1821 #ifdef HAVE_SYSV_COMPAT
1825 usec_t start_timestamp;
1826 usec_t exit_timestamp;
1828 int exit_code, exit_status;
1831 unsigned n_accepted;
1832 unsigned n_connections;
1836 const char *sysfs_path;
1838 /* Mount, Automount */
1844 LIST_HEAD(ExecStatusInfo, exec);
1847 static void print_status_info(UnitStatusInfo *i) {
1849 const char *on, *off, *ss;
1851 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1852 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1856 /* This shows pretty information about a unit. See
1857 * print_property() for a low-level property printer */
1859 printf("%s", strna(i->id));
1861 if (i->description && !streq_ptr(i->id, i->description))
1862 printf(" - %s", i->description);
1867 printf("\t Follow: unit currently follows state of %s\n", i->following);
1869 if (streq_ptr(i->load_state, "failed") ||
1870 streq_ptr(i->load_state, "banned")) {
1871 on = ansi_highlight(true);
1872 off = ansi_highlight(false);
1877 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1879 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1881 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1883 if (streq_ptr(i->active_state, "failed")) {
1884 on = ansi_highlight(true);
1885 off = ansi_highlight(false);
1886 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1887 on = ansi_highlight_green(true);
1888 off = ansi_highlight_green(false);
1893 printf("\t Active: %s%s (%s)%s",
1895 strna(i->active_state),
1899 printf("\t Active: %s%s%s",
1901 strna(i->active_state),
1904 timestamp = (streq_ptr(i->active_state, "active") ||
1905 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1906 (streq_ptr(i->active_state, "inactive") ||
1907 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1908 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1909 i->active_exit_timestamp;
1911 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1912 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1915 printf(" since %s; %s\n", s2, s1);
1917 printf(" since %s\n", s2);
1922 printf("\t Device: %s\n", i->sysfs_path);
1924 printf("\t Where: %s\n", i->where);
1926 printf("\t What: %s\n", i->what);
1929 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1931 LIST_FOREACH(exec, p, i->exec) {
1935 /* Only show exited processes here */
1939 t = strv_join(p->argv, " ");
1940 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
1943 #ifdef HAVE_SYSV_COMPAT
1945 good = is_clean_exit_lsb(p->code, p->status);
1948 good = is_clean_exit(p->code, p->status);
1951 on = ansi_highlight(true);
1952 off = ansi_highlight(false);
1956 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
1958 if (p->code == CLD_EXITED) {
1961 printf("status=%i", p->status);
1963 #ifdef HAVE_SYSV_COMPAT
1964 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1966 if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1971 printf("signal=%s", signal_to_string(p->status));
1973 printf(")%s\n", off);
1977 if (i->main_pid == p->pid &&
1978 i->start_timestamp == p->start_timestamp &&
1979 i->exit_timestamp == p->start_timestamp)
1980 /* Let's not show this twice */
1983 if (p->pid == i->control_pid)
1987 if (i->main_pid > 0 || i->control_pid > 0) {
1990 if (i->main_pid > 0) {
1991 printf("Main PID: %u", (unsigned) i->main_pid);
1995 get_process_name(i->main_pid, &t);
2000 } else if (i->exit_code > 0) {
2001 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2003 if (i->exit_code == CLD_EXITED) {
2006 printf("status=%i", i->exit_status);
2008 #ifdef HAVE_SYSV_COMPAT
2009 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
2011 if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
2016 printf("signal=%s", signal_to_string(i->exit_status));
2021 if (i->main_pid > 0 && i->control_pid > 0)
2024 if (i->control_pid > 0) {
2027 printf(" Control: %u", (unsigned) i->control_pid);
2029 get_process_name(i->control_pid, &t);
2040 printf("\t Status: \"%s\"\n", i->status_text);
2042 if (i->default_control_group) {
2045 printf("\t CGroup: %s\n", i->default_control_group);
2047 if ((c = columns()) > 18)
2052 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
2055 if (i->need_daemon_reload)
2056 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2057 ansi_highlight(true),
2058 ansi_highlight(false),
2059 arg_user ? "--user" : "--system");
2062 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2064 switch (dbus_message_iter_get_arg_type(iter)) {
2066 case DBUS_TYPE_STRING: {
2069 dbus_message_iter_get_basic(iter, &s);
2072 if (streq(name, "Id"))
2074 else if (streq(name, "LoadState"))
2076 else if (streq(name, "ActiveState"))
2077 i->active_state = s;
2078 else if (streq(name, "SubState"))
2080 else if (streq(name, "Description"))
2082 else if (streq(name, "FragmentPath"))
2084 #ifdef HAVE_SYSV_COMPAT
2085 else if (streq(name, "SysVPath")) {
2090 else if (streq(name, "DefaultControlGroup"))
2091 i->default_control_group = s;
2092 else if (streq(name, "StatusText"))
2094 else if (streq(name, "SysFSPath"))
2096 else if (streq(name, "Where"))
2098 else if (streq(name, "What"))
2100 else if (streq(name, "Following"))
2107 case DBUS_TYPE_BOOLEAN: {
2110 dbus_message_iter_get_basic(iter, &b);
2112 if (streq(name, "Accept"))
2114 else if (streq(name, "NeedDaemonReload"))
2115 i->need_daemon_reload = b;
2120 case DBUS_TYPE_UINT32: {
2123 dbus_message_iter_get_basic(iter, &u);
2125 if (streq(name, "MainPID")) {
2127 i->main_pid = (pid_t) u;
2130 } else if (streq(name, "ControlPID"))
2131 i->control_pid = (pid_t) u;
2132 else if (streq(name, "ExecMainPID")) {
2134 i->main_pid = (pid_t) u;
2135 } else if (streq(name, "NAccepted"))
2137 else if (streq(name, "NConnections"))
2138 i->n_connections = u;
2143 case DBUS_TYPE_INT32: {
2146 dbus_message_iter_get_basic(iter, &j);
2148 if (streq(name, "ExecMainCode"))
2149 i->exit_code = (int) j;
2150 else if (streq(name, "ExecMainStatus"))
2151 i->exit_status = (int) j;
2156 case DBUS_TYPE_UINT64: {
2159 dbus_message_iter_get_basic(iter, &u);
2161 if (streq(name, "ExecMainStartTimestamp"))
2162 i->start_timestamp = (usec_t) u;
2163 else if (streq(name, "ExecMainExitTimestamp"))
2164 i->exit_timestamp = (usec_t) u;
2165 else if (streq(name, "ActiveEnterTimestamp"))
2166 i->active_enter_timestamp = (usec_t) u;
2167 else if (streq(name, "InactiveEnterTimestamp"))
2168 i->inactive_enter_timestamp = (usec_t) u;
2169 else if (streq(name, "InactiveExitTimestamp"))
2170 i->inactive_exit_timestamp = (usec_t) u;
2171 else if (streq(name, "ActiveExitTimestamp"))
2172 i->active_exit_timestamp = (usec_t) u;
2177 case DBUS_TYPE_ARRAY: {
2179 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2180 startswith(name, "Exec")) {
2181 DBusMessageIter sub;
2183 dbus_message_iter_recurse(iter, &sub);
2184 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2185 ExecStatusInfo *info;
2188 if (!(info = new0(ExecStatusInfo, 1)))
2191 if (!(info->name = strdup(name))) {
2196 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2201 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2203 dbus_message_iter_next(&sub);
2214 static int print_property(const char *name, DBusMessageIter *iter) {
2218 /* This is a low-level property printer, see
2219 * print_status_info() for the nicer output */
2221 if (arg_property && !strv_find(arg_property, name))
2224 switch (dbus_message_iter_get_arg_type(iter)) {
2226 case DBUS_TYPE_STRING: {
2228 dbus_message_iter_get_basic(iter, &s);
2230 if (arg_all || s[0])
2231 printf("%s=%s\n", name, s);
2236 case DBUS_TYPE_BOOLEAN: {
2238 dbus_message_iter_get_basic(iter, &b);
2239 printf("%s=%s\n", name, yes_no(b));
2244 case DBUS_TYPE_UINT64: {
2246 dbus_message_iter_get_basic(iter, &u);
2248 /* Yes, heuristics! But we can change this check
2249 * should it turn out to not be sufficient */
2251 if (strstr(name, "Timestamp")) {
2252 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
2254 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
2255 printf("%s=%s\n", name, strempty(t));
2256 } else if (strstr(name, "USec")) {
2257 char timespan[FORMAT_TIMESPAN_MAX];
2259 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
2261 printf("%s=%llu\n", name, (unsigned long long) u);
2266 case DBUS_TYPE_UINT32: {
2268 dbus_message_iter_get_basic(iter, &u);
2270 if (strstr(name, "UMask") || strstr(name, "Mode"))
2271 printf("%s=%04o\n", name, u);
2273 printf("%s=%u\n", name, (unsigned) u);
2278 case DBUS_TYPE_INT32: {
2280 dbus_message_iter_get_basic(iter, &i);
2282 printf("%s=%i\n", name, (int) i);
2286 case DBUS_TYPE_DOUBLE: {
2288 dbus_message_iter_get_basic(iter, &d);
2290 printf("%s=%g\n", name, d);
2294 case DBUS_TYPE_STRUCT: {
2295 DBusMessageIter sub;
2296 dbus_message_iter_recurse(iter, &sub);
2298 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2301 dbus_message_iter_get_basic(&sub, &u);
2304 printf("%s=%u\n", name, (unsigned) u);
2306 printf("%s=\n", name);
2309 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2312 dbus_message_iter_get_basic(&sub, &s);
2314 if (arg_all || s[0])
2315 printf("%s=%s\n", name, s);
2323 case DBUS_TYPE_ARRAY:
2325 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2326 DBusMessageIter sub;
2329 dbus_message_iter_recurse(iter, &sub);
2331 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2332 printf("%s=", name);
2334 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2337 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2338 dbus_message_iter_get_basic(&sub, &s);
2339 printf("%s%s", space ? " " : "", s);
2342 dbus_message_iter_next(&sub);
2350 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2351 DBusMessageIter sub;
2353 dbus_message_iter_recurse(iter, &sub);
2355 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2356 printf("%s=", name);
2358 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2361 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2362 dbus_message_iter_get_basic(&sub, &u);
2365 dbus_message_iter_next(&sub);
2373 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2374 DBusMessageIter sub, sub2;
2376 dbus_message_iter_recurse(iter, &sub);
2377 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2378 const char *type, *path;
2380 dbus_message_iter_recurse(&sub, &sub2);
2382 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2383 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2384 printf("%s=%s\n", type, path);
2386 dbus_message_iter_next(&sub);
2391 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2392 DBusMessageIter sub, sub2;
2394 dbus_message_iter_recurse(iter, &sub);
2395 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2397 uint64_t value, next_elapse;
2399 dbus_message_iter_recurse(&sub, &sub2);
2401 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2402 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2403 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2404 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2406 printf("%s={ value=%s ; next_elapse=%s }\n",
2408 format_timespan(timespan1, sizeof(timespan1), value),
2409 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2412 dbus_message_iter_next(&sub);
2417 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2418 DBusMessageIter sub;
2420 dbus_message_iter_recurse(iter, &sub);
2421 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2422 ExecStatusInfo info;
2425 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2426 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2429 t = strv_join(info.argv, " ");
2431 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2435 yes_no(info.ignore),
2436 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2437 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2438 (unsigned) info. pid,
2439 sigchld_code_to_string(info.code),
2441 info.code == CLD_EXITED ? "" : "/",
2442 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2448 strv_free(info.argv);
2450 dbus_message_iter_next(&sub);
2460 printf("%s=[unprintable]\n", name);
2465 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2466 DBusMessage *m = NULL, *reply = NULL;
2467 const char *interface = "";
2470 DBusMessageIter iter, sub, sub2, sub3;
2471 UnitStatusInfo info;
2479 dbus_error_init(&error);
2481 if (!(m = dbus_message_new_method_call(
2482 "org.freedesktop.systemd1",
2484 "org.freedesktop.DBus.Properties",
2486 log_error("Could not allocate message.");
2491 if (!dbus_message_append_args(m,
2492 DBUS_TYPE_STRING, &interface,
2493 DBUS_TYPE_INVALID)) {
2494 log_error("Could not append arguments to message.");
2499 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2500 log_error("Failed to issue method call: %s", bus_error_message(&error));
2505 if (!dbus_message_iter_init(reply, &iter) ||
2506 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2507 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2508 log_error("Failed to parse reply.");
2513 dbus_message_iter_recurse(&iter, &sub);
2520 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2523 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2524 log_error("Failed to parse reply.");
2529 dbus_message_iter_recurse(&sub, &sub2);
2531 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2532 log_error("Failed to parse reply.");
2537 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2538 log_error("Failed to parse reply.");
2543 dbus_message_iter_recurse(&sub2, &sub3);
2545 if (show_properties)
2546 r = print_property(name, &sub3);
2548 r = status_property(name, &sub3, &info);
2551 log_error("Failed to parse reply.");
2556 dbus_message_iter_next(&sub);
2561 if (!show_properties)
2562 print_status_info(&info);
2564 if (!streq_ptr(info.active_state, "active") &&
2565 !streq_ptr(info.active_state, "reloading") &&
2566 streq(verb, "status"))
2567 /* According to LSB: "program not running" */
2570 while ((p = info.exec)) {
2571 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2572 exec_status_info_free(p);
2577 dbus_message_unref(m);
2580 dbus_message_unref(reply);
2582 dbus_error_free(&error);
2587 static int show(DBusConnection *bus, char **args, unsigned n) {
2588 DBusMessage *m = NULL, *reply = NULL;
2592 bool show_properties, new_line = false;
2597 dbus_error_init(&error);
2599 show_properties = !streq(args[0], "status");
2601 if (show_properties)
2604 if (show_properties && n <= 1) {
2605 /* If not argument is specified inspect the manager
2608 ret = show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2612 for (i = 1; i < n; i++) {
2613 const char *path = NULL;
2616 if (safe_atou32(args[i], &id) < 0) {
2618 /* Interpret as unit name */
2620 if (!(m = dbus_message_new_method_call(
2621 "org.freedesktop.systemd1",
2622 "/org/freedesktop/systemd1",
2623 "org.freedesktop.systemd1.Manager",
2625 log_error("Could not allocate message.");
2630 if (!dbus_message_append_args(m,
2631 DBUS_TYPE_STRING, &args[i],
2632 DBUS_TYPE_INVALID)) {
2633 log_error("Could not append arguments to message.");
2638 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2640 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2641 log_error("Failed to issue method call: %s", bus_error_message(&error));
2646 dbus_error_free(&error);
2648 dbus_message_unref(m);
2649 if (!(m = dbus_message_new_method_call(
2650 "org.freedesktop.systemd1",
2651 "/org/freedesktop/systemd1",
2652 "org.freedesktop.systemd1.Manager",
2654 log_error("Could not allocate message.");
2659 if (!dbus_message_append_args(m,
2660 DBUS_TYPE_STRING, &args[i],
2661 DBUS_TYPE_INVALID)) {
2662 log_error("Could not append arguments to message.");
2667 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2668 log_error("Failed to issue method call: %s", bus_error_message(&error));
2670 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2671 ret = 4; /* According to LSB: "program or service status is unknown" */
2678 } else if (show_properties) {
2680 /* Interpret as job id */
2682 if (!(m = dbus_message_new_method_call(
2683 "org.freedesktop.systemd1",
2684 "/org/freedesktop/systemd1",
2685 "org.freedesktop.systemd1.Manager",
2687 log_error("Could not allocate message.");
2692 if (!dbus_message_append_args(m,
2693 DBUS_TYPE_UINT32, &id,
2694 DBUS_TYPE_INVALID)) {
2695 log_error("Could not append arguments to message.");
2700 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2701 log_error("Failed to issue method call: %s", bus_error_message(&error));
2707 /* Interpret as PID */
2709 if (!(m = dbus_message_new_method_call(
2710 "org.freedesktop.systemd1",
2711 "/org/freedesktop/systemd1",
2712 "org.freedesktop.systemd1.Manager",
2714 log_error("Could not allocate message.");
2719 if (!dbus_message_append_args(m,
2720 DBUS_TYPE_UINT32, &id,
2721 DBUS_TYPE_INVALID)) {
2722 log_error("Could not append arguments to message.");
2727 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2728 log_error("Failed to issue method call: %s", bus_error_message(&error));
2734 if (!dbus_message_get_args(reply, &error,
2735 DBUS_TYPE_OBJECT_PATH, &path,
2736 DBUS_TYPE_INVALID)) {
2737 log_error("Failed to parse reply: %s", bus_error_message(&error));
2742 if ((r = show_one(args[0], bus, path, show_properties, &new_line)) != 0)
2745 dbus_message_unref(m);
2746 dbus_message_unref(reply);
2752 dbus_message_unref(m);
2755 dbus_message_unref(reply);
2757 dbus_error_free(&error);
2762 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2764 DBusMessage *m = NULL, *reply = NULL;
2769 dbus_error_init(&error);
2771 log_debug("Got D-Bus request: %s.%s() on %s",
2772 dbus_message_get_interface(message),
2773 dbus_message_get_member(message),
2774 dbus_message_get_path(message));
2776 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2777 log_error("Warning! D-Bus connection terminated.");
2778 dbus_connection_close(connection);
2780 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2781 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2782 const char *id, *path;
2784 if (!dbus_message_get_args(message, &error,
2785 DBUS_TYPE_STRING, &id,
2786 DBUS_TYPE_OBJECT_PATH, &path,
2788 log_error("Failed to parse message: %s", bus_error_message(&error));
2789 else if (streq(dbus_message_get_member(message), "UnitNew"))
2790 printf("Unit %s added.\n", id);
2792 printf("Unit %s removed.\n", id);
2794 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2795 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2797 const char *path, *result;
2799 if (!dbus_message_get_args(message, &error,
2800 DBUS_TYPE_UINT32, &id,
2801 DBUS_TYPE_OBJECT_PATH, &path,
2802 DBUS_TYPE_STRING, &result,
2804 log_error("Failed to parse message: %s", bus_error_message(&error));
2805 else if (streq(dbus_message_get_member(message), "JobNew"))
2806 printf("Job %u added.\n", id);
2808 printf("Job %u removed.\n", id);
2811 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2813 const char *path, *interface, *property = "Id";
2814 DBusMessageIter iter, sub;
2816 path = dbus_message_get_path(message);
2818 if (!dbus_message_get_args(message, &error,
2819 DBUS_TYPE_STRING, &interface,
2820 DBUS_TYPE_INVALID)) {
2821 log_error("Failed to parse message: %s", bus_error_message(&error));
2825 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2826 !streq(interface, "org.freedesktop.systemd1.Unit"))
2829 if (!(m = dbus_message_new_method_call(
2830 "org.freedesktop.systemd1",
2832 "org.freedesktop.DBus.Properties",
2834 log_error("Could not allocate message.");
2838 if (!dbus_message_append_args(m,
2839 DBUS_TYPE_STRING, &interface,
2840 DBUS_TYPE_STRING, &property,
2841 DBUS_TYPE_INVALID)) {
2842 log_error("Could not append arguments to message.");
2846 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2847 log_error("Failed to issue method call: %s", bus_error_message(&error));
2851 if (!dbus_message_iter_init(reply, &iter) ||
2852 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2853 log_error("Failed to parse reply.");
2857 dbus_message_iter_recurse(&iter, &sub);
2859 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2862 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2863 log_error("Failed to parse reply.");
2867 dbus_message_iter_get_basic(&sub, &id);
2868 printf("Unit %s changed.\n", id);
2872 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2873 log_error("Failed to parse reply.");
2877 dbus_message_iter_get_basic(&sub, &id);
2878 printf("Job %u changed.\n", id);
2884 dbus_message_unref(m);
2887 dbus_message_unref(reply);
2889 dbus_error_free(&error);
2890 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2894 dbus_message_unref(m);
2897 dbus_message_unref(reply);
2899 dbus_error_free(&error);
2900 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2903 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2904 DBusMessage *m = NULL, *reply = NULL;
2908 dbus_error_init(&error);
2911 dbus_bus_add_match(bus,
2913 "sender='org.freedesktop.systemd1',"
2914 "interface='org.freedesktop.systemd1.Manager',"
2915 "path='/org/freedesktop/systemd1'",
2918 if (dbus_error_is_set(&error)) {
2919 log_error("Failed to add match: %s", bus_error_message(&error));
2924 dbus_bus_add_match(bus,
2926 "sender='org.freedesktop.systemd1',"
2927 "interface='org.freedesktop.DBus.Properties',"
2928 "member='PropertiesChanged'",
2931 if (dbus_error_is_set(&error)) {
2932 log_error("Failed to add match: %s", bus_error_message(&error));
2938 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2939 log_error("Failed to add filter.");
2944 if (!(m = dbus_message_new_method_call(
2945 "org.freedesktop.systemd1",
2946 "/org/freedesktop/systemd1",
2947 "org.freedesktop.systemd1.Manager",
2949 log_error("Could not allocate message.");
2954 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2955 log_error("Failed to issue method call: %s", bus_error_message(&error));
2960 while (dbus_connection_read_write_dispatch(bus, -1))
2967 /* This is slightly dirty, since we don't undo the filter or the matches. */
2970 dbus_message_unref(m);
2973 dbus_message_unref(reply);
2975 dbus_error_free(&error);
2980 static int dump(DBusConnection *bus, char **args, unsigned n) {
2981 DBusMessage *m = NULL, *reply = NULL;
2986 dbus_error_init(&error);
2990 if (!(m = dbus_message_new_method_call(
2991 "org.freedesktop.systemd1",
2992 "/org/freedesktop/systemd1",
2993 "org.freedesktop.systemd1.Manager",
2995 log_error("Could not allocate message.");
2999 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3000 log_error("Failed to issue method call: %s", bus_error_message(&error));
3005 if (!dbus_message_get_args(reply, &error,
3006 DBUS_TYPE_STRING, &text,
3007 DBUS_TYPE_INVALID)) {
3008 log_error("Failed to parse reply: %s", bus_error_message(&error));
3013 fputs(text, stdout);
3019 dbus_message_unref(m);
3022 dbus_message_unref(reply);
3024 dbus_error_free(&error);
3029 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
3030 DBusMessage *m = NULL, *reply = NULL;
3033 const char *name = "", *path, *id;
3034 dbus_bool_t cleanup = FALSE;
3035 DBusMessageIter iter, sub;
3037 *interface = "org.freedesktop.systemd1.Unit",
3040 dbus_error_init(&error);
3042 if (!(m = dbus_message_new_method_call(
3043 "org.freedesktop.systemd1",
3044 "/org/freedesktop/systemd1",
3045 "org.freedesktop.systemd1.Manager",
3046 "CreateSnapshot"))) {
3047 log_error("Could not allocate message.");
3054 if (!dbus_message_append_args(m,
3055 DBUS_TYPE_STRING, &name,
3056 DBUS_TYPE_BOOLEAN, &cleanup,
3057 DBUS_TYPE_INVALID)) {
3058 log_error("Could not append arguments to message.");
3063 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3064 log_error("Failed to issue method call: %s", bus_error_message(&error));
3069 if (!dbus_message_get_args(reply, &error,
3070 DBUS_TYPE_OBJECT_PATH, &path,
3071 DBUS_TYPE_INVALID)) {
3072 log_error("Failed to parse reply: %s", bus_error_message(&error));
3077 dbus_message_unref(m);
3078 if (!(m = dbus_message_new_method_call(
3079 "org.freedesktop.systemd1",
3081 "org.freedesktop.DBus.Properties",
3083 log_error("Could not allocate message.");
3087 if (!dbus_message_append_args(m,
3088 DBUS_TYPE_STRING, &interface,
3089 DBUS_TYPE_STRING, &property,
3090 DBUS_TYPE_INVALID)) {
3091 log_error("Could not append arguments to message.");
3096 dbus_message_unref(reply);
3097 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3098 log_error("Failed to issue method call: %s", bus_error_message(&error));
3103 if (!dbus_message_iter_init(reply, &iter) ||
3104 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3105 log_error("Failed to parse reply.");
3110 dbus_message_iter_recurse(&iter, &sub);
3112 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3113 log_error("Failed to parse reply.");
3118 dbus_message_iter_get_basic(&sub, &id);
3126 dbus_message_unref(m);
3129 dbus_message_unref(reply);
3131 dbus_error_free(&error);
3136 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
3137 DBusMessage *m = NULL, *reply = NULL;
3145 dbus_error_init(&error);
3147 for (i = 1; i < n; i++) {
3148 const char *path = NULL;
3150 if (!(m = dbus_message_new_method_call(
3151 "org.freedesktop.systemd1",
3152 "/org/freedesktop/systemd1",
3153 "org.freedesktop.systemd1.Manager",
3155 log_error("Could not allocate message.");
3160 if (!dbus_message_append_args(m,
3161 DBUS_TYPE_STRING, &args[i],
3162 DBUS_TYPE_INVALID)) {
3163 log_error("Could not append arguments to message.");
3168 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3169 log_error("Failed to issue method call: %s", bus_error_message(&error));
3174 if (!dbus_message_get_args(reply, &error,
3175 DBUS_TYPE_OBJECT_PATH, &path,
3176 DBUS_TYPE_INVALID)) {
3177 log_error("Failed to parse reply: %s", bus_error_message(&error));
3182 dbus_message_unref(m);
3183 if (!(m = dbus_message_new_method_call(
3184 "org.freedesktop.systemd1",
3186 "org.freedesktop.systemd1.Snapshot",
3188 log_error("Could not allocate message.");
3193 dbus_message_unref(reply);
3194 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3195 log_error("Failed to issue method call: %s", bus_error_message(&error));
3200 dbus_message_unref(m);
3201 dbus_message_unref(reply);
3209 dbus_message_unref(m);
3212 dbus_message_unref(reply);
3214 dbus_error_free(&error);
3219 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
3220 DBusMessage *m = NULL, *reply = NULL;
3225 dbus_error_init(&error);
3227 if (arg_action == ACTION_RELOAD)
3229 else if (arg_action == ACTION_REEXEC)
3230 method = "Reexecute";
3232 assert(arg_action == ACTION_SYSTEMCTL);
3235 streq(args[0], "clear-jobs") ||
3236 streq(args[0], "cancel") ? "ClearJobs" :
3237 streq(args[0], "daemon-reexec") ? "Reexecute" :
3238 streq(args[0], "reset-failed") ? "ResetFailed" :
3239 streq(args[0], "halt") ? "Halt" :
3240 streq(args[0], "poweroff") ? "PowerOff" :
3241 streq(args[0], "reboot") ? "Reboot" :
3242 streq(args[0], "kexec") ? "KExec" :
3243 streq(args[0], "exit") ? "Exit" :
3244 /* "daemon-reload" */ "Reload";
3247 if (!(m = dbus_message_new_method_call(
3248 "org.freedesktop.systemd1",
3249 "/org/freedesktop/systemd1",
3250 "org.freedesktop.systemd1.Manager",
3252 log_error("Could not allocate message.");
3256 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3258 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3259 /* There's always a fallback possible for
3260 * legacy actions. */
3265 log_error("Failed to issue method call: %s", bus_error_message(&error));
3274 dbus_message_unref(m);
3277 dbus_message_unref(reply);
3279 dbus_error_free(&error);
3284 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3285 DBusMessage *m = NULL, *reply = NULL;
3291 dbus_error_init(&error);
3294 return daemon_reload(bus, args, n);
3296 for (i = 1; i < n; i++) {
3298 if (!(m = dbus_message_new_method_call(
3299 "org.freedesktop.systemd1",
3300 "/org/freedesktop/systemd1",
3301 "org.freedesktop.systemd1.Manager",
3302 "ResetFailedUnit"))) {
3303 log_error("Could not allocate message.");
3308 if (!dbus_message_append_args(m,
3309 DBUS_TYPE_STRING, args + i,
3310 DBUS_TYPE_INVALID)) {
3311 log_error("Could not append arguments to message.");
3316 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3317 log_error("Failed to issue method call: %s", bus_error_message(&error));
3322 dbus_message_unref(m);
3323 dbus_message_unref(reply);
3331 dbus_message_unref(m);
3334 dbus_message_unref(reply);
3336 dbus_error_free(&error);
3341 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3342 DBusMessage *m = NULL, *reply = NULL;
3344 DBusMessageIter iter, sub, sub2;
3347 *interface = "org.freedesktop.systemd1.Manager",
3348 *property = "Environment";
3350 dbus_error_init(&error);
3354 if (!(m = dbus_message_new_method_call(
3355 "org.freedesktop.systemd1",
3356 "/org/freedesktop/systemd1",
3357 "org.freedesktop.DBus.Properties",
3359 log_error("Could not allocate message.");
3363 if (!dbus_message_append_args(m,
3364 DBUS_TYPE_STRING, &interface,
3365 DBUS_TYPE_STRING, &property,
3366 DBUS_TYPE_INVALID)) {
3367 log_error("Could not append arguments to message.");
3372 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3373 log_error("Failed to issue method call: %s", bus_error_message(&error));
3378 if (!dbus_message_iter_init(reply, &iter) ||
3379 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3380 log_error("Failed to parse reply.");
3385 dbus_message_iter_recurse(&iter, &sub);
3387 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3388 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3389 log_error("Failed to parse reply.");
3394 dbus_message_iter_recurse(&sub, &sub2);
3396 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3399 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3400 log_error("Failed to parse reply.");
3405 dbus_message_iter_get_basic(&sub2, &text);
3406 printf("%s\n", text);
3408 dbus_message_iter_next(&sub2);
3415 dbus_message_unref(m);
3418 dbus_message_unref(reply);
3420 dbus_error_free(&error);
3425 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3426 DBusMessage *m = NULL, *reply = NULL;
3430 DBusMessageIter iter, sub;
3433 dbus_error_init(&error);
3435 method = streq(args[0], "set-environment")
3437 : "UnsetEnvironment";
3439 if (!(m = dbus_message_new_method_call(
3440 "org.freedesktop.systemd1",
3441 "/org/freedesktop/systemd1",
3442 "org.freedesktop.systemd1.Manager",
3445 log_error("Could not allocate message.");
3449 dbus_message_iter_init_append(m, &iter);
3451 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3452 log_error("Could not append arguments to message.");
3457 for (i = 1; i < n; i++)
3458 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3459 log_error("Could not append arguments to message.");
3464 if (!dbus_message_iter_close_container(&iter, &sub)) {
3465 log_error("Could not append arguments to message.");
3470 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3471 log_error("Failed to issue method call: %s", bus_error_message(&error));
3480 dbus_message_unref(m);
3483 dbus_message_unref(reply);
3485 dbus_error_free(&error);
3498 static Hashmap *will_install = NULL, *have_installed = NULL;
3499 static Set *remove_symlinks_to = NULL;
3500 static unsigned n_symlinks = 0;
3502 static void install_info_free(InstallInfo *i) {
3507 strv_free(i->aliases);
3508 strv_free(i->wanted_by);
3512 static void install_info_hashmap_free(Hashmap *m) {
3515 while ((i = hashmap_steal_first(m)))
3516 install_info_free(i);
3521 static int install_info_add(const char *name) {
3525 assert(will_install);
3527 if (!unit_name_is_valid_no_type(name, true)) {
3528 log_warning("Unit name %s is not a valid unit name.", name);
3532 if (hashmap_get(have_installed, name) ||
3533 hashmap_get(will_install, name))
3536 if (!(i = new0(InstallInfo, 1))) {
3541 if (!(i->name = strdup(name))) {
3546 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3553 install_info_free(i);
3558 static int config_parse_also(
3559 const char *filename,
3561 const char *section,
3575 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3579 if (!(n = strndup(w, l)))
3582 if ((r = install_info_add(n)) < 0) {
3583 log_warning("Cannot install unit %s: %s", n, strerror(-r));
3594 static int mark_symlink_for_removal(const char *p) {
3599 assert(path_is_absolute(p));
3601 if (!remove_symlinks_to)
3604 if (!(n = strdup(p)))
3607 path_kill_slashes(n);
3609 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3611 return r == -EEXIST ? 0 : r;
3617 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3626 if (!(d = fdopendir(fd))) {
3627 close_nointr_nofail(fd);
3633 while ((de = readdir(d))) {
3634 bool is_dir = false, is_link = false;
3636 if (ignore_file(de->d_name))
3639 if (de->d_type == DT_LNK)
3641 else if (de->d_type == DT_DIR)
3643 else if (de->d_type == DT_UNKNOWN) {
3646 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3647 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3654 is_link = S_ISLNK(st.st_mode);
3655 is_dir = S_ISDIR(st.st_mode);
3663 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3664 log_error("Failed to open %s/%s: %m", root, de->d_name);
3671 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3672 log_error("Failed to allocate directory string.");
3673 close_nointr_nofail(nfd);
3678 /* This will close nfd, regardless whether it succeeds or not */
3679 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3685 } else if (is_link) {
3689 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3690 log_error("Failed to allocate symlink string.");
3695 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3696 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3704 if ((c = canonicalize_file_name(dest))) {
3705 /* This might fail if the destination
3706 * is already removed */
3712 path_kill_slashes(dest);
3713 if (set_get(remove_symlinks_to, dest)) {
3716 log_info("rm '%s'", p);
3718 if (unlink(p) < 0) {
3719 log_error("Cannot unlink symlink %s: %m", p);
3724 rmdir_parents(p, config_path);
3725 path_kill_slashes(p);
3727 if (!set_get(remove_symlinks_to, p)) {
3729 if ((r = mark_symlink_for_removal(p)) < 0) {
3748 static int remove_marked_symlinks(const char *config_path) {
3752 assert(config_path);
3754 if (set_size(remove_symlinks_to) <= 0)
3757 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3764 if ((cfd = dup(fd)) < 0) {
3769 /* This takes possession of cfd and closes it */
3770 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3776 close_nointr_nofail(fd);
3781 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3788 if (streq(verb, "enable")) {
3791 mkdir_parents(new_path, 0755);
3793 if (symlink(old_path, new_path) >= 0) {
3796 log_info("ln -s '%s' '%s'", old_path, new_path);
3801 if (errno != EEXIST) {
3802 log_error("Cannot link %s to %s: %m", old_path, new_path);
3806 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3808 if (errno == EINVAL) {
3809 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3813 log_error("readlink() failed: %s", strerror(-r));
3817 if (streq(dest, old_path)) {
3823 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3832 log_info("ln -s '%s' '%s'", old_path, new_path);
3834 if (symlink(old_path, new_path) >= 0)
3837 log_error("Cannot link %s to %s: %m", old_path, new_path);
3840 } else if (streq(verb, "disable")) {
3843 if ((r = mark_symlink_for_removal(old_path)) < 0)
3846 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3847 if (errno == ENOENT)
3850 if (errno == EINVAL) {
3851 log_warning("File %s not a symlink, ignoring.", old_path);
3855 log_error("readlink() failed: %s", strerror(-r));
3859 if (!streq(dest, old_path)) {
3860 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3867 if ((r = mark_symlink_for_removal(new_path)) < 0)
3871 log_info("rm '%s'", new_path);
3873 if (unlink(new_path) >= 0)
3876 log_error("Cannot unlink %s: %m", new_path);
3879 } else if (streq(verb, "is-enabled")) {
3882 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3884 if (errno == ENOENT || errno == EINVAL)
3887 log_error("readlink() failed: %s", strerror(-r));
3891 if (streq(dest, old_path)) {
3899 assert_not_reached("Unknown action.");
3902 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3904 char *alias_path = NULL;
3909 assert(config_path);
3911 STRV_FOREACH(s, i->aliases) {
3914 if (!(alias_path = path_make_absolute(*s, config_path))) {
3915 log_error("Out of memory");
3920 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3923 if (streq(verb, "disable"))
3924 rmdir_parents(alias_path, config_path);
3934 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3936 char *alias_path = NULL;
3941 assert(config_path);
3943 STRV_FOREACH(s, i->wanted_by) {
3944 if (!unit_name_is_valid_no_type(*s, true)) {
3945 log_error("Invalid name %s.", *s);
3953 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3954 log_error("Out of memory");
3959 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3962 if (streq(verb, "disable"))
3963 rmdir_parents(alias_path, config_path);
3974 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3976 const ConfigItem items[] = {
3977 { "Alias", config_parse_strv, &i->aliases, "Install" },
3978 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3979 { "Also", config_parse_also, NULL, "Install" },
3981 { NULL, NULL, NULL, NULL }
3985 char *filename = NULL;
3992 STRV_FOREACH(p, paths->unit_path) {
3995 if (!(filename = path_make_absolute(i->name, *p))) {
3996 log_error("Out of memory");
4000 /* Ensure that we don't follow symlinks */
4001 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
4002 if ((f = fdopen(fd, "re")))
4005 if (errno == ELOOP) {
4006 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
4011 if (errno != ENOENT) {
4012 log_error("Failed to open %s: %m", filename);
4022 #if defined(TARGET_FEDORA) && defined (HAVE_SYSV_COMPAT)
4024 if (endswith(i->name, ".service")) {
4028 if (asprintf(&sysv, SYSTEM_SYSVINIT_PATH "/%s", i->name) < 0) {
4029 log_error("Out of memory");
4033 sysv[strlen(sysv) - sizeof(".service") + 1] = 0;
4034 exists = access(sysv, F_OK) >= 0;
4040 const char *argv[] = {
4047 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", i->name);
4049 argv[1] = file_name_from_path(sysv);
4051 streq(verb, "enable") ? "on" :
4052 streq(verb, "disable") ? "off" : NULL;
4054 log_info("Executing %s %s %s", argv[0], argv[1], strempty(argv[2]));
4056 if ((pid = fork()) < 0) {
4057 log_error("Failed to fork: %m");
4060 } else if (pid == 0) {
4061 execv(argv[0], (char**) argv);
4062 _exit(EXIT_FAILURE);
4067 if ((r = wait_for_terminate(pid, &status)) < 0)
4070 if (status.si_code == CLD_EXITED) {
4071 if (status.si_status == 0 && (streq(verb, "enable") || streq(verb, "disable")))
4074 return status.si_status == 0 ? 0 : -EINVAL;
4084 log_error("Couldn't find %s.", i->name);
4090 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
4095 n_symlinks += strv_length(i->aliases);
4096 n_symlinks += strv_length(i->wanted_by);
4100 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
4103 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
4106 if ((r = mark_symlink_for_removal(filename)) < 0)
4109 if ((r = remove_marked_symlinks(config_path)) < 0)
4115 static char *get_config_path(void) {
4117 if (arg_user && arg_global)
4118 return strdup(USER_CONFIG_UNIT_PATH);
4123 if (user_config_home(&p) < 0)
4129 return strdup(SYSTEM_CONFIG_UNIT_PATH);
4132 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
4136 char *config_path = NULL;
4139 const char *verb = args[0];
4141 dbus_error_init(&error);
4144 if ((r = lookup_paths_init(&paths, arg_user ? MANAGER_USER : MANAGER_SYSTEM)) < 0) {
4145 log_error("Failed to determine lookup paths: %s", strerror(-r));
4149 if (!(config_path = get_config_path())) {
4150 log_error("Failed to determine config path");
4155 will_install = hashmap_new(string_hash_func, string_compare_func);
4156 have_installed = hashmap_new(string_hash_func, string_compare_func);
4158 if (!will_install || !have_installed) {
4159 log_error("Failed to allocate unit sets.");
4164 if (!arg_defaults && streq(verb, "disable"))
4165 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
4166 log_error("Failed to allocate symlink sets.");
4171 for (j = 1; j < n; j++)
4172 if ((r = install_info_add(args[j])) < 0) {
4173 log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
4177 while ((i = hashmap_first(will_install))) {
4180 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
4182 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
4190 /* In test mode and found something */
4196 if (streq(verb, "is-enabled"))
4197 r = r > 0 ? 0 : -ENOENT;
4199 if (n_symlinks <= 0)
4200 log_warning("Unit files contain no applicable installation information. Ignoring.");
4203 /* Don't try to reload anything if the user asked us to not do this */
4205 /* Don't try to reload anything when updating a unit globally */
4207 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
4208 (arg_user || sd_booted() > 0) &&
4209 /* Don't try to reload anything if we are running in a chroot environment */
4210 (arg_user || running_in_chroot() <= 0) ) {
4213 if ((q = daemon_reload(bus, args, n)) < 0)
4219 install_info_hashmap_free(will_install);
4220 install_info_hashmap_free(have_installed);
4222 set_free_free(remove_symlinks_to);
4224 lookup_paths_free(&paths);
4231 static int systemctl_help(void) {
4233 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4234 "Send control commands to or query the systemd manager.\n\n"
4235 " -h --help Show this help\n"
4236 " --version Show package version\n"
4237 " -t --type=TYPE List only units of a particular type\n"
4238 " -p --property=NAME Show only properties by this name\n"
4239 " -a --all Show all units/properties, including dead/empty ones\n"
4240 " --failed Show only failed units\n"
4241 " --full Don't ellipsize unit names on output\n"
4242 " --fail When queueing a new job, fail if conflicting jobs are\n"
4244 " --ignore-dependencies\n"
4245 " When queueing a new job, ignore all its dependencies\n"
4246 " -q --quiet Suppress output\n"
4247 " --no-block Do not wait until operation finished\n"
4248 " --no-pager Do not pipe output into a pager.\n"
4249 " --system Connect to system manager\n"
4250 " --user Connect to user service manager\n"
4251 " --order When generating graph for dot, show only order\n"
4252 " --require When generating graph for dot, show only requirement\n"
4253 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4254 " --global Enable/disable unit files globally\n"
4255 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4257 " --no-ask-password\n"
4258 " Do not ask for system passwords\n"
4259 " --kill-mode=MODE How to send signal\n"
4260 " --kill-who=WHO Who to send signal to\n"
4261 " -s --signal=SIGNAL Which signal to send\n"
4262 " -f --force When enabling unit files, override existing symlinks\n"
4263 " When shutting down, execute action immediately\n"
4264 " --defaults When disabling unit files, remove default symlinks only\n\n"
4266 " list-units List units\n"
4267 " start [NAME...] Start (activate) one or more units\n"
4268 " stop [NAME...] Stop (deactivate) one or more units\n"
4269 " reload [NAME...] Reload one or more units\n"
4270 " restart [NAME...] Start or restart one or more units\n"
4271 " try-restart [NAME...] Restart one or more units if active\n"
4272 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4273 " otherwise start or restart\n"
4274 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4275 " otherwise restart if active\n"
4276 " isolate [NAME] Start one unit and stop all others\n"
4277 " kill [NAME...] Send signal to processes of a unit\n"
4278 " is-active [NAME...] Check whether units are active\n"
4279 " status [NAME...|PID...] Show runtime status of one or more units\n"
4280 " show [NAME...|JOB...] Show properties of one or more\n"
4281 " units/jobs or the manager\n"
4282 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4284 " enable [NAME...] Enable one or more unit files\n"
4285 " disable [NAME...] Disable one or more unit files\n"
4286 " is-enabled [NAME...] Check whether unit files are enabled\n"
4287 " load [NAME...] Load one or more units\n"
4288 " list-jobs List jobs\n"
4289 " cancel [JOB...] Cancel all, one, or more jobs\n"
4290 " monitor Monitor unit/job changes\n"
4291 " dump Dump server status\n"
4292 " dot Dump dependency graph for dot(1)\n"
4293 " snapshot [NAME] Create a snapshot\n"
4294 " delete [NAME...] Remove one or more snapshots\n"
4295 " daemon-reload Reload systemd manager configuration\n"
4296 " daemon-reexec Reexecute systemd manager\n"
4297 " show-environment Dump environment\n"
4298 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4299 " unset-environment [NAME...] Unset one or more environment variables\n"
4300 " default Enter system default mode\n"
4301 " rescue Enter system rescue mode\n"
4302 " emergency Enter system emergency mode\n"
4303 " halt Shut down and halt the system\n"
4304 " poweroff Shut down and power-off the system\n"
4305 " reboot Shut down and reboot the system\n"
4306 " kexec Shut down and reboot the system with kexec\n"
4307 " exit Ask for user instance termination\n",
4308 program_invocation_short_name);
4313 static int halt_help(void) {
4315 printf("%s [OPTIONS...]\n\n"
4316 "%s the system.\n\n"
4317 " --help Show this help\n"
4318 " --halt Halt the machine\n"
4319 " -p --poweroff Switch off the machine\n"
4320 " --reboot Reboot the machine\n"
4321 " -f --force Force immediate halt/power-off/reboot\n"
4322 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4323 " -d --no-wtmp Don't write wtmp record\n"
4324 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4325 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4326 program_invocation_short_name,
4327 arg_action == ACTION_REBOOT ? "Reboot" :
4328 arg_action == ACTION_POWEROFF ? "Power off" :
4334 static int shutdown_help(void) {
4336 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4337 "Shut down the system.\n\n"
4338 " --help Show this help\n"
4339 " -H --halt Halt the machine\n"
4340 " -P --poweroff Power-off the machine\n"
4341 " -r --reboot Reboot the machine\n"
4342 " -h Equivalent to --poweroff, overriden by --halt\n"
4343 " -k Don't halt/power-off/reboot, just send warnings\n"
4344 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4345 " -c Cancel a pending shutdown\n",
4346 program_invocation_short_name);
4351 static int telinit_help(void) {
4353 printf("%s [OPTIONS...] {COMMAND}\n\n"
4354 "Send control commands to the init daemon.\n\n"
4355 " --help Show this help\n"
4356 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4358 " 0 Power-off the machine\n"
4359 " 6 Reboot the machine\n"
4360 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4361 " 1, s, S Enter rescue mode\n"
4362 " q, Q Reload init daemon configuration\n"
4363 " u, U Reexecute init daemon\n",
4364 program_invocation_short_name);
4369 static int runlevel_help(void) {
4371 printf("%s [OPTIONS...]\n\n"
4372 "Prints the previous and current runlevel of the init system.\n\n"
4373 " --help Show this help\n",
4374 program_invocation_short_name);
4379 static int systemctl_parse_argv(int argc, char *argv[]) {
4383 ARG_IGNORE_DEPENDENCIES,
4398 ARG_NO_ASK_PASSWORD,
4402 static const struct option options[] = {
4403 { "help", no_argument, NULL, 'h' },
4404 { "version", no_argument, NULL, ARG_VERSION },
4405 { "type", required_argument, NULL, 't' },
4406 { "property", required_argument, NULL, 'p' },
4407 { "all", no_argument, NULL, 'a' },
4408 { "failed", no_argument, NULL, ARG_FAILED },
4409 { "full", no_argument, NULL, ARG_FULL },
4410 { "fail", no_argument, NULL, ARG_FAIL },
4411 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4412 { "user", no_argument, NULL, ARG_USER },
4413 { "system", no_argument, NULL, ARG_SYSTEM },
4414 { "global", no_argument, NULL, ARG_GLOBAL },
4415 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4416 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4417 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4418 { "quiet", no_argument, NULL, 'q' },
4419 { "order", no_argument, NULL, ARG_ORDER },
4420 { "require", no_argument, NULL, ARG_REQUIRE },
4421 { "force", no_argument, NULL, 'f' },
4422 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4423 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4424 { "kill-mode", required_argument, NULL, ARG_KILL_MODE },
4425 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4426 { "signal", required_argument, NULL, 's' },
4427 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4428 { NULL, 0, NULL, 0 }
4436 /* Only when running as systemctl we ask for passwords */
4437 arg_ask_password = true;
4439 while ((c = getopt_long(argc, argv, "ht:p:aqfs:", options, NULL)) >= 0) {
4448 puts(PACKAGE_STRING);
4450 puts(SYSTEMD_FEATURES);
4460 if (!(l = strv_append(arg_property, optarg)))
4463 strv_free(arg_property);
4466 /* If the user asked for a particular
4467 * property, show it to him, even if it is
4478 arg_job_mode = "fail";
4481 case ARG_IGNORE_DEPENDENCIES:
4482 arg_job_mode = "ignore-dependencies";
4494 arg_no_block = true;
4498 arg_no_pager = true;
4506 arg_dot = DOT_ORDER;
4510 arg_dot = DOT_REQUIRE;
4530 arg_no_reload = true;
4539 arg_defaults = true;
4543 arg_kill_who = optarg;
4547 arg_kill_mode = optarg;
4551 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4552 log_error("Failed to parse signal string %s.", optarg);
4557 case ARG_NO_ASK_PASSWORD:
4558 arg_ask_password = false;
4565 log_error("Unknown option code %c", c);
4573 static int halt_parse_argv(int argc, char *argv[]) {
4582 static const struct option options[] = {
4583 { "help", no_argument, NULL, ARG_HELP },
4584 { "halt", no_argument, NULL, ARG_HALT },
4585 { "poweroff", no_argument, NULL, 'p' },
4586 { "reboot", no_argument, NULL, ARG_REBOOT },
4587 { "force", no_argument, NULL, 'f' },
4588 { "wtmp-only", no_argument, NULL, 'w' },
4589 { "no-wtmp", no_argument, NULL, 'd' },
4590 { "no-sync", no_argument, NULL, 'n' },
4591 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4592 { NULL, 0, NULL, 0 }
4600 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4601 if (runlevel == '0' || runlevel == '6')
4602 arg_immediate = true;
4604 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4612 arg_action = ACTION_HALT;
4616 if (arg_action != ACTION_REBOOT)
4617 arg_action = ACTION_POWEROFF;
4621 arg_action = ACTION_REBOOT;
4625 arg_immediate = true;
4646 /* Compatibility nops */
4653 log_error("Unknown option code %c", c);
4658 if (optind < argc) {
4659 log_error("Too many arguments.");
4666 static int parse_time_spec(const char *t, usec_t *_u) {
4670 if (streq(t, "now"))
4672 else if (t[0] == '+') {
4675 if (safe_atou64(t + 1, &u) < 0)
4678 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4687 hour = strtol(t, &e, 10);
4688 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4691 minute = strtol(e+1, &e, 10);
4692 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4695 n = now(CLOCK_REALTIME);
4696 s = (time_t) (n / USEC_PER_SEC);
4699 assert_se(localtime_r(&s, &tm));
4701 tm.tm_hour = (int) hour;
4702 tm.tm_min = (int) minute;
4705 assert_se(s = mktime(&tm));
4707 *_u = (usec_t) s * USEC_PER_SEC;
4710 *_u += USEC_PER_DAY;
4716 static bool kexec_loaded(void) {
4717 bool loaded = false;
4720 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4728 static int shutdown_parse_argv(int argc, char *argv[]) {
4735 static const struct option options[] = {
4736 { "help", no_argument, NULL, ARG_HELP },
4737 { "halt", no_argument, NULL, 'H' },
4738 { "poweroff", no_argument, NULL, 'P' },
4739 { "reboot", no_argument, NULL, 'r' },
4740 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4741 { NULL, 0, NULL, 0 }
4749 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4757 arg_action = ACTION_HALT;
4761 arg_action = ACTION_POWEROFF;
4766 arg_action = ACTION_KEXEC;
4768 arg_action = ACTION_REBOOT;
4772 if (arg_action != ACTION_HALT)
4773 arg_action = ACTION_POWEROFF;
4786 /* Compatibility nops */
4790 arg_action = ACTION_CANCEL_SHUTDOWN;
4797 log_error("Unknown option code %c", c);
4802 if (argc > optind) {
4803 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4804 log_error("Failed to parse time specification: %s", argv[optind]);
4808 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4810 /* We skip the time argument */
4811 if (argc > optind + 1)
4812 arg_wall = argv + optind + 1;
4819 static int telinit_parse_argv(int argc, char *argv[]) {
4826 static const struct option options[] = {
4827 { "help", no_argument, NULL, ARG_HELP },
4828 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4829 { NULL, 0, NULL, 0 }
4832 static const struct {
4836 { '0', ACTION_POWEROFF },
4837 { '6', ACTION_REBOOT },
4838 { '1', ACTION_RESCUE },
4839 { '2', ACTION_RUNLEVEL2 },
4840 { '3', ACTION_RUNLEVEL3 },
4841 { '4', ACTION_RUNLEVEL4 },
4842 { '5', ACTION_RUNLEVEL5 },
4843 { 's', ACTION_RESCUE },
4844 { 'S', ACTION_RESCUE },
4845 { 'q', ACTION_RELOAD },
4846 { 'Q', ACTION_RELOAD },
4847 { 'u', ACTION_REEXEC },
4848 { 'U', ACTION_REEXEC }
4857 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4872 log_error("Unknown option code %c", c);
4877 if (optind >= argc) {
4882 if (optind + 1 < argc) {
4883 log_error("Too many arguments.");
4887 if (strlen(argv[optind]) != 1) {
4888 log_error("Expected single character argument.");
4892 for (i = 0; i < ELEMENTSOF(table); i++)
4893 if (table[i].from == argv[optind][0])
4896 if (i >= ELEMENTSOF(table)) {
4897 log_error("Unknown command %s.", argv[optind]);
4901 arg_action = table[i].to;
4908 static int runlevel_parse_argv(int argc, char *argv[]) {
4914 static const struct option options[] = {
4915 { "help", no_argument, NULL, ARG_HELP },
4916 { NULL, 0, NULL, 0 }
4924 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4935 log_error("Unknown option code %c", c);
4940 if (optind < argc) {
4941 log_error("Too many arguments.");
4948 static int parse_argv(int argc, char *argv[]) {
4952 if (program_invocation_short_name) {
4954 if (strstr(program_invocation_short_name, "halt")) {
4955 arg_action = ACTION_HALT;
4956 return halt_parse_argv(argc, argv);
4957 } else if (strstr(program_invocation_short_name, "poweroff")) {
4958 arg_action = ACTION_POWEROFF;
4959 return halt_parse_argv(argc, argv);
4960 } else if (strstr(program_invocation_short_name, "reboot")) {
4962 arg_action = ACTION_KEXEC;
4964 arg_action = ACTION_REBOOT;
4965 return halt_parse_argv(argc, argv);
4966 } else if (strstr(program_invocation_short_name, "shutdown")) {
4967 arg_action = ACTION_POWEROFF;
4968 return shutdown_parse_argv(argc, argv);
4969 } else if (strstr(program_invocation_short_name, "init")) {
4971 if (sd_booted() > 0) {
4972 arg_action = ACTION_INVALID;
4973 return telinit_parse_argv(argc, argv);
4975 /* Hmm, so some other init system is
4976 * running, we need to forward this
4977 * request to it. For now we simply
4978 * guess that it is Upstart. */
4980 execv("/lib/upstart/telinit", argv);
4982 log_error("Couldn't find an alternative telinit implementation to spawn.");
4986 } else if (strstr(program_invocation_short_name, "runlevel")) {
4987 arg_action = ACTION_RUNLEVEL;
4988 return runlevel_parse_argv(argc, argv);
4992 arg_action = ACTION_SYSTEMCTL;
4993 return systemctl_parse_argv(argc, argv);
4996 static int action_to_runlevel(void) {
4998 static const char table[_ACTION_MAX] = {
4999 [ACTION_HALT] = '0',
5000 [ACTION_POWEROFF] = '0',
5001 [ACTION_REBOOT] = '6',
5002 [ACTION_RUNLEVEL2] = '2',
5003 [ACTION_RUNLEVEL3] = '3',
5004 [ACTION_RUNLEVEL4] = '4',
5005 [ACTION_RUNLEVEL5] = '5',
5006 [ACTION_RESCUE] = '1'
5009 assert(arg_action < _ACTION_MAX);
5011 return table[arg_action];
5014 static int talk_upstart(void) {
5015 DBusMessage *m = NULL, *reply = NULL;
5017 int previous, rl, r;
5019 env1_buf[] = "RUNLEVEL=X",
5020 env2_buf[] = "PREVLEVEL=X";
5021 char *env1 = env1_buf, *env2 = env2_buf;
5022 const char *emit = "runlevel";
5023 dbus_bool_t b_false = FALSE;
5024 DBusMessageIter iter, sub;
5025 DBusConnection *bus;
5027 dbus_error_init(&error);
5029 if (!(rl = action_to_runlevel()))
5032 if (utmp_get_runlevel(&previous, NULL) < 0)
5035 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
5036 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
5041 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
5046 if ((r = bus_check_peercred(bus)) < 0) {
5047 log_error("Failed to verify owner of bus.");
5051 if (!(m = dbus_message_new_method_call(
5052 "com.ubuntu.Upstart",
5053 "/com/ubuntu/Upstart",
5054 "com.ubuntu.Upstart0_6",
5057 log_error("Could not allocate message.");
5062 dbus_message_iter_init_append(m, &iter);
5064 env1_buf[sizeof(env1_buf)-2] = rl;
5065 env2_buf[sizeof(env2_buf)-2] = previous;
5067 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5068 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5069 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5070 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5071 !dbus_message_iter_close_container(&iter, &sub) ||
5072 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5073 log_error("Could not append arguments to message.");
5078 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5080 if (error_is_no_service(&error)) {
5085 log_error("Failed to issue method call: %s", bus_error_message(&error));
5094 dbus_message_unref(m);
5097 dbus_message_unref(reply);
5100 dbus_connection_flush(bus);
5101 dbus_connection_close(bus);
5102 dbus_connection_unref(bus);
5105 dbus_error_free(&error);
5110 static int talk_initctl(void) {
5111 struct init_request request;
5115 if (!(rl = action_to_runlevel()))
5119 request.magic = INIT_MAGIC;
5120 request.sleeptime = 0;
5121 request.cmd = INIT_CMD_RUNLVL;
5122 request.runlevel = rl;
5124 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5126 if (errno == ENOENT)
5129 log_error("Failed to open "INIT_FIFO": %m");
5134 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5135 close_nointr_nofail(fd);
5138 log_error("Failed to write to "INIT_FIFO": %m");
5139 return errno ? -errno : -EIO;
5145 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5147 static const struct {
5155 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
5157 { "list-units", LESS, 1, list_units },
5158 { "list-jobs", EQUAL, 1, list_jobs },
5159 { "clear-jobs", EQUAL, 1, daemon_reload },
5160 { "load", MORE, 2, load_unit },
5161 { "cancel", MORE, 2, cancel_job },
5162 { "start", MORE, 2, start_unit },
5163 { "stop", MORE, 2, start_unit },
5164 { "reload", MORE, 2, start_unit },
5165 { "restart", MORE, 2, start_unit },
5166 { "try-restart", MORE, 2, start_unit },
5167 { "reload-or-restart", MORE, 2, start_unit },
5168 { "reload-or-try-restart", MORE, 2, start_unit },
5169 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5170 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5171 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5172 { "isolate", EQUAL, 2, start_unit },
5173 { "kill", MORE, 2, kill_unit },
5174 { "is-active", MORE, 2, check_unit },
5175 { "check", MORE, 2, check_unit },
5176 { "show", MORE, 1, show },
5177 { "status", MORE, 2, show },
5178 { "monitor", EQUAL, 1, monitor },
5179 { "dump", EQUAL, 1, dump },
5180 { "dot", EQUAL, 1, dot },
5181 { "snapshot", LESS, 2, snapshot },
5182 { "delete", MORE, 2, delete_snapshot },
5183 { "daemon-reload", EQUAL, 1, daemon_reload },
5184 { "daemon-reexec", EQUAL, 1, daemon_reload },
5185 { "show-environment", EQUAL, 1, show_enviroment },
5186 { "set-environment", MORE, 2, set_environment },
5187 { "unset-environment", MORE, 2, set_environment },
5188 { "halt", EQUAL, 1, start_special },
5189 { "poweroff", EQUAL, 1, start_special },
5190 { "reboot", EQUAL, 1, start_special },
5191 { "kexec", EQUAL, 1, start_special },
5192 { "default", EQUAL, 1, start_special },
5193 { "rescue", EQUAL, 1, start_special },
5194 { "emergency", EQUAL, 1, start_special },
5195 { "exit", EQUAL, 1, start_special },
5196 { "reset-failed", MORE, 1, reset_failed },
5197 { "enable", MORE, 2, enable_unit },
5198 { "disable", MORE, 2, enable_unit },
5199 { "is-enabled", MORE, 2, enable_unit }
5209 left = argc - optind;
5212 /* Special rule: no arguments means "list-units" */
5215 if (streq(argv[optind], "help")) {
5220 for (i = 0; i < ELEMENTSOF(verbs); i++)
5221 if (streq(argv[optind], verbs[i].verb))
5224 if (i >= ELEMENTSOF(verbs)) {
5225 log_error("Unknown operation %s", argv[optind]);
5230 switch (verbs[i].argc_cmp) {
5233 if (left != verbs[i].argc) {
5234 log_error("Invalid number of arguments.");
5241 if (left < verbs[i].argc) {
5242 log_error("Too few arguments.");
5249 if (left > verbs[i].argc) {
5250 log_error("Too many arguments.");
5257 assert_not_reached("Unknown comparison operator.");
5260 /* Require a bus connection for all operations but
5262 if (!streq(verbs[i].verb, "enable") &&
5263 !streq(verbs[i].verb, "disable") &&
5265 log_error("Failed to get D-Bus connection: %s", error->message);
5269 return verbs[i].dispatch(bus, argv + optind, left);
5272 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
5274 struct msghdr msghdr;
5276 union sockaddr_union sockaddr;
5277 struct shutdownd_command c;
5285 strncpy(c.wall_message, message, sizeof(c.wall_message));
5287 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
5291 sockaddr.sa.sa_family = AF_UNIX;
5292 sockaddr.un.sun_path[0] = 0;
5293 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
5296 iovec.iov_base = (char*) &c;
5297 iovec.iov_len = sizeof(c);
5300 msghdr.msg_name = &sockaddr;
5301 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
5303 msghdr.msg_iov = &iovec;
5304 msghdr.msg_iovlen = 1;
5306 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5307 close_nointr_nofail(fd);
5311 close_nointr_nofail(fd);
5315 static int reload_with_fallback(DBusConnection *bus) {
5318 /* First, try systemd via D-Bus. */
5319 if (daemon_reload(bus, NULL, 0) > 0)
5323 /* Nothing else worked, so let's try signals */
5324 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5326 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5327 log_error("kill() failed: %m");
5334 static int start_with_fallback(DBusConnection *bus) {
5337 /* First, try systemd via D-Bus. */
5338 if (start_unit(bus, NULL, 0) >= 0)
5342 /* Hmm, talking to systemd via D-Bus didn't work. Then
5343 * let's try to talk to Upstart via D-Bus. */
5344 if (talk_upstart() > 0)
5347 /* Nothing else worked, so let's try
5349 if (talk_initctl() > 0)
5352 log_error("Failed to talk to init daemon.");
5356 warn_wall(arg_action);
5360 static int halt_main(DBusConnection *bus) {
5363 if (geteuid() != 0) {
5364 log_error("Must be root.");
5370 char date[FORMAT_TIMESTAMP_MAX];
5372 m = strv_join(arg_wall, " ");
5373 r = send_shutdownd(arg_when,
5374 arg_action == ACTION_HALT ? 'H' :
5375 arg_action == ACTION_POWEROFF ? 'P' :
5382 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5384 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5385 format_timestamp(date, sizeof(date), arg_when));
5390 if (!arg_dry && !arg_immediate)
5391 return start_with_fallback(bus);
5394 if (sd_booted() > 0)
5395 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5396 else if ((r = utmp_put_shutdown(0)) < 0)
5397 log_warning("Failed to write utmp record: %s", strerror(-r));
5406 /* Make sure C-A-D is handled by the kernel from this
5408 reboot(RB_ENABLE_CAD);
5410 switch (arg_action) {
5413 log_info("Halting.");
5414 reboot(RB_HALT_SYSTEM);
5417 case ACTION_POWEROFF:
5418 log_info("Powering off.");
5419 reboot(RB_POWER_OFF);
5423 log_info("Rebooting.");
5424 reboot(RB_AUTOBOOT);
5428 assert_not_reached("Unknown halt action.");
5431 /* We should never reach this. */
5435 static int runlevel_main(void) {
5436 int r, runlevel, previous;
5438 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5439 printf("unknown\n");
5444 previous <= 0 ? 'N' : previous,
5445 runlevel <= 0 ? 'N' : runlevel);
5450 static void pager_open(void) {
5458 if (!on_tty() || arg_no_pager)
5461 if ((pager = getenv("PAGER")))
5462 if (!*pager || streq(pager, "cat"))
5465 /* Determine and cache number of columns before we spawn the
5466 * pager so that we get the value from the actual tty */
5470 log_error("Failed to create pager pipe: %m");
5474 parent_pid = getpid();
5477 if (pager_pid < 0) {
5478 log_error("Failed to fork pager: %m");
5483 /* In the child start the pager */
5484 if (pager_pid == 0) {
5486 dup2(fd[0], STDIN_FILENO);
5489 setenv("LESS", "FRSX", 0);
5491 /* Make sure the pager goes away when the parent dies */
5492 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5493 _exit(EXIT_FAILURE);
5495 /* Check whether our parent died before we were able
5496 * to set the death signal */
5497 if (getppid() != parent_pid)
5498 _exit(EXIT_SUCCESS);
5501 execlp(pager, pager, NULL);
5502 execl("/bin/sh", "sh", "-c", pager, NULL);
5504 /* Debian's alternatives command for pagers is
5505 * called 'pager'. Note that we do not call
5506 * sensible-pagers here, since that is just a
5507 * shell script that implements a logic that
5508 * is similar to this one anyway, but is
5509 * Debian-specific. */
5510 execlp("pager", "pager", NULL);
5512 execlp("less", "less", NULL);
5513 execlp("more", "more", NULL);
5516 log_error("Unable to execute pager: %m");
5517 _exit(EXIT_FAILURE);
5520 /* Return in the parent */
5521 if (dup2(fd[1], STDOUT_FILENO) < 0)
5522 log_error("Failed to duplicate pager pipe: %m");
5527 static void pager_close(void) {
5533 /* Inform pager that we are done */
5535 wait_for_terminate(pager_pid, &dummy);
5539 static void agent_close(void) {
5545 /* Inform agent that we are done */
5546 kill(agent_pid, SIGTERM);
5547 wait_for_terminate(agent_pid, &dummy);
5551 int main(int argc, char*argv[]) {
5552 int r, retval = EXIT_FAILURE;
5553 DBusConnection *bus = NULL;
5556 dbus_error_init(&error);
5558 log_parse_environment();
5561 if ((r = parse_argv(argc, argv)) < 0)
5564 retval = EXIT_SUCCESS;
5568 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5569 * let's shortcut this */
5570 if (arg_action == ACTION_RUNLEVEL) {
5571 r = runlevel_main();
5572 retval = r < 0 ? EXIT_FAILURE : r;
5576 bus_connect(arg_user ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5578 switch (arg_action) {
5580 case ACTION_SYSTEMCTL:
5581 r = systemctl_main(bus, argc, argv, &error);
5585 case ACTION_POWEROFF:
5591 case ACTION_RUNLEVEL2:
5592 case ACTION_RUNLEVEL3:
5593 case ACTION_RUNLEVEL4:
5594 case ACTION_RUNLEVEL5:
5596 case ACTION_EMERGENCY:
5597 case ACTION_DEFAULT:
5598 r = start_with_fallback(bus);
5603 r = reload_with_fallback(bus);
5606 case ACTION_CANCEL_SHUTDOWN:
5607 r = send_shutdownd(0, 0, false, NULL);
5610 case ACTION_INVALID:
5611 case ACTION_RUNLEVEL:
5613 assert_not_reached("Unknown action");
5616 retval = r < 0 ? EXIT_FAILURE : r;
5621 dbus_connection_flush(bus);
5622 dbus_connection_close(bus);
5623 dbus_connection_unref(bus);
5626 dbus_error_free(&error);
5630 strv_free(arg_property);