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") && !streq(d.result, "skipped"))
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") && !streq_ptr(d.result, "skipped"))
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" :
1421 streq(args[0], "try-restart") ||
1422 streq(args[0], "condrestart") ? "TryRestartUnit" :
1424 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1426 streq(args[0], "reload-or-try-restart") ||
1427 streq(args[0], "condreload") ||
1429 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1433 (streq(args[0], "isolate") ||
1434 streq(args[0], "rescue") ||
1435 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1437 one_name = table[verb_to_action(args[0])];
1440 assert(arg_action < ELEMENTSOF(table));
1441 assert(table[arg_action]);
1443 method = "StartUnit";
1445 mode = (arg_action == ACTION_EMERGENCY ||
1446 arg_action == ACTION_RESCUE ||
1447 arg_action == ACTION_RUNLEVEL2 ||
1448 arg_action == ACTION_RUNLEVEL3 ||
1449 arg_action == ACTION_RUNLEVEL4 ||
1450 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1452 one_name = table[arg_action];
1455 if (!arg_no_block) {
1456 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1457 log_error("Could not watch jobs: %s", strerror(-ret));
1461 if (!(s = set_new(string_hash_func, string_compare_func))) {
1462 log_error("Failed to allocate set.");
1469 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1472 for (i = 1; i < n; i++)
1473 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1474 ret = translate_bus_error_to_exit_status(r, &error);
1475 dbus_error_free(&error);
1480 if ((r = wait_for_jobs(bus, s)) < 0) {
1489 dbus_error_free(&error);
1494 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1501 (streq(args[0], "halt") ||
1502 streq(args[0], "poweroff") ||
1503 streq(args[0], "reboot") ||
1504 streq(args[0], "kexec") ||
1505 streq(args[0], "exit")))
1506 return daemon_reload(bus, args, n);
1508 r = start_unit(bus, args, n);
1511 warn_wall(verb_to_action(args[0]));
1516 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1517 DBusMessage *m = NULL, *reply = NULL;
1519 *interface = "org.freedesktop.systemd1.Unit",
1520 *property = "ActiveState";
1521 int r = 3; /* According to LSB: "program is not running" */
1528 dbus_error_init(&error);
1530 for (i = 1; i < n; i++) {
1531 const char *path = NULL;
1533 DBusMessageIter iter, sub;
1535 if (!(m = dbus_message_new_method_call(
1536 "org.freedesktop.systemd1",
1537 "/org/freedesktop/systemd1",
1538 "org.freedesktop.systemd1.Manager",
1540 log_error("Could not allocate message.");
1545 if (!dbus_message_append_args(m,
1546 DBUS_TYPE_STRING, &args[i],
1547 DBUS_TYPE_INVALID)) {
1548 log_error("Could not append arguments to message.");
1553 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1555 /* Hmm, cannot figure out anything about this unit... */
1559 dbus_error_free(&error);
1560 dbus_message_unref(m);
1564 if (!dbus_message_get_args(reply, &error,
1565 DBUS_TYPE_OBJECT_PATH, &path,
1566 DBUS_TYPE_INVALID)) {
1567 log_error("Failed to parse reply: %s", bus_error_message(&error));
1572 dbus_message_unref(m);
1573 if (!(m = dbus_message_new_method_call(
1574 "org.freedesktop.systemd1",
1576 "org.freedesktop.DBus.Properties",
1578 log_error("Could not allocate message.");
1583 if (!dbus_message_append_args(m,
1584 DBUS_TYPE_STRING, &interface,
1585 DBUS_TYPE_STRING, &property,
1586 DBUS_TYPE_INVALID)) {
1587 log_error("Could not append arguments to message.");
1592 dbus_message_unref(reply);
1593 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1594 log_error("Failed to issue method call: %s", bus_error_message(&error));
1599 if (!dbus_message_iter_init(reply, &iter) ||
1600 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1601 log_error("Failed to parse reply.");
1606 dbus_message_iter_recurse(&iter, &sub);
1608 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1609 log_error("Failed to parse reply.");
1614 dbus_message_iter_get_basic(&sub, &state);
1619 if (streq(state, "active") || streq(state, "reloading"))
1622 dbus_message_unref(m);
1623 dbus_message_unref(reply);
1629 dbus_message_unref(m);
1632 dbus_message_unref(reply);
1634 dbus_error_free(&error);
1639 static int kill_unit(DBusConnection *bus, char **args, unsigned n) {
1640 DBusMessage *m = NULL, *reply = NULL;
1648 dbus_error_init(&error);
1651 arg_kill_who = "all";
1654 arg_kill_mode = streq(arg_kill_who, "all") ? "control-group" : "process";
1656 for (i = 1; i < n; i++) {
1658 if (!(m = dbus_message_new_method_call(
1659 "org.freedesktop.systemd1",
1660 "/org/freedesktop/systemd1",
1661 "org.freedesktop.systemd1.Manager",
1663 log_error("Could not allocate message.");
1668 if (!dbus_message_append_args(m,
1669 DBUS_TYPE_STRING, &args[i],
1670 DBUS_TYPE_STRING, &arg_kill_who,
1671 DBUS_TYPE_STRING, &arg_kill_mode,
1672 DBUS_TYPE_INT32, &arg_signal,
1673 DBUS_TYPE_INVALID)) {
1674 log_error("Could not append arguments to message.");
1679 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1680 log_error("Failed to issue method call: %s", bus_error_message(&error));
1681 dbus_error_free(&error);
1685 dbus_message_unref(m);
1688 dbus_message_unref(reply);
1694 dbus_message_unref(m);
1697 dbus_message_unref(reply);
1699 dbus_error_free(&error);
1704 typedef struct ExecStatusInfo {
1712 usec_t start_timestamp;
1713 usec_t exit_timestamp;
1718 LIST_FIELDS(struct ExecStatusInfo, exec);
1721 static void exec_status_info_free(ExecStatusInfo *i) {
1730 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1731 uint64_t start_timestamp, exit_timestamp;
1732 DBusMessageIter sub2, sub3;
1736 int32_t code, status;
1742 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1745 dbus_message_iter_recurse(sub, &sub2);
1747 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1750 if (!(i->path = strdup(path)))
1753 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1754 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1758 dbus_message_iter_recurse(&sub2, &sub3);
1759 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1760 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1761 dbus_message_iter_next(&sub3);
1766 if (!(i->argv = new0(char*, n+1)))
1770 dbus_message_iter_recurse(&sub2, &sub3);
1771 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1774 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1775 dbus_message_iter_get_basic(&sub3, &s);
1776 dbus_message_iter_next(&sub3);
1778 if (!(i->argv[n++] = strdup(s)))
1782 if (!dbus_message_iter_next(&sub2) ||
1783 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1784 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1785 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1786 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1787 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1788 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1792 i->start_timestamp = (usec_t) start_timestamp;
1793 i->exit_timestamp = (usec_t) exit_timestamp;
1794 i->pid = (pid_t) pid;
1801 typedef struct UnitStatusInfo {
1803 const char *load_state;
1804 const char *active_state;
1805 const char *sub_state;
1807 const char *description;
1808 const char *following;
1811 const char *default_control_group;
1813 usec_t inactive_exit_timestamp;
1814 usec_t active_enter_timestamp;
1815 usec_t active_exit_timestamp;
1816 usec_t inactive_enter_timestamp;
1818 bool need_daemon_reload;
1823 const char *status_text;
1825 #ifdef HAVE_SYSV_COMPAT
1829 usec_t start_timestamp;
1830 usec_t exit_timestamp;
1832 int exit_code, exit_status;
1835 unsigned n_accepted;
1836 unsigned n_connections;
1840 const char *sysfs_path;
1842 /* Mount, Automount */
1848 LIST_HEAD(ExecStatusInfo, exec);
1851 static void print_status_info(UnitStatusInfo *i) {
1853 const char *on, *off, *ss;
1855 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1856 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1860 /* This shows pretty information about a unit. See
1861 * print_property() for a low-level property printer */
1863 printf("%s", strna(i->id));
1865 if (i->description && !streq_ptr(i->id, i->description))
1866 printf(" - %s", i->description);
1871 printf("\t Follow: unit currently follows state of %s\n", i->following);
1873 if (streq_ptr(i->load_state, "failed") ||
1874 streq_ptr(i->load_state, "banned")) {
1875 on = ansi_highlight(true);
1876 off = ansi_highlight(false);
1881 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1883 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1885 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1887 if (streq_ptr(i->active_state, "failed")) {
1888 on = ansi_highlight(true);
1889 off = ansi_highlight(false);
1890 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1891 on = ansi_highlight_green(true);
1892 off = ansi_highlight_green(false);
1897 printf("\t Active: %s%s (%s)%s",
1899 strna(i->active_state),
1903 printf("\t Active: %s%s%s",
1905 strna(i->active_state),
1908 timestamp = (streq_ptr(i->active_state, "active") ||
1909 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1910 (streq_ptr(i->active_state, "inactive") ||
1911 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1912 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1913 i->active_exit_timestamp;
1915 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1916 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1919 printf(" since %s; %s\n", s2, s1);
1921 printf(" since %s\n", s2);
1926 printf("\t Device: %s\n", i->sysfs_path);
1928 printf("\t Where: %s\n", i->where);
1930 printf("\t What: %s\n", i->what);
1933 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1935 LIST_FOREACH(exec, p, i->exec) {
1939 /* Only show exited processes here */
1943 t = strv_join(p->argv, " ");
1944 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
1947 #ifdef HAVE_SYSV_COMPAT
1949 good = is_clean_exit_lsb(p->code, p->status);
1952 good = is_clean_exit(p->code, p->status);
1955 on = ansi_highlight(true);
1956 off = ansi_highlight(false);
1960 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
1962 if (p->code == CLD_EXITED) {
1965 printf("status=%i", p->status);
1967 #ifdef HAVE_SYSV_COMPAT
1968 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1970 if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1975 printf("signal=%s", signal_to_string(p->status));
1977 printf(")%s\n", off);
1981 if (i->main_pid == p->pid &&
1982 i->start_timestamp == p->start_timestamp &&
1983 i->exit_timestamp == p->start_timestamp)
1984 /* Let's not show this twice */
1987 if (p->pid == i->control_pid)
1991 if (i->main_pid > 0 || i->control_pid > 0) {
1994 if (i->main_pid > 0) {
1995 printf("Main PID: %u", (unsigned) i->main_pid);
1999 get_process_name(i->main_pid, &t);
2004 } else if (i->exit_code > 0) {
2005 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2007 if (i->exit_code == CLD_EXITED) {
2010 printf("status=%i", i->exit_status);
2012 #ifdef HAVE_SYSV_COMPAT
2013 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
2015 if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
2020 printf("signal=%s", signal_to_string(i->exit_status));
2025 if (i->main_pid > 0 && i->control_pid > 0)
2028 if (i->control_pid > 0) {
2031 printf(" Control: %u", (unsigned) i->control_pid);
2033 get_process_name(i->control_pid, &t);
2044 printf("\t Status: \"%s\"\n", i->status_text);
2046 if (i->default_control_group) {
2049 printf("\t CGroup: %s\n", i->default_control_group);
2051 if ((c = columns()) > 18)
2056 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
2059 if (i->need_daemon_reload)
2060 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2061 ansi_highlight(true),
2062 ansi_highlight(false),
2063 arg_user ? "--user" : "--system");
2066 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2068 switch (dbus_message_iter_get_arg_type(iter)) {
2070 case DBUS_TYPE_STRING: {
2073 dbus_message_iter_get_basic(iter, &s);
2076 if (streq(name, "Id"))
2078 else if (streq(name, "LoadState"))
2080 else if (streq(name, "ActiveState"))
2081 i->active_state = s;
2082 else if (streq(name, "SubState"))
2084 else if (streq(name, "Description"))
2086 else if (streq(name, "FragmentPath"))
2088 #ifdef HAVE_SYSV_COMPAT
2089 else if (streq(name, "SysVPath")) {
2094 else if (streq(name, "DefaultControlGroup"))
2095 i->default_control_group = s;
2096 else if (streq(name, "StatusText"))
2098 else if (streq(name, "SysFSPath"))
2100 else if (streq(name, "Where"))
2102 else if (streq(name, "What"))
2104 else if (streq(name, "Following"))
2111 case DBUS_TYPE_BOOLEAN: {
2114 dbus_message_iter_get_basic(iter, &b);
2116 if (streq(name, "Accept"))
2118 else if (streq(name, "NeedDaemonReload"))
2119 i->need_daemon_reload = b;
2124 case DBUS_TYPE_UINT32: {
2127 dbus_message_iter_get_basic(iter, &u);
2129 if (streq(name, "MainPID")) {
2131 i->main_pid = (pid_t) u;
2134 } else if (streq(name, "ControlPID"))
2135 i->control_pid = (pid_t) u;
2136 else if (streq(name, "ExecMainPID")) {
2138 i->main_pid = (pid_t) u;
2139 } else if (streq(name, "NAccepted"))
2141 else if (streq(name, "NConnections"))
2142 i->n_connections = u;
2147 case DBUS_TYPE_INT32: {
2150 dbus_message_iter_get_basic(iter, &j);
2152 if (streq(name, "ExecMainCode"))
2153 i->exit_code = (int) j;
2154 else if (streq(name, "ExecMainStatus"))
2155 i->exit_status = (int) j;
2160 case DBUS_TYPE_UINT64: {
2163 dbus_message_iter_get_basic(iter, &u);
2165 if (streq(name, "ExecMainStartTimestamp"))
2166 i->start_timestamp = (usec_t) u;
2167 else if (streq(name, "ExecMainExitTimestamp"))
2168 i->exit_timestamp = (usec_t) u;
2169 else if (streq(name, "ActiveEnterTimestamp"))
2170 i->active_enter_timestamp = (usec_t) u;
2171 else if (streq(name, "InactiveEnterTimestamp"))
2172 i->inactive_enter_timestamp = (usec_t) u;
2173 else if (streq(name, "InactiveExitTimestamp"))
2174 i->inactive_exit_timestamp = (usec_t) u;
2175 else if (streq(name, "ActiveExitTimestamp"))
2176 i->active_exit_timestamp = (usec_t) u;
2181 case DBUS_TYPE_ARRAY: {
2183 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2184 startswith(name, "Exec")) {
2185 DBusMessageIter sub;
2187 dbus_message_iter_recurse(iter, &sub);
2188 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2189 ExecStatusInfo *info;
2192 if (!(info = new0(ExecStatusInfo, 1)))
2195 if (!(info->name = strdup(name))) {
2200 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2205 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2207 dbus_message_iter_next(&sub);
2218 static int print_property(const char *name, DBusMessageIter *iter) {
2222 /* This is a low-level property printer, see
2223 * print_status_info() for the nicer output */
2225 if (arg_property && !strv_find(arg_property, name))
2228 switch (dbus_message_iter_get_arg_type(iter)) {
2230 case DBUS_TYPE_STRING: {
2232 dbus_message_iter_get_basic(iter, &s);
2234 if (arg_all || s[0])
2235 printf("%s=%s\n", name, s);
2240 case DBUS_TYPE_BOOLEAN: {
2242 dbus_message_iter_get_basic(iter, &b);
2243 printf("%s=%s\n", name, yes_no(b));
2248 case DBUS_TYPE_UINT64: {
2250 dbus_message_iter_get_basic(iter, &u);
2252 /* Yes, heuristics! But we can change this check
2253 * should it turn out to not be sufficient */
2255 if (strstr(name, "Timestamp")) {
2256 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
2258 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
2259 printf("%s=%s\n", name, strempty(t));
2260 } else if (strstr(name, "USec")) {
2261 char timespan[FORMAT_TIMESPAN_MAX];
2263 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
2265 printf("%s=%llu\n", name, (unsigned long long) u);
2270 case DBUS_TYPE_UINT32: {
2272 dbus_message_iter_get_basic(iter, &u);
2274 if (strstr(name, "UMask") || strstr(name, "Mode"))
2275 printf("%s=%04o\n", name, u);
2277 printf("%s=%u\n", name, (unsigned) u);
2282 case DBUS_TYPE_INT32: {
2284 dbus_message_iter_get_basic(iter, &i);
2286 printf("%s=%i\n", name, (int) i);
2290 case DBUS_TYPE_DOUBLE: {
2292 dbus_message_iter_get_basic(iter, &d);
2294 printf("%s=%g\n", name, d);
2298 case DBUS_TYPE_STRUCT: {
2299 DBusMessageIter sub;
2300 dbus_message_iter_recurse(iter, &sub);
2302 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2305 dbus_message_iter_get_basic(&sub, &u);
2308 printf("%s=%u\n", name, (unsigned) u);
2310 printf("%s=\n", name);
2313 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2316 dbus_message_iter_get_basic(&sub, &s);
2318 if (arg_all || s[0])
2319 printf("%s=%s\n", name, s);
2327 case DBUS_TYPE_ARRAY:
2329 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2330 DBusMessageIter sub;
2333 dbus_message_iter_recurse(iter, &sub);
2335 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2336 printf("%s=", name);
2338 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2341 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2342 dbus_message_iter_get_basic(&sub, &s);
2343 printf("%s%s", space ? " " : "", s);
2346 dbus_message_iter_next(&sub);
2354 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2355 DBusMessageIter sub;
2357 dbus_message_iter_recurse(iter, &sub);
2359 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2360 printf("%s=", name);
2362 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2365 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2366 dbus_message_iter_get_basic(&sub, &u);
2369 dbus_message_iter_next(&sub);
2377 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
2378 DBusMessageIter sub, sub2;
2380 dbus_message_iter_recurse(iter, &sub);
2381 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2385 dbus_message_iter_recurse(&sub, &sub2);
2387 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
2388 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
2389 printf("EnvironmentFile=%s (ignore=%s)\n", path, yes_no(ignore));
2391 dbus_message_iter_next(&sub);
2396 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2397 DBusMessageIter sub, sub2;
2399 dbus_message_iter_recurse(iter, &sub);
2400 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2401 const char *type, *path;
2403 dbus_message_iter_recurse(&sub, &sub2);
2405 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2406 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2407 printf("%s=%s\n", type, path);
2409 dbus_message_iter_next(&sub);
2414 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2415 DBusMessageIter sub, sub2;
2417 dbus_message_iter_recurse(iter, &sub);
2418 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2420 uint64_t value, next_elapse;
2422 dbus_message_iter_recurse(&sub, &sub2);
2424 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2425 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2426 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2427 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2429 printf("%s={ value=%s ; next_elapse=%s }\n",
2431 format_timespan(timespan1, sizeof(timespan1), value),
2432 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2435 dbus_message_iter_next(&sub);
2440 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2441 DBusMessageIter sub;
2443 dbus_message_iter_recurse(iter, &sub);
2444 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2445 ExecStatusInfo info;
2448 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2449 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2452 t = strv_join(info.argv, " ");
2454 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2458 yes_no(info.ignore),
2459 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2460 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2461 (unsigned) info. pid,
2462 sigchld_code_to_string(info.code),
2464 info.code == CLD_EXITED ? "" : "/",
2465 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2471 strv_free(info.argv);
2473 dbus_message_iter_next(&sub);
2483 printf("%s=[unprintable]\n", name);
2488 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2489 DBusMessage *m = NULL, *reply = NULL;
2490 const char *interface = "";
2493 DBusMessageIter iter, sub, sub2, sub3;
2494 UnitStatusInfo info;
2502 dbus_error_init(&error);
2504 if (!(m = dbus_message_new_method_call(
2505 "org.freedesktop.systemd1",
2507 "org.freedesktop.DBus.Properties",
2509 log_error("Could not allocate message.");
2514 if (!dbus_message_append_args(m,
2515 DBUS_TYPE_STRING, &interface,
2516 DBUS_TYPE_INVALID)) {
2517 log_error("Could not append arguments to message.");
2522 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2523 log_error("Failed to issue method call: %s", bus_error_message(&error));
2528 if (!dbus_message_iter_init(reply, &iter) ||
2529 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2530 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2531 log_error("Failed to parse reply.");
2536 dbus_message_iter_recurse(&iter, &sub);
2543 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2546 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2547 log_error("Failed to parse reply.");
2552 dbus_message_iter_recurse(&sub, &sub2);
2554 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2555 log_error("Failed to parse reply.");
2560 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2561 log_error("Failed to parse reply.");
2566 dbus_message_iter_recurse(&sub2, &sub3);
2568 if (show_properties)
2569 r = print_property(name, &sub3);
2571 r = status_property(name, &sub3, &info);
2574 log_error("Failed to parse reply.");
2579 dbus_message_iter_next(&sub);
2584 if (!show_properties)
2585 print_status_info(&info);
2587 if (!streq_ptr(info.active_state, "active") &&
2588 !streq_ptr(info.active_state, "reloading") &&
2589 streq(verb, "status"))
2590 /* According to LSB: "program not running" */
2593 while ((p = info.exec)) {
2594 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2595 exec_status_info_free(p);
2600 dbus_message_unref(m);
2603 dbus_message_unref(reply);
2605 dbus_error_free(&error);
2610 static int show(DBusConnection *bus, char **args, unsigned n) {
2611 DBusMessage *m = NULL, *reply = NULL;
2615 bool show_properties, new_line = false;
2620 dbus_error_init(&error);
2622 show_properties = !streq(args[0], "status");
2624 if (show_properties)
2627 if (show_properties && n <= 1) {
2628 /* If not argument is specified inspect the manager
2631 ret = show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2635 for (i = 1; i < n; i++) {
2636 const char *path = NULL;
2639 if (safe_atou32(args[i], &id) < 0) {
2641 /* Interpret as unit name */
2643 if (!(m = dbus_message_new_method_call(
2644 "org.freedesktop.systemd1",
2645 "/org/freedesktop/systemd1",
2646 "org.freedesktop.systemd1.Manager",
2648 log_error("Could not allocate message.");
2653 if (!dbus_message_append_args(m,
2654 DBUS_TYPE_STRING, &args[i],
2655 DBUS_TYPE_INVALID)) {
2656 log_error("Could not append arguments to message.");
2661 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2663 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2664 log_error("Failed to issue method call: %s", bus_error_message(&error));
2669 dbus_error_free(&error);
2671 dbus_message_unref(m);
2672 if (!(m = dbus_message_new_method_call(
2673 "org.freedesktop.systemd1",
2674 "/org/freedesktop/systemd1",
2675 "org.freedesktop.systemd1.Manager",
2677 log_error("Could not allocate message.");
2682 if (!dbus_message_append_args(m,
2683 DBUS_TYPE_STRING, &args[i],
2684 DBUS_TYPE_INVALID)) {
2685 log_error("Could not append arguments to message.");
2690 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2691 log_error("Failed to issue method call: %s", bus_error_message(&error));
2693 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2694 ret = 4; /* According to LSB: "program or service status is unknown" */
2701 } else if (show_properties) {
2703 /* Interpret as job id */
2705 if (!(m = dbus_message_new_method_call(
2706 "org.freedesktop.systemd1",
2707 "/org/freedesktop/systemd1",
2708 "org.freedesktop.systemd1.Manager",
2710 log_error("Could not allocate message.");
2715 if (!dbus_message_append_args(m,
2716 DBUS_TYPE_UINT32, &id,
2717 DBUS_TYPE_INVALID)) {
2718 log_error("Could not append arguments to message.");
2723 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2724 log_error("Failed to issue method call: %s", bus_error_message(&error));
2730 /* Interpret as PID */
2732 if (!(m = dbus_message_new_method_call(
2733 "org.freedesktop.systemd1",
2734 "/org/freedesktop/systemd1",
2735 "org.freedesktop.systemd1.Manager",
2737 log_error("Could not allocate message.");
2742 if (!dbus_message_append_args(m,
2743 DBUS_TYPE_UINT32, &id,
2744 DBUS_TYPE_INVALID)) {
2745 log_error("Could not append arguments to message.");
2750 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2751 log_error("Failed to issue method call: %s", bus_error_message(&error));
2757 if (!dbus_message_get_args(reply, &error,
2758 DBUS_TYPE_OBJECT_PATH, &path,
2759 DBUS_TYPE_INVALID)) {
2760 log_error("Failed to parse reply: %s", bus_error_message(&error));
2765 if ((r = show_one(args[0], bus, path, show_properties, &new_line)) != 0)
2768 dbus_message_unref(m);
2769 dbus_message_unref(reply);
2775 dbus_message_unref(m);
2778 dbus_message_unref(reply);
2780 dbus_error_free(&error);
2785 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2787 DBusMessage *m = NULL, *reply = NULL;
2792 dbus_error_init(&error);
2794 log_debug("Got D-Bus request: %s.%s() on %s",
2795 dbus_message_get_interface(message),
2796 dbus_message_get_member(message),
2797 dbus_message_get_path(message));
2799 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2800 log_error("Warning! D-Bus connection terminated.");
2801 dbus_connection_close(connection);
2803 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2804 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2805 const char *id, *path;
2807 if (!dbus_message_get_args(message, &error,
2808 DBUS_TYPE_STRING, &id,
2809 DBUS_TYPE_OBJECT_PATH, &path,
2811 log_error("Failed to parse message: %s", bus_error_message(&error));
2812 else if (streq(dbus_message_get_member(message), "UnitNew"))
2813 printf("Unit %s added.\n", id);
2815 printf("Unit %s removed.\n", id);
2817 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2818 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2820 const char *path, *result;
2822 if (!dbus_message_get_args(message, &error,
2823 DBUS_TYPE_UINT32, &id,
2824 DBUS_TYPE_OBJECT_PATH, &path,
2825 DBUS_TYPE_STRING, &result,
2827 log_error("Failed to parse message: %s", bus_error_message(&error));
2828 else if (streq(dbus_message_get_member(message), "JobNew"))
2829 printf("Job %u added.\n", id);
2831 printf("Job %u removed.\n", id);
2834 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2836 const char *path, *interface, *property = "Id";
2837 DBusMessageIter iter, sub;
2839 path = dbus_message_get_path(message);
2841 if (!dbus_message_get_args(message, &error,
2842 DBUS_TYPE_STRING, &interface,
2843 DBUS_TYPE_INVALID)) {
2844 log_error("Failed to parse message: %s", bus_error_message(&error));
2848 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2849 !streq(interface, "org.freedesktop.systemd1.Unit"))
2852 if (!(m = dbus_message_new_method_call(
2853 "org.freedesktop.systemd1",
2855 "org.freedesktop.DBus.Properties",
2857 log_error("Could not allocate message.");
2861 if (!dbus_message_append_args(m,
2862 DBUS_TYPE_STRING, &interface,
2863 DBUS_TYPE_STRING, &property,
2864 DBUS_TYPE_INVALID)) {
2865 log_error("Could not append arguments to message.");
2869 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2870 log_error("Failed to issue method call: %s", bus_error_message(&error));
2874 if (!dbus_message_iter_init(reply, &iter) ||
2875 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2876 log_error("Failed to parse reply.");
2880 dbus_message_iter_recurse(&iter, &sub);
2882 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2885 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2886 log_error("Failed to parse reply.");
2890 dbus_message_iter_get_basic(&sub, &id);
2891 printf("Unit %s changed.\n", id);
2895 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2896 log_error("Failed to parse reply.");
2900 dbus_message_iter_get_basic(&sub, &id);
2901 printf("Job %u changed.\n", id);
2907 dbus_message_unref(m);
2910 dbus_message_unref(reply);
2912 dbus_error_free(&error);
2913 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2917 dbus_message_unref(m);
2920 dbus_message_unref(reply);
2922 dbus_error_free(&error);
2923 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2926 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2927 DBusMessage *m = NULL, *reply = NULL;
2931 dbus_error_init(&error);
2934 dbus_bus_add_match(bus,
2936 "sender='org.freedesktop.systemd1',"
2937 "interface='org.freedesktop.systemd1.Manager',"
2938 "path='/org/freedesktop/systemd1'",
2941 if (dbus_error_is_set(&error)) {
2942 log_error("Failed to add match: %s", bus_error_message(&error));
2947 dbus_bus_add_match(bus,
2949 "sender='org.freedesktop.systemd1',"
2950 "interface='org.freedesktop.DBus.Properties',"
2951 "member='PropertiesChanged'",
2954 if (dbus_error_is_set(&error)) {
2955 log_error("Failed to add match: %s", bus_error_message(&error));
2961 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2962 log_error("Failed to add filter.");
2967 if (!(m = dbus_message_new_method_call(
2968 "org.freedesktop.systemd1",
2969 "/org/freedesktop/systemd1",
2970 "org.freedesktop.systemd1.Manager",
2972 log_error("Could not allocate message.");
2977 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2978 log_error("Failed to issue method call: %s", bus_error_message(&error));
2983 while (dbus_connection_read_write_dispatch(bus, -1))
2990 /* This is slightly dirty, since we don't undo the filter or the matches. */
2993 dbus_message_unref(m);
2996 dbus_message_unref(reply);
2998 dbus_error_free(&error);
3003 static int dump(DBusConnection *bus, char **args, unsigned n) {
3004 DBusMessage *m = NULL, *reply = NULL;
3009 dbus_error_init(&error);
3013 if (!(m = dbus_message_new_method_call(
3014 "org.freedesktop.systemd1",
3015 "/org/freedesktop/systemd1",
3016 "org.freedesktop.systemd1.Manager",
3018 log_error("Could not allocate message.");
3022 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3023 log_error("Failed to issue method call: %s", bus_error_message(&error));
3028 if (!dbus_message_get_args(reply, &error,
3029 DBUS_TYPE_STRING, &text,
3030 DBUS_TYPE_INVALID)) {
3031 log_error("Failed to parse reply: %s", bus_error_message(&error));
3036 fputs(text, stdout);
3042 dbus_message_unref(m);
3045 dbus_message_unref(reply);
3047 dbus_error_free(&error);
3052 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
3053 DBusMessage *m = NULL, *reply = NULL;
3056 const char *name = "", *path, *id;
3057 dbus_bool_t cleanup = FALSE;
3058 DBusMessageIter iter, sub;
3060 *interface = "org.freedesktop.systemd1.Unit",
3063 dbus_error_init(&error);
3065 if (!(m = dbus_message_new_method_call(
3066 "org.freedesktop.systemd1",
3067 "/org/freedesktop/systemd1",
3068 "org.freedesktop.systemd1.Manager",
3069 "CreateSnapshot"))) {
3070 log_error("Could not allocate message.");
3077 if (!dbus_message_append_args(m,
3078 DBUS_TYPE_STRING, &name,
3079 DBUS_TYPE_BOOLEAN, &cleanup,
3080 DBUS_TYPE_INVALID)) {
3081 log_error("Could not append arguments to message.");
3086 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3087 log_error("Failed to issue method call: %s", bus_error_message(&error));
3092 if (!dbus_message_get_args(reply, &error,
3093 DBUS_TYPE_OBJECT_PATH, &path,
3094 DBUS_TYPE_INVALID)) {
3095 log_error("Failed to parse reply: %s", bus_error_message(&error));
3100 dbus_message_unref(m);
3101 if (!(m = dbus_message_new_method_call(
3102 "org.freedesktop.systemd1",
3104 "org.freedesktop.DBus.Properties",
3106 log_error("Could not allocate message.");
3110 if (!dbus_message_append_args(m,
3111 DBUS_TYPE_STRING, &interface,
3112 DBUS_TYPE_STRING, &property,
3113 DBUS_TYPE_INVALID)) {
3114 log_error("Could not append arguments to message.");
3119 dbus_message_unref(reply);
3120 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3121 log_error("Failed to issue method call: %s", bus_error_message(&error));
3126 if (!dbus_message_iter_init(reply, &iter) ||
3127 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3128 log_error("Failed to parse reply.");
3133 dbus_message_iter_recurse(&iter, &sub);
3135 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3136 log_error("Failed to parse reply.");
3141 dbus_message_iter_get_basic(&sub, &id);
3149 dbus_message_unref(m);
3152 dbus_message_unref(reply);
3154 dbus_error_free(&error);
3159 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
3160 DBusMessage *m = NULL, *reply = NULL;
3168 dbus_error_init(&error);
3170 for (i = 1; i < n; i++) {
3171 const char *path = NULL;
3173 if (!(m = dbus_message_new_method_call(
3174 "org.freedesktop.systemd1",
3175 "/org/freedesktop/systemd1",
3176 "org.freedesktop.systemd1.Manager",
3178 log_error("Could not allocate message.");
3183 if (!dbus_message_append_args(m,
3184 DBUS_TYPE_STRING, &args[i],
3185 DBUS_TYPE_INVALID)) {
3186 log_error("Could not append arguments to message.");
3191 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3192 log_error("Failed to issue method call: %s", bus_error_message(&error));
3197 if (!dbus_message_get_args(reply, &error,
3198 DBUS_TYPE_OBJECT_PATH, &path,
3199 DBUS_TYPE_INVALID)) {
3200 log_error("Failed to parse reply: %s", bus_error_message(&error));
3205 dbus_message_unref(m);
3206 if (!(m = dbus_message_new_method_call(
3207 "org.freedesktop.systemd1",
3209 "org.freedesktop.systemd1.Snapshot",
3211 log_error("Could not allocate message.");
3216 dbus_message_unref(reply);
3217 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3218 log_error("Failed to issue method call: %s", bus_error_message(&error));
3223 dbus_message_unref(m);
3224 dbus_message_unref(reply);
3232 dbus_message_unref(m);
3235 dbus_message_unref(reply);
3237 dbus_error_free(&error);
3242 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
3243 DBusMessage *m = NULL, *reply = NULL;
3248 dbus_error_init(&error);
3250 if (arg_action == ACTION_RELOAD)
3252 else if (arg_action == ACTION_REEXEC)
3253 method = "Reexecute";
3255 assert(arg_action == ACTION_SYSTEMCTL);
3258 streq(args[0], "clear-jobs") ||
3259 streq(args[0], "cancel") ? "ClearJobs" :
3260 streq(args[0], "daemon-reexec") ? "Reexecute" :
3261 streq(args[0], "reset-failed") ? "ResetFailed" :
3262 streq(args[0], "halt") ? "Halt" :
3263 streq(args[0], "poweroff") ? "PowerOff" :
3264 streq(args[0], "reboot") ? "Reboot" :
3265 streq(args[0], "kexec") ? "KExec" :
3266 streq(args[0], "exit") ? "Exit" :
3267 /* "daemon-reload" */ "Reload";
3270 if (!(m = dbus_message_new_method_call(
3271 "org.freedesktop.systemd1",
3272 "/org/freedesktop/systemd1",
3273 "org.freedesktop.systemd1.Manager",
3275 log_error("Could not allocate message.");
3279 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3281 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3282 /* There's always a fallback possible for
3283 * legacy actions. */
3288 log_error("Failed to issue method call: %s", bus_error_message(&error));
3297 dbus_message_unref(m);
3300 dbus_message_unref(reply);
3302 dbus_error_free(&error);
3307 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3308 DBusMessage *m = NULL, *reply = NULL;
3314 dbus_error_init(&error);
3317 return daemon_reload(bus, args, n);
3319 for (i = 1; i < n; i++) {
3321 if (!(m = dbus_message_new_method_call(
3322 "org.freedesktop.systemd1",
3323 "/org/freedesktop/systemd1",
3324 "org.freedesktop.systemd1.Manager",
3325 "ResetFailedUnit"))) {
3326 log_error("Could not allocate message.");
3331 if (!dbus_message_append_args(m,
3332 DBUS_TYPE_STRING, args + i,
3333 DBUS_TYPE_INVALID)) {
3334 log_error("Could not append arguments to message.");
3339 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3340 log_error("Failed to issue method call: %s", bus_error_message(&error));
3345 dbus_message_unref(m);
3346 dbus_message_unref(reply);
3354 dbus_message_unref(m);
3357 dbus_message_unref(reply);
3359 dbus_error_free(&error);
3364 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3365 DBusMessage *m = NULL, *reply = NULL;
3367 DBusMessageIter iter, sub, sub2;
3370 *interface = "org.freedesktop.systemd1.Manager",
3371 *property = "Environment";
3373 dbus_error_init(&error);
3377 if (!(m = dbus_message_new_method_call(
3378 "org.freedesktop.systemd1",
3379 "/org/freedesktop/systemd1",
3380 "org.freedesktop.DBus.Properties",
3382 log_error("Could not allocate message.");
3386 if (!dbus_message_append_args(m,
3387 DBUS_TYPE_STRING, &interface,
3388 DBUS_TYPE_STRING, &property,
3389 DBUS_TYPE_INVALID)) {
3390 log_error("Could not append arguments to message.");
3395 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3396 log_error("Failed to issue method call: %s", bus_error_message(&error));
3401 if (!dbus_message_iter_init(reply, &iter) ||
3402 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3403 log_error("Failed to parse reply.");
3408 dbus_message_iter_recurse(&iter, &sub);
3410 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3411 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3412 log_error("Failed to parse reply.");
3417 dbus_message_iter_recurse(&sub, &sub2);
3419 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3422 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3423 log_error("Failed to parse reply.");
3428 dbus_message_iter_get_basic(&sub2, &text);
3429 printf("%s\n", text);
3431 dbus_message_iter_next(&sub2);
3438 dbus_message_unref(m);
3441 dbus_message_unref(reply);
3443 dbus_error_free(&error);
3448 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3449 DBusMessage *m = NULL, *reply = NULL;
3453 DBusMessageIter iter, sub;
3456 dbus_error_init(&error);
3458 method = streq(args[0], "set-environment")
3460 : "UnsetEnvironment";
3462 if (!(m = dbus_message_new_method_call(
3463 "org.freedesktop.systemd1",
3464 "/org/freedesktop/systemd1",
3465 "org.freedesktop.systemd1.Manager",
3468 log_error("Could not allocate message.");
3472 dbus_message_iter_init_append(m, &iter);
3474 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3475 log_error("Could not append arguments to message.");
3480 for (i = 1; i < n; i++)
3481 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3482 log_error("Could not append arguments to message.");
3487 if (!dbus_message_iter_close_container(&iter, &sub)) {
3488 log_error("Could not append arguments to message.");
3493 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3494 log_error("Failed to issue method call: %s", bus_error_message(&error));
3503 dbus_message_unref(m);
3506 dbus_message_unref(reply);
3508 dbus_error_free(&error);
3521 static Hashmap *will_install = NULL, *have_installed = NULL;
3522 static Set *remove_symlinks_to = NULL;
3523 static unsigned n_symlinks = 0;
3525 static void install_info_free(InstallInfo *i) {
3530 strv_free(i->aliases);
3531 strv_free(i->wanted_by);
3535 static void install_info_hashmap_free(Hashmap *m) {
3538 while ((i = hashmap_steal_first(m)))
3539 install_info_free(i);
3544 static int install_info_add(const char *name) {
3548 assert(will_install);
3550 if (!unit_name_is_valid_no_type(name, true)) {
3551 log_warning("Unit name %s is not a valid unit name.", name);
3555 if (hashmap_get(have_installed, name) ||
3556 hashmap_get(will_install, name))
3559 if (!(i = new0(InstallInfo, 1))) {
3564 if (!(i->name = strdup(name))) {
3569 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3576 install_info_free(i);
3581 static int config_parse_also(
3582 const char *filename,
3584 const char *section,
3598 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3602 if (!(n = strndup(w, l)))
3605 if ((r = install_info_add(n)) < 0) {
3606 log_warning("Cannot install unit %s: %s", n, strerror(-r));
3617 static int mark_symlink_for_removal(const char *p) {
3622 assert(path_is_absolute(p));
3624 if (!remove_symlinks_to)
3627 if (!(n = strdup(p)))
3630 path_kill_slashes(n);
3632 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3634 return r == -EEXIST ? 0 : r;
3640 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3649 if (!(d = fdopendir(fd))) {
3650 close_nointr_nofail(fd);
3656 while ((de = readdir(d))) {
3657 bool is_dir = false, is_link = false;
3659 if (ignore_file(de->d_name))
3662 if (de->d_type == DT_LNK)
3664 else if (de->d_type == DT_DIR)
3666 else if (de->d_type == DT_UNKNOWN) {
3669 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3670 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3677 is_link = S_ISLNK(st.st_mode);
3678 is_dir = S_ISDIR(st.st_mode);
3686 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3687 log_error("Failed to open %s/%s: %m", root, de->d_name);
3694 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3695 log_error("Failed to allocate directory string.");
3696 close_nointr_nofail(nfd);
3701 /* This will close nfd, regardless whether it succeeds or not */
3702 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3708 } else if (is_link) {
3712 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3713 log_error("Failed to allocate symlink string.");
3718 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3719 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3727 if ((c = canonicalize_file_name(dest))) {
3728 /* This might fail if the destination
3729 * is already removed */
3735 path_kill_slashes(dest);
3736 if (set_get(remove_symlinks_to, dest)) {
3739 log_info("rm '%s'", p);
3741 if (unlink(p) < 0) {
3742 log_error("Cannot unlink symlink %s: %m", p);
3747 rmdir_parents(p, config_path);
3748 path_kill_slashes(p);
3750 if (!set_get(remove_symlinks_to, p)) {
3752 if ((r = mark_symlink_for_removal(p)) < 0) {
3771 static int remove_marked_symlinks(const char *config_path) {
3775 assert(config_path);
3777 if (set_size(remove_symlinks_to) <= 0)
3780 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3787 if ((cfd = dup(fd)) < 0) {
3792 /* This takes possession of cfd and closes it */
3793 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3799 close_nointr_nofail(fd);
3804 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3811 if (streq(verb, "enable")) {
3814 mkdir_parents(new_path, 0755);
3816 if (symlink(old_path, new_path) >= 0) {
3819 log_info("ln -s '%s' '%s'", old_path, new_path);
3824 if (errno != EEXIST) {
3825 log_error("Cannot link %s to %s: %m", old_path, new_path);
3829 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3831 if (errno == EINVAL) {
3832 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3836 log_error("readlink() failed: %s", strerror(-r));
3840 if (streq(dest, old_path)) {
3846 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3855 log_info("ln -s '%s' '%s'", old_path, new_path);
3857 if (symlink(old_path, new_path) >= 0)
3860 log_error("Cannot link %s to %s: %m", old_path, new_path);
3863 } else if (streq(verb, "disable")) {
3866 if ((r = mark_symlink_for_removal(old_path)) < 0)
3869 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3870 if (errno == ENOENT)
3873 if (errno == EINVAL) {
3874 log_warning("File %s not a symlink, ignoring.", old_path);
3878 log_error("readlink() failed: %s", strerror(-r));
3882 if (!streq(dest, old_path)) {
3883 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3890 if ((r = mark_symlink_for_removal(new_path)) < 0)
3894 log_info("rm '%s'", new_path);
3896 if (unlink(new_path) >= 0)
3899 log_error("Cannot unlink %s: %m", new_path);
3902 } else if (streq(verb, "is-enabled")) {
3905 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3907 if (errno == ENOENT || errno == EINVAL)
3910 log_error("readlink() failed: %s", strerror(-r));
3914 if (streq(dest, old_path)) {
3922 assert_not_reached("Unknown action.");
3925 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3927 char *alias_path = NULL;
3932 assert(config_path);
3934 STRV_FOREACH(s, i->aliases) {
3937 if (!(alias_path = path_make_absolute(*s, config_path))) {
3938 log_error("Out of memory");
3943 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3946 if (streq(verb, "disable"))
3947 rmdir_parents(alias_path, config_path);
3957 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3959 char *alias_path = NULL;
3964 assert(config_path);
3966 STRV_FOREACH(s, i->wanted_by) {
3967 if (!unit_name_is_valid_no_type(*s, true)) {
3968 log_error("Invalid name %s.", *s);
3976 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3977 log_error("Out of memory");
3982 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3985 if (streq(verb, "disable"))
3986 rmdir_parents(alias_path, config_path);
3997 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3999 const ConfigItem items[] = {
4000 { "Alias", config_parse_strv, &i->aliases, "Install" },
4001 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
4002 { "Also", config_parse_also, NULL, "Install" },
4004 { NULL, NULL, NULL, NULL }
4008 char *filename = NULL;
4015 STRV_FOREACH(p, paths->unit_path) {
4018 if (!(filename = path_make_absolute(i->name, *p))) {
4019 log_error("Out of memory");
4023 /* Ensure that we don't follow symlinks */
4024 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
4025 if ((f = fdopen(fd, "re")))
4028 if (errno == ELOOP) {
4029 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
4034 if (errno != ENOENT) {
4035 log_error("Failed to open %s: %m", filename);
4045 #if (defined(TARGET_FEDORA) || defined(TARGET_MANDRIVA)) && defined (HAVE_SYSV_COMPAT)
4047 if (endswith(i->name, ".service")) {
4051 if (asprintf(&sysv, SYSTEM_SYSVINIT_PATH "/%s", i->name) < 0) {
4052 log_error("Out of memory");
4056 sysv[strlen(sysv) - sizeof(".service") + 1] = 0;
4057 exists = access(sysv, F_OK) >= 0;
4063 const char *argv[] = {
4070 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", i->name);
4072 argv[1] = file_name_from_path(sysv);
4074 streq(verb, "enable") ? "on" :
4075 streq(verb, "disable") ? "off" : "--level=3";
4077 log_info("Executing %s %s %s", argv[0], argv[1], strempty(argv[2]));
4079 if ((pid = fork()) < 0) {
4080 log_error("Failed to fork: %m");
4083 } else if (pid == 0) {
4084 execv(argv[0], (char**) argv);
4085 _exit(EXIT_FAILURE);
4090 if ((r = wait_for_terminate(pid, &status)) < 0)
4093 if (status.si_code == CLD_EXITED) {
4095 if (streq(verb, "is-enabled"))
4096 return status.si_status == 0 ? 1 : 0;
4098 if (status.si_status == 0)
4101 return status.si_status == 0 ? 0 : -EINVAL;
4112 log_error("Couldn't find %s.", i->name);
4118 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
4123 n_symlinks += strv_length(i->aliases);
4124 n_symlinks += strv_length(i->wanted_by);
4128 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
4131 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
4134 if ((r = mark_symlink_for_removal(filename)) < 0)
4137 if ((r = remove_marked_symlinks(config_path)) < 0)
4143 static char *get_config_path(void) {
4145 if (arg_user && arg_global)
4146 return strdup(USER_CONFIG_UNIT_PATH);
4151 if (user_config_home(&p) < 0)
4157 return strdup(SYSTEM_CONFIG_UNIT_PATH);
4160 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
4164 char *config_path = NULL;
4167 const char *verb = args[0];
4169 dbus_error_init(&error);
4172 if ((r = lookup_paths_init(&paths, arg_user ? MANAGER_USER : MANAGER_SYSTEM)) < 0) {
4173 log_error("Failed to determine lookup paths: %s", strerror(-r));
4177 if (!(config_path = get_config_path())) {
4178 log_error("Failed to determine config path");
4183 will_install = hashmap_new(string_hash_func, string_compare_func);
4184 have_installed = hashmap_new(string_hash_func, string_compare_func);
4186 if (!will_install || !have_installed) {
4187 log_error("Failed to allocate unit sets.");
4192 if (!arg_defaults && streq(verb, "disable"))
4193 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
4194 log_error("Failed to allocate symlink sets.");
4199 for (j = 1; j < n; j++)
4200 if ((r = install_info_add(args[j])) < 0) {
4201 log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
4207 while ((i = hashmap_first(will_install))) {
4210 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
4212 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
4220 /* In test mode and found something */
4226 if (streq(verb, "is-enabled"))
4227 r = r > 0 ? 0 : -ENOENT;
4229 if (n_symlinks <= 0)
4230 log_warning("Unit files contain no applicable installation information. Ignoring.");
4233 /* Don't try to reload anything if the user asked us to not do this */
4235 /* Don't try to reload anything when updating a unit globally */
4237 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
4238 (arg_user || sd_booted() > 0) &&
4239 /* Don't try to reload anything if we are running in a chroot environment */
4240 (arg_user || running_in_chroot() <= 0) ) {
4243 if ((q = daemon_reload(bus, args, n)) < 0)
4249 install_info_hashmap_free(will_install);
4250 install_info_hashmap_free(have_installed);
4252 set_free_free(remove_symlinks_to);
4254 lookup_paths_free(&paths);
4261 static int systemctl_help(void) {
4263 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4264 "Send control commands to or query the systemd manager.\n\n"
4265 " -h --help Show this help\n"
4266 " --version Show package version\n"
4267 " -t --type=TYPE List only units of a particular type\n"
4268 " -p --property=NAME Show only properties by this name\n"
4269 " -a --all Show all units/properties, including dead/empty ones\n"
4270 " --failed Show only failed units\n"
4271 " --full Don't ellipsize unit names on output\n"
4272 " --fail When queueing a new job, fail if conflicting jobs are\n"
4274 " --ignore-dependencies\n"
4275 " When queueing a new job, ignore all its dependencies\n"
4276 " -q --quiet Suppress output\n"
4277 " --no-block Do not wait until operation finished\n"
4278 " --no-pager Do not pipe output into a pager.\n"
4279 " --system Connect to system manager\n"
4280 " --user Connect to user service manager\n"
4281 " --order When generating graph for dot, show only order\n"
4282 " --require When generating graph for dot, show only requirement\n"
4283 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4284 " --global Enable/disable unit files globally\n"
4285 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4287 " --no-ask-password\n"
4288 " Do not ask for system passwords\n"
4289 " --kill-mode=MODE How to send signal\n"
4290 " --kill-who=WHO Who to send signal to\n"
4291 " -s --signal=SIGNAL Which signal to send\n"
4292 " -f --force When enabling unit files, override existing symlinks\n"
4293 " When shutting down, execute action immediately\n"
4294 " --defaults When disabling unit files, remove default symlinks only\n\n"
4296 " list-units List units\n"
4297 " start [NAME...] Start (activate) one or more units\n"
4298 " stop [NAME...] Stop (deactivate) one or more units\n"
4299 " reload [NAME...] Reload one or more units\n"
4300 " restart [NAME...] Start or restart one or more units\n"
4301 " try-restart [NAME...] Restart one or more units if active\n"
4302 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4303 " otherwise start or restart\n"
4304 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4305 " otherwise restart if active\n"
4306 " isolate [NAME] Start one unit and stop all others\n"
4307 " kill [NAME...] Send signal to processes of a unit\n"
4308 " is-active [NAME...] Check whether units are active\n"
4309 " status [NAME...|PID...] Show runtime status of one or more units\n"
4310 " show [NAME...|JOB...] Show properties of one or more\n"
4311 " units/jobs or the manager\n"
4312 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4314 " enable [NAME...] Enable one or more unit files\n"
4315 " disable [NAME...] Disable one or more unit files\n"
4316 " is-enabled [NAME...] Check whether unit files are enabled\n"
4317 " load [NAME...] Load one or more units\n"
4318 " list-jobs List jobs\n"
4319 " cancel [JOB...] Cancel all, one, or more jobs\n"
4320 " monitor Monitor unit/job changes\n"
4321 " dump Dump server status\n"
4322 " dot Dump dependency graph for dot(1)\n"
4323 " snapshot [NAME] Create a snapshot\n"
4324 " delete [NAME...] Remove one or more snapshots\n"
4325 " daemon-reload Reload systemd manager configuration\n"
4326 " daemon-reexec Reexecute systemd manager\n"
4327 " show-environment Dump environment\n"
4328 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4329 " unset-environment [NAME...] Unset one or more environment variables\n"
4330 " default Enter system default mode\n"
4331 " rescue Enter system rescue mode\n"
4332 " emergency Enter system emergency mode\n"
4333 " halt Shut down and halt the system\n"
4334 " poweroff Shut down and power-off the system\n"
4335 " reboot Shut down and reboot the system\n"
4336 " kexec Shut down and reboot the system with kexec\n"
4337 " exit Ask for user instance termination\n",
4338 program_invocation_short_name);
4343 static int halt_help(void) {
4345 printf("%s [OPTIONS...]\n\n"
4346 "%s the system.\n\n"
4347 " --help Show this help\n"
4348 " --halt Halt the machine\n"
4349 " -p --poweroff Switch off the machine\n"
4350 " --reboot Reboot the machine\n"
4351 " -f --force Force immediate halt/power-off/reboot\n"
4352 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4353 " -d --no-wtmp Don't write wtmp record\n"
4354 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4355 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4356 program_invocation_short_name,
4357 arg_action == ACTION_REBOOT ? "Reboot" :
4358 arg_action == ACTION_POWEROFF ? "Power off" :
4364 static int shutdown_help(void) {
4366 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4367 "Shut down the system.\n\n"
4368 " --help Show this help\n"
4369 " -H --halt Halt the machine\n"
4370 " -P --poweroff Power-off the machine\n"
4371 " -r --reboot Reboot the machine\n"
4372 " -h Equivalent to --poweroff, overriden by --halt\n"
4373 " -k Don't halt/power-off/reboot, just send warnings\n"
4374 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4375 " -c Cancel a pending shutdown\n",
4376 program_invocation_short_name);
4381 static int telinit_help(void) {
4383 printf("%s [OPTIONS...] {COMMAND}\n\n"
4384 "Send control commands to the init daemon.\n\n"
4385 " --help Show this help\n"
4386 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4388 " 0 Power-off the machine\n"
4389 " 6 Reboot the machine\n"
4390 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4391 " 1, s, S Enter rescue mode\n"
4392 " q, Q Reload init daemon configuration\n"
4393 " u, U Reexecute init daemon\n",
4394 program_invocation_short_name);
4399 static int runlevel_help(void) {
4401 printf("%s [OPTIONS...]\n\n"
4402 "Prints the previous and current runlevel of the init system.\n\n"
4403 " --help Show this help\n",
4404 program_invocation_short_name);
4409 static int systemctl_parse_argv(int argc, char *argv[]) {
4413 ARG_IGNORE_DEPENDENCIES,
4428 ARG_NO_ASK_PASSWORD,
4432 static const struct option options[] = {
4433 { "help", no_argument, NULL, 'h' },
4434 { "version", no_argument, NULL, ARG_VERSION },
4435 { "type", required_argument, NULL, 't' },
4436 { "property", required_argument, NULL, 'p' },
4437 { "all", no_argument, NULL, 'a' },
4438 { "failed", no_argument, NULL, ARG_FAILED },
4439 { "full", no_argument, NULL, ARG_FULL },
4440 { "fail", no_argument, NULL, ARG_FAIL },
4441 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4442 { "user", no_argument, NULL, ARG_USER },
4443 { "system", no_argument, NULL, ARG_SYSTEM },
4444 { "global", no_argument, NULL, ARG_GLOBAL },
4445 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4446 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4447 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4448 { "quiet", no_argument, NULL, 'q' },
4449 { "order", no_argument, NULL, ARG_ORDER },
4450 { "require", no_argument, NULL, ARG_REQUIRE },
4451 { "force", no_argument, NULL, 'f' },
4452 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4453 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4454 { "kill-mode", required_argument, NULL, ARG_KILL_MODE },
4455 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4456 { "signal", required_argument, NULL, 's' },
4457 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4458 { NULL, 0, NULL, 0 }
4466 /* Only when running as systemctl we ask for passwords */
4467 arg_ask_password = true;
4469 while ((c = getopt_long(argc, argv, "ht:p:aqfs:", options, NULL)) >= 0) {
4478 puts(PACKAGE_STRING);
4480 puts(SYSTEMD_FEATURES);
4490 if (!(l = strv_append(arg_property, optarg)))
4493 strv_free(arg_property);
4496 /* If the user asked for a particular
4497 * property, show it to him, even if it is
4508 arg_job_mode = "fail";
4511 case ARG_IGNORE_DEPENDENCIES:
4512 arg_job_mode = "ignore-dependencies";
4524 arg_no_block = true;
4528 arg_no_pager = true;
4536 arg_dot = DOT_ORDER;
4540 arg_dot = DOT_REQUIRE;
4560 arg_no_reload = true;
4569 arg_defaults = true;
4573 arg_kill_who = optarg;
4577 arg_kill_mode = optarg;
4581 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4582 log_error("Failed to parse signal string %s.", optarg);
4587 case ARG_NO_ASK_PASSWORD:
4588 arg_ask_password = false;
4595 log_error("Unknown option code %c", c);
4603 static int halt_parse_argv(int argc, char *argv[]) {
4612 static const struct option options[] = {
4613 { "help", no_argument, NULL, ARG_HELP },
4614 { "halt", no_argument, NULL, ARG_HALT },
4615 { "poweroff", no_argument, NULL, 'p' },
4616 { "reboot", no_argument, NULL, ARG_REBOOT },
4617 { "force", no_argument, NULL, 'f' },
4618 { "wtmp-only", no_argument, NULL, 'w' },
4619 { "no-wtmp", no_argument, NULL, 'd' },
4620 { "no-sync", no_argument, NULL, 'n' },
4621 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4622 { NULL, 0, NULL, 0 }
4630 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4631 if (runlevel == '0' || runlevel == '6')
4632 arg_immediate = true;
4634 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4642 arg_action = ACTION_HALT;
4646 if (arg_action != ACTION_REBOOT)
4647 arg_action = ACTION_POWEROFF;
4651 arg_action = ACTION_REBOOT;
4655 arg_immediate = true;
4676 /* Compatibility nops */
4683 log_error("Unknown option code %c", c);
4688 if (optind < argc) {
4689 log_error("Too many arguments.");
4696 static int parse_time_spec(const char *t, usec_t *_u) {
4700 if (streq(t, "now"))
4702 else if (t[0] == '+') {
4705 if (safe_atou64(t + 1, &u) < 0)
4708 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4717 hour = strtol(t, &e, 10);
4718 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4721 minute = strtol(e+1, &e, 10);
4722 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4725 n = now(CLOCK_REALTIME);
4726 s = (time_t) (n / USEC_PER_SEC);
4729 assert_se(localtime_r(&s, &tm));
4731 tm.tm_hour = (int) hour;
4732 tm.tm_min = (int) minute;
4735 assert_se(s = mktime(&tm));
4737 *_u = (usec_t) s * USEC_PER_SEC;
4740 *_u += USEC_PER_DAY;
4746 static bool kexec_loaded(void) {
4747 bool loaded = false;
4750 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4758 static int shutdown_parse_argv(int argc, char *argv[]) {
4765 static const struct option options[] = {
4766 { "help", no_argument, NULL, ARG_HELP },
4767 { "halt", no_argument, NULL, 'H' },
4768 { "poweroff", no_argument, NULL, 'P' },
4769 { "reboot", no_argument, NULL, 'r' },
4770 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4771 { NULL, 0, NULL, 0 }
4779 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4787 arg_action = ACTION_HALT;
4791 arg_action = ACTION_POWEROFF;
4796 arg_action = ACTION_KEXEC;
4798 arg_action = ACTION_REBOOT;
4802 if (arg_action != ACTION_HALT)
4803 arg_action = ACTION_POWEROFF;
4816 /* Compatibility nops */
4820 arg_action = ACTION_CANCEL_SHUTDOWN;
4827 log_error("Unknown option code %c", c);
4832 if (argc > optind) {
4833 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4834 log_error("Failed to parse time specification: %s", argv[optind]);
4838 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4840 /* We skip the time argument */
4841 if (argc > optind + 1)
4842 arg_wall = argv + optind + 1;
4849 static int telinit_parse_argv(int argc, char *argv[]) {
4856 static const struct option options[] = {
4857 { "help", no_argument, NULL, ARG_HELP },
4858 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4859 { NULL, 0, NULL, 0 }
4862 static const struct {
4866 { '0', ACTION_POWEROFF },
4867 { '6', ACTION_REBOOT },
4868 { '1', ACTION_RESCUE },
4869 { '2', ACTION_RUNLEVEL2 },
4870 { '3', ACTION_RUNLEVEL3 },
4871 { '4', ACTION_RUNLEVEL4 },
4872 { '5', ACTION_RUNLEVEL5 },
4873 { 's', ACTION_RESCUE },
4874 { 'S', ACTION_RESCUE },
4875 { 'q', ACTION_RELOAD },
4876 { 'Q', ACTION_RELOAD },
4877 { 'u', ACTION_REEXEC },
4878 { 'U', ACTION_REEXEC }
4887 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4902 log_error("Unknown option code %c", c);
4907 if (optind >= argc) {
4912 if (optind + 1 < argc) {
4913 log_error("Too many arguments.");
4917 if (strlen(argv[optind]) != 1) {
4918 log_error("Expected single character argument.");
4922 for (i = 0; i < ELEMENTSOF(table); i++)
4923 if (table[i].from == argv[optind][0])
4926 if (i >= ELEMENTSOF(table)) {
4927 log_error("Unknown command %s.", argv[optind]);
4931 arg_action = table[i].to;
4938 static int runlevel_parse_argv(int argc, char *argv[]) {
4944 static const struct option options[] = {
4945 { "help", no_argument, NULL, ARG_HELP },
4946 { NULL, 0, NULL, 0 }
4954 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4965 log_error("Unknown option code %c", c);
4970 if (optind < argc) {
4971 log_error("Too many arguments.");
4978 static int parse_argv(int argc, char *argv[]) {
4982 if (program_invocation_short_name) {
4984 if (strstr(program_invocation_short_name, "halt")) {
4985 arg_action = ACTION_HALT;
4986 return halt_parse_argv(argc, argv);
4987 } else if (strstr(program_invocation_short_name, "poweroff")) {
4988 arg_action = ACTION_POWEROFF;
4989 return halt_parse_argv(argc, argv);
4990 } else if (strstr(program_invocation_short_name, "reboot")) {
4992 arg_action = ACTION_KEXEC;
4994 arg_action = ACTION_REBOOT;
4995 return halt_parse_argv(argc, argv);
4996 } else if (strstr(program_invocation_short_name, "shutdown")) {
4997 arg_action = ACTION_POWEROFF;
4998 return shutdown_parse_argv(argc, argv);
4999 } else if (strstr(program_invocation_short_name, "init")) {
5001 if (sd_booted() > 0) {
5002 arg_action = ACTION_INVALID;
5003 return telinit_parse_argv(argc, argv);
5005 /* Hmm, so some other init system is
5006 * running, we need to forward this
5007 * request to it. For now we simply
5008 * guess that it is Upstart. */
5010 execv("/lib/upstart/telinit", argv);
5012 log_error("Couldn't find an alternative telinit implementation to spawn.");
5016 } else if (strstr(program_invocation_short_name, "runlevel")) {
5017 arg_action = ACTION_RUNLEVEL;
5018 return runlevel_parse_argv(argc, argv);
5022 arg_action = ACTION_SYSTEMCTL;
5023 return systemctl_parse_argv(argc, argv);
5026 static int action_to_runlevel(void) {
5028 static const char table[_ACTION_MAX] = {
5029 [ACTION_HALT] = '0',
5030 [ACTION_POWEROFF] = '0',
5031 [ACTION_REBOOT] = '6',
5032 [ACTION_RUNLEVEL2] = '2',
5033 [ACTION_RUNLEVEL3] = '3',
5034 [ACTION_RUNLEVEL4] = '4',
5035 [ACTION_RUNLEVEL5] = '5',
5036 [ACTION_RESCUE] = '1'
5039 assert(arg_action < _ACTION_MAX);
5041 return table[arg_action];
5044 static int talk_upstart(void) {
5045 DBusMessage *m = NULL, *reply = NULL;
5047 int previous, rl, r;
5049 env1_buf[] = "RUNLEVEL=X",
5050 env2_buf[] = "PREVLEVEL=X";
5051 char *env1 = env1_buf, *env2 = env2_buf;
5052 const char *emit = "runlevel";
5053 dbus_bool_t b_false = FALSE;
5054 DBusMessageIter iter, sub;
5055 DBusConnection *bus;
5057 dbus_error_init(&error);
5059 if (!(rl = action_to_runlevel()))
5062 if (utmp_get_runlevel(&previous, NULL) < 0)
5065 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
5066 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
5071 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
5076 if ((r = bus_check_peercred(bus)) < 0) {
5077 log_error("Failed to verify owner of bus.");
5081 if (!(m = dbus_message_new_method_call(
5082 "com.ubuntu.Upstart",
5083 "/com/ubuntu/Upstart",
5084 "com.ubuntu.Upstart0_6",
5087 log_error("Could not allocate message.");
5092 dbus_message_iter_init_append(m, &iter);
5094 env1_buf[sizeof(env1_buf)-2] = rl;
5095 env2_buf[sizeof(env2_buf)-2] = previous;
5097 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5098 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5099 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5100 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5101 !dbus_message_iter_close_container(&iter, &sub) ||
5102 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5103 log_error("Could not append arguments to message.");
5108 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5110 if (error_is_no_service(&error)) {
5115 log_error("Failed to issue method call: %s", bus_error_message(&error));
5124 dbus_message_unref(m);
5127 dbus_message_unref(reply);
5130 dbus_connection_flush(bus);
5131 dbus_connection_close(bus);
5132 dbus_connection_unref(bus);
5135 dbus_error_free(&error);
5140 static int talk_initctl(void) {
5141 struct init_request request;
5145 if (!(rl = action_to_runlevel()))
5149 request.magic = INIT_MAGIC;
5150 request.sleeptime = 0;
5151 request.cmd = INIT_CMD_RUNLVL;
5152 request.runlevel = rl;
5154 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5156 if (errno == ENOENT)
5159 log_error("Failed to open "INIT_FIFO": %m");
5164 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5165 close_nointr_nofail(fd);
5168 log_error("Failed to write to "INIT_FIFO": %m");
5169 return errno ? -errno : -EIO;
5175 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5177 static const struct {
5185 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
5187 { "list-units", LESS, 1, list_units },
5188 { "list-jobs", EQUAL, 1, list_jobs },
5189 { "clear-jobs", EQUAL, 1, daemon_reload },
5190 { "load", MORE, 2, load_unit },
5191 { "cancel", MORE, 2, cancel_job },
5192 { "start", MORE, 2, start_unit },
5193 { "stop", MORE, 2, start_unit },
5194 { "reload", MORE, 2, start_unit },
5195 { "restart", MORE, 2, start_unit },
5196 { "try-restart", MORE, 2, start_unit },
5197 { "reload-or-restart", MORE, 2, start_unit },
5198 { "reload-or-try-restart", MORE, 2, start_unit },
5199 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5200 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5201 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5202 { "isolate", EQUAL, 2, start_unit },
5203 { "kill", MORE, 2, kill_unit },
5204 { "is-active", MORE, 2, check_unit },
5205 { "check", MORE, 2, check_unit },
5206 { "show", MORE, 1, show },
5207 { "status", MORE, 2, show },
5208 { "monitor", EQUAL, 1, monitor },
5209 { "dump", EQUAL, 1, dump },
5210 { "dot", EQUAL, 1, dot },
5211 { "snapshot", LESS, 2, snapshot },
5212 { "delete", MORE, 2, delete_snapshot },
5213 { "daemon-reload", EQUAL, 1, daemon_reload },
5214 { "daemon-reexec", EQUAL, 1, daemon_reload },
5215 { "show-environment", EQUAL, 1, show_enviroment },
5216 { "set-environment", MORE, 2, set_environment },
5217 { "unset-environment", MORE, 2, set_environment },
5218 { "halt", EQUAL, 1, start_special },
5219 { "poweroff", EQUAL, 1, start_special },
5220 { "reboot", EQUAL, 1, start_special },
5221 { "kexec", EQUAL, 1, start_special },
5222 { "default", EQUAL, 1, start_special },
5223 { "rescue", EQUAL, 1, start_special },
5224 { "emergency", EQUAL, 1, start_special },
5225 { "exit", EQUAL, 1, start_special },
5226 { "reset-failed", MORE, 1, reset_failed },
5227 { "enable", MORE, 2, enable_unit },
5228 { "disable", MORE, 2, enable_unit },
5229 { "is-enabled", MORE, 2, enable_unit }
5239 left = argc - optind;
5242 /* Special rule: no arguments means "list-units" */
5245 if (streq(argv[optind], "help")) {
5250 for (i = 0; i < ELEMENTSOF(verbs); i++)
5251 if (streq(argv[optind], verbs[i].verb))
5254 if (i >= ELEMENTSOF(verbs)) {
5255 log_error("Unknown operation %s", argv[optind]);
5260 switch (verbs[i].argc_cmp) {
5263 if (left != verbs[i].argc) {
5264 log_error("Invalid number of arguments.");
5271 if (left < verbs[i].argc) {
5272 log_error("Too few arguments.");
5279 if (left > verbs[i].argc) {
5280 log_error("Too many arguments.");
5287 assert_not_reached("Unknown comparison operator.");
5290 /* Require a bus connection for all operations but
5292 if (!streq(verbs[i].verb, "enable") &&
5293 !streq(verbs[i].verb, "disable") &&
5295 log_error("Failed to get D-Bus connection: %s", error->message);
5299 return verbs[i].dispatch(bus, argv + optind, left);
5302 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
5304 struct msghdr msghdr;
5306 union sockaddr_union sockaddr;
5307 struct shutdownd_command c;
5315 strncpy(c.wall_message, message, sizeof(c.wall_message));
5317 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
5321 sockaddr.sa.sa_family = AF_UNIX;
5322 sockaddr.un.sun_path[0] = 0;
5323 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
5326 iovec.iov_base = (char*) &c;
5327 iovec.iov_len = sizeof(c);
5330 msghdr.msg_name = &sockaddr;
5331 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
5333 msghdr.msg_iov = &iovec;
5334 msghdr.msg_iovlen = 1;
5336 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5337 close_nointr_nofail(fd);
5341 close_nointr_nofail(fd);
5345 static int reload_with_fallback(DBusConnection *bus) {
5348 /* First, try systemd via D-Bus. */
5349 if (daemon_reload(bus, NULL, 0) > 0)
5353 /* Nothing else worked, so let's try signals */
5354 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5356 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5357 log_error("kill() failed: %m");
5364 static int start_with_fallback(DBusConnection *bus) {
5367 /* First, try systemd via D-Bus. */
5368 if (start_unit(bus, NULL, 0) >= 0)
5372 /* Hmm, talking to systemd via D-Bus didn't work. Then
5373 * let's try to talk to Upstart via D-Bus. */
5374 if (talk_upstart() > 0)
5377 /* Nothing else worked, so let's try
5379 if (talk_initctl() > 0)
5382 log_error("Failed to talk to init daemon.");
5386 warn_wall(arg_action);
5390 static int halt_main(DBusConnection *bus) {
5393 if (geteuid() != 0) {
5394 log_error("Must be root.");
5400 char date[FORMAT_TIMESTAMP_MAX];
5402 m = strv_join(arg_wall, " ");
5403 r = send_shutdownd(arg_when,
5404 arg_action == ACTION_HALT ? 'H' :
5405 arg_action == ACTION_POWEROFF ? 'P' :
5412 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5414 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5415 format_timestamp(date, sizeof(date), arg_when));
5420 if (!arg_dry && !arg_immediate)
5421 return start_with_fallback(bus);
5424 if (sd_booted() > 0)
5425 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5426 else if ((r = utmp_put_shutdown(0)) < 0)
5427 log_warning("Failed to write utmp record: %s", strerror(-r));
5436 /* Make sure C-A-D is handled by the kernel from this
5438 reboot(RB_ENABLE_CAD);
5440 switch (arg_action) {
5443 log_info("Halting.");
5444 reboot(RB_HALT_SYSTEM);
5447 case ACTION_POWEROFF:
5448 log_info("Powering off.");
5449 reboot(RB_POWER_OFF);
5453 log_info("Rebooting.");
5454 reboot(RB_AUTOBOOT);
5458 assert_not_reached("Unknown halt action.");
5461 /* We should never reach this. */
5465 static int runlevel_main(void) {
5466 int r, runlevel, previous;
5468 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5469 printf("unknown\n");
5474 previous <= 0 ? 'N' : previous,
5475 runlevel <= 0 ? 'N' : runlevel);
5480 static void pager_open(void) {
5488 if (!on_tty() || arg_no_pager)
5491 if ((pager = getenv("PAGER")))
5492 if (!*pager || streq(pager, "cat"))
5495 /* Determine and cache number of columns before we spawn the
5496 * pager so that we get the value from the actual tty */
5500 log_error("Failed to create pager pipe: %m");
5504 parent_pid = getpid();
5507 if (pager_pid < 0) {
5508 log_error("Failed to fork pager: %m");
5513 /* In the child start the pager */
5514 if (pager_pid == 0) {
5516 dup2(fd[0], STDIN_FILENO);
5519 setenv("LESS", "FRSX", 0);
5521 /* Make sure the pager goes away when the parent dies */
5522 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5523 _exit(EXIT_FAILURE);
5525 /* Check whether our parent died before we were able
5526 * to set the death signal */
5527 if (getppid() != parent_pid)
5528 _exit(EXIT_SUCCESS);
5531 execlp(pager, pager, NULL);
5532 execl("/bin/sh", "sh", "-c", pager, NULL);
5534 /* Debian's alternatives command for pagers is
5535 * called 'pager'. Note that we do not call
5536 * sensible-pagers here, since that is just a
5537 * shell script that implements a logic that
5538 * is similar to this one anyway, but is
5539 * Debian-specific. */
5540 execlp("pager", "pager", NULL);
5542 execlp("less", "less", NULL);
5543 execlp("more", "more", NULL);
5546 log_error("Unable to execute pager: %m");
5547 _exit(EXIT_FAILURE);
5550 /* Return in the parent */
5551 if (dup2(fd[1], STDOUT_FILENO) < 0)
5552 log_error("Failed to duplicate pager pipe: %m");
5557 static void pager_close(void) {
5563 /* Inform pager that we are done */
5565 kill(pager_pid, SIGCONT);
5566 wait_for_terminate(pager_pid, &dummy);
5570 static void agent_close(void) {
5576 /* Inform agent that we are done */
5577 kill(agent_pid, SIGTERM);
5578 kill(agent_pid, SIGCONT);
5579 wait_for_terminate(agent_pid, &dummy);
5583 int main(int argc, char*argv[]) {
5584 int r, retval = EXIT_FAILURE;
5585 DBusConnection *bus = NULL;
5588 dbus_error_init(&error);
5590 log_parse_environment();
5593 if ((r = parse_argv(argc, argv)) < 0)
5596 retval = EXIT_SUCCESS;
5600 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5601 * let's shortcut this */
5602 if (arg_action == ACTION_RUNLEVEL) {
5603 r = runlevel_main();
5604 retval = r < 0 ? EXIT_FAILURE : r;
5608 bus_connect(arg_user ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5610 switch (arg_action) {
5612 case ACTION_SYSTEMCTL:
5613 r = systemctl_main(bus, argc, argv, &error);
5617 case ACTION_POWEROFF:
5623 case ACTION_RUNLEVEL2:
5624 case ACTION_RUNLEVEL3:
5625 case ACTION_RUNLEVEL4:
5626 case ACTION_RUNLEVEL5:
5628 case ACTION_EMERGENCY:
5629 case ACTION_DEFAULT:
5630 r = start_with_fallback(bus);
5635 r = reload_with_fallback(bus);
5638 case ACTION_CANCEL_SHUTDOWN:
5639 r = send_shutdownd(0, 0, false, NULL);
5642 case ACTION_INVALID:
5643 case ACTION_RUNLEVEL:
5645 assert_not_reached("Unknown action");
5648 retval = r < 0 ? EXIT_FAILURE : r;
5653 dbus_connection_flush(bus);
5654 dbus_connection_close(bus);
5655 dbus_connection_unref(bus);
5658 dbus_error_free(&error);
5662 strv_free(arg_property);