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 bool arg_fail = false;
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 char **arg_wall = NULL;
80 static const char *arg_kill_who = NULL;
81 static const char *arg_kill_mode = NULL;
82 static int arg_signal = SIGTERM;
83 static usec_t arg_when = 0;
102 ACTION_CANCEL_SHUTDOWN,
104 } arg_action = ACTION_SYSTEMCTL;
111 static bool private_bus = false;
113 static pid_t pager_pid = 0;
115 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
116 static void pager_open(void);
118 static bool on_tty(void) {
121 /* Note that this is invoked relatively early, before we start
122 * the pager. That means the value we return reflects whether
123 * we originally were started on a tty, not if we currently
124 * are. But this is intended, since we want colour and so on
125 * when run in our own pager. */
127 if (_unlikely_(t < 0))
128 t = isatty(STDOUT_FILENO) > 0;
133 static void spawn_ask_password_agent(void) {
136 /* We check STDIN here, not STDOUT, since this is about input,
138 if (!isatty(STDIN_FILENO))
141 if (!arg_ask_password)
149 /* Spawns a temporary TTY agent, making sure it goes away when
152 if ((child = fork()) < 0)
157 const char * const args[] = {
158 SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH,
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 execv(args[0], (char **) args);
209 static const char *ansi_highlight(bool b) {
214 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
217 static const char *ansi_highlight_green(bool b) {
222 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
225 static bool error_is_no_service(const DBusError *error) {
228 if (!dbus_error_is_set(error))
231 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
234 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
237 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
240 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
243 if (!dbus_error_is_set(error))
246 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
247 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
248 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
249 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
250 return EXIT_NOPERMISSION;
252 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
253 return EXIT_NOTINSTALLED;
255 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
256 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
257 return EXIT_NOTIMPLEMENTED;
259 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
260 return EXIT_NOTCONFIGURED;
268 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
273 if (dbus_message_iter_get_arg_type(iter) != type)
276 dbus_message_iter_get_basic(iter, data);
278 if (!dbus_message_iter_next(iter) != !next)
284 static void warn_wall(enum action action) {
285 static const char *table[_ACTION_MAX] = {
286 [ACTION_HALT] = "The system is going down for system halt NOW!",
287 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
288 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
289 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
290 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
291 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
300 if (!(p = strv_join(arg_wall, " "))) {
301 log_error("Failed to join strings.");
317 utmp_wall(table[action], NULL);
322 const char *description;
323 const char *load_state;
324 const char *active_state;
325 const char *sub_state;
326 const char *following;
327 const char *unit_path;
329 const char *job_type;
330 const char *job_path;
333 static int compare_unit_info(const void *a, const void *b) {
335 const struct unit_info *u = a, *v = b;
337 d1 = strrchr(u->id, '.');
338 d2 = strrchr(v->id, '.');
343 if ((r = strcasecmp(d1, d2)) != 0)
347 return strcasecmp(u->id, v->id);
350 static bool output_show_job(const struct unit_info *u) {
353 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
354 streq(dot+1, arg_type))) &&
355 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0);
358 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
359 unsigned active_len, sub_len, job_len, n_shown = 0;
360 const struct unit_info *u;
362 active_len = sizeof("ACTIVE")-1;
363 sub_len = sizeof("SUB")-1;
364 job_len = sizeof("JOB")-1;
366 for (u = unit_infos; u < unit_infos + c; u++) {
367 if (!output_show_job(u))
370 active_len = MAX(active_len, strlen(u->active_state));
371 sub_len = MAX(sub_len, strlen(u->sub_state));
373 job_len = MAX(job_len, strlen(u->job_type));
377 printf("%-25s %-6s %-*s %-*s %-*s", "UNIT", "LOAD",
378 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
379 if (columns() >= 80+12 || arg_full)
380 printf(" %s\n", "DESCRIPTION");
385 for (u = unit_infos; u < unit_infos + c; u++) {
388 const char *on_loaded, *off_loaded;
389 const char *on_active, *off_active;
391 if (!output_show_job(u))
396 if (!streq(u->load_state, "loaded") &&
397 !streq(u->load_state, "banned")) {
398 on_loaded = ansi_highlight(true);
399 off_loaded = ansi_highlight(false);
401 on_loaded = off_loaded = "";
403 if (streq(u->active_state, "failed")) {
404 on_active = ansi_highlight(true);
405 off_active = ansi_highlight(false);
407 on_active = off_active = "";
409 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
411 printf("%-25s %s%-6s%s %s%-*s %-*s%s%n",
413 on_loaded, u->load_state, off_loaded,
414 on_active, active_len, u->active_state,
415 sub_len, u->sub_state, off_active,
420 a -= strlen(on_loaded) + strlen(off_loaded);
421 a -= strlen(on_active) + strlen(off_active);
424 printf(" %-*s", job_len, u->job_type);
428 if (a + b + 1 < columns()) {
430 printf(" %-*s", job_len, "");
433 printf(" %s", u->description);
435 printf(" %.*s", columns() - a - b - 1, u->description);
442 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
443 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
444 "SUB = The low-level unit activation state, values depend on unit type.\n"
445 "JOB = Pending job for the unit.\n");
448 printf("\n%u units listed.\n", n_shown);
450 printf("\n%u units listed. Pass --all to see inactive units, too.\n", n_shown);
454 static int list_units(DBusConnection *bus, char **args, unsigned n) {
455 DBusMessage *m = NULL, *reply = NULL;
458 DBusMessageIter iter, sub, sub2;
459 unsigned c = 0, n_units = 0;
460 struct unit_info *unit_infos = NULL;
462 dbus_error_init(&error);
468 if (!(m = dbus_message_new_method_call(
469 "org.freedesktop.systemd1",
470 "/org/freedesktop/systemd1",
471 "org.freedesktop.systemd1.Manager",
473 log_error("Could not allocate message.");
477 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
478 log_error("Failed to issue method call: %s", bus_error_message(&error));
483 if (!dbus_message_iter_init(reply, &iter) ||
484 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
485 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
486 log_error("Failed to parse reply.");
491 dbus_message_iter_recurse(&iter, &sub);
493 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
496 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
497 log_error("Failed to parse reply.");
505 n_units = MAX(2*c, 16);
506 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
509 log_error("Failed to allocate unit array.");
519 dbus_message_iter_recurse(&sub, &sub2);
521 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
522 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
523 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
524 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
525 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
526 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
527 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
528 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
529 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
530 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
531 log_error("Failed to parse reply.");
536 dbus_message_iter_next(&sub);
541 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
542 output_units_list(unit_infos, c);
549 dbus_message_unref(m);
552 dbus_message_unref(reply);
556 dbus_error_free(&error);
561 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
562 static const char * const colors[] = {
563 "Requires", "[color=\"black\"]",
564 "RequiresOverridable", "[color=\"black\"]",
565 "Requisite", "[color=\"darkblue\"]",
566 "RequisiteOverridable", "[color=\"darkblue\"]",
567 "Wants", "[color=\"darkgrey\"]",
568 "Conflicts", "[color=\"red\"]",
569 "ConflictedBy", "[color=\"red\"]",
570 "After", "[color=\"green\"]"
573 const char *c = NULL;
580 for (i = 0; i < ELEMENTSOF(colors); i += 2)
581 if (streq(colors[i], prop)) {
589 if (arg_dot != DOT_ALL)
590 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
593 switch (dbus_message_iter_get_arg_type(iter)) {
595 case DBUS_TYPE_ARRAY:
597 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
600 dbus_message_iter_recurse(iter, &sub);
602 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
605 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
606 dbus_message_iter_get_basic(&sub, &s);
607 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
609 dbus_message_iter_next(&sub);
619 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
620 DBusMessage *m = NULL, *reply = NULL;
621 const char *interface = "org.freedesktop.systemd1.Unit";
624 DBusMessageIter iter, sub, sub2, sub3;
629 dbus_error_init(&error);
631 if (!(m = dbus_message_new_method_call(
632 "org.freedesktop.systemd1",
634 "org.freedesktop.DBus.Properties",
636 log_error("Could not allocate message.");
641 if (!dbus_message_append_args(m,
642 DBUS_TYPE_STRING, &interface,
643 DBUS_TYPE_INVALID)) {
644 log_error("Could not append arguments to message.");
649 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
650 log_error("Failed to issue method call: %s", bus_error_message(&error));
655 if (!dbus_message_iter_init(reply, &iter) ||
656 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
657 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
658 log_error("Failed to parse reply.");
663 dbus_message_iter_recurse(&iter, &sub);
665 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
668 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
669 log_error("Failed to parse reply.");
674 dbus_message_iter_recurse(&sub, &sub2);
676 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
677 log_error("Failed to parse reply.");
682 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
683 log_error("Failed to parse reply.");
688 dbus_message_iter_recurse(&sub2, &sub3);
690 if (dot_one_property(name, prop, &sub3)) {
691 log_error("Failed to parse reply.");
696 dbus_message_iter_next(&sub);
703 dbus_message_unref(m);
706 dbus_message_unref(reply);
708 dbus_error_free(&error);
713 static int dot(DBusConnection *bus, char **args, unsigned n) {
714 DBusMessage *m = NULL, *reply = NULL;
717 DBusMessageIter iter, sub, sub2;
719 dbus_error_init(&error);
723 if (!(m = dbus_message_new_method_call(
724 "org.freedesktop.systemd1",
725 "/org/freedesktop/systemd1",
726 "org.freedesktop.systemd1.Manager",
728 log_error("Could not allocate message.");
732 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
733 log_error("Failed to issue method call: %s", bus_error_message(&error));
738 if (!dbus_message_iter_init(reply, &iter) ||
739 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
740 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
741 log_error("Failed to parse reply.");
746 printf("digraph systemd {\n");
748 dbus_message_iter_recurse(&iter, &sub);
749 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
750 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
752 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
753 log_error("Failed to parse reply.");
758 dbus_message_iter_recurse(&sub, &sub2);
760 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
761 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
762 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
763 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
764 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
765 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
766 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
767 log_error("Failed to parse reply.");
772 if ((r = dot_one(bus, id, unit_path)) < 0)
775 /* printf("\t\"%s\";\n", id); */
776 dbus_message_iter_next(&sub);
781 log_info(" Color legend: black = Requires\n"
782 " dark blue = Requisite\n"
783 " dark grey = Wants\n"
787 if (isatty(fileno(stdout)))
788 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
789 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
795 dbus_message_unref(m);
798 dbus_message_unref(reply);
800 dbus_error_free(&error);
805 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
806 DBusMessage *m = NULL, *reply = NULL;
809 DBusMessageIter iter, sub, sub2;
812 dbus_error_init(&error);
818 if (!(m = dbus_message_new_method_call(
819 "org.freedesktop.systemd1",
820 "/org/freedesktop/systemd1",
821 "org.freedesktop.systemd1.Manager",
823 log_error("Could not allocate message.");
827 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
828 log_error("Failed to issue method call: %s", bus_error_message(&error));
833 if (!dbus_message_iter_init(reply, &iter) ||
834 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
835 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
836 log_error("Failed to parse reply.");
841 dbus_message_iter_recurse(&iter, &sub);
843 if (isatty(STDOUT_FILENO))
844 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
846 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
847 const char *name, *type, *state, *job_path, *unit_path;
851 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
852 log_error("Failed to parse reply.");
857 dbus_message_iter_recurse(&sub, &sub2);
859 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
860 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
861 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
862 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
863 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
864 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
865 log_error("Failed to parse reply.");
870 e = arg_full ? NULL : ellipsize(name, 25, 33);
871 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
876 dbus_message_iter_next(&sub);
879 if (isatty(STDOUT_FILENO))
880 printf("\n%u jobs listed.\n", k);
886 dbus_message_unref(m);
889 dbus_message_unref(reply);
891 dbus_error_free(&error);
896 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
897 DBusMessage *m = NULL, *reply = NULL;
902 dbus_error_init(&error);
907 for (i = 1; i < n; i++) {
909 if (!(m = dbus_message_new_method_call(
910 "org.freedesktop.systemd1",
911 "/org/freedesktop/systemd1",
912 "org.freedesktop.systemd1.Manager",
914 log_error("Could not allocate message.");
919 if (!dbus_message_append_args(m,
920 DBUS_TYPE_STRING, &args[i],
921 DBUS_TYPE_INVALID)) {
922 log_error("Could not append arguments to message.");
927 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
928 log_error("Failed to issue method call: %s", bus_error_message(&error));
933 dbus_message_unref(m);
934 dbus_message_unref(reply);
943 dbus_message_unref(m);
946 dbus_message_unref(reply);
948 dbus_error_free(&error);
953 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
954 DBusMessage *m = NULL, *reply = NULL;
959 dbus_error_init(&error);
965 return daemon_reload(bus, args, n);
967 for (i = 1; i < n; i++) {
971 if (!(m = dbus_message_new_method_call(
972 "org.freedesktop.systemd1",
973 "/org/freedesktop/systemd1",
974 "org.freedesktop.systemd1.Manager",
976 log_error("Could not allocate message.");
981 if ((r = safe_atou(args[i], &id)) < 0) {
982 log_error("Failed to parse job id: %s", strerror(-r));
986 assert_cc(sizeof(uint32_t) == sizeof(id));
987 if (!dbus_message_append_args(m,
988 DBUS_TYPE_UINT32, &id,
989 DBUS_TYPE_INVALID)) {
990 log_error("Could not append arguments to message.");
995 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
996 log_error("Failed to issue method call: %s", bus_error_message(&error));
1001 if (!dbus_message_get_args(reply, &error,
1002 DBUS_TYPE_OBJECT_PATH, &path,
1003 DBUS_TYPE_INVALID)) {
1004 log_error("Failed to parse reply: %s", bus_error_message(&error));
1009 dbus_message_unref(m);
1010 if (!(m = dbus_message_new_method_call(
1011 "org.freedesktop.systemd1",
1013 "org.freedesktop.systemd1.Job",
1015 log_error("Could not allocate message.");
1020 dbus_message_unref(reply);
1021 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1022 log_error("Failed to issue method call: %s", bus_error_message(&error));
1027 dbus_message_unref(m);
1028 dbus_message_unref(reply);
1036 dbus_message_unref(m);
1039 dbus_message_unref(reply);
1041 dbus_error_free(&error);
1046 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1047 DBusMessage *m = NULL, *reply = NULL;
1048 dbus_bool_t b = FALSE;
1049 DBusMessageIter iter, sub;
1051 *interface = "org.freedesktop.systemd1.Unit",
1052 *property = "NeedDaemonReload",
1055 /* We ignore all errors here, since this is used to show a warning only */
1057 if (!(m = dbus_message_new_method_call(
1058 "org.freedesktop.systemd1",
1059 "/org/freedesktop/systemd1",
1060 "org.freedesktop.systemd1.Manager",
1064 if (!dbus_message_append_args(m,
1065 DBUS_TYPE_STRING, &unit,
1069 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1072 if (!dbus_message_get_args(reply, NULL,
1073 DBUS_TYPE_OBJECT_PATH, &path,
1077 dbus_message_unref(m);
1078 if (!(m = dbus_message_new_method_call(
1079 "org.freedesktop.systemd1",
1081 "org.freedesktop.DBus.Properties",
1085 if (!dbus_message_append_args(m,
1086 DBUS_TYPE_STRING, &interface,
1087 DBUS_TYPE_STRING, &property,
1088 DBUS_TYPE_INVALID)) {
1092 dbus_message_unref(reply);
1093 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1096 if (!dbus_message_iter_init(reply, &iter) ||
1097 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1100 dbus_message_iter_recurse(&iter, &sub);
1102 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1105 dbus_message_iter_get_basic(&sub, &b);
1109 dbus_message_unref(m);
1112 dbus_message_unref(reply);
1117 typedef struct WaitData {
1122 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1130 dbus_error_init(&error);
1132 log_debug("Got D-Bus request: %s.%s() on %s",
1133 dbus_message_get_interface(message),
1134 dbus_message_get_member(message),
1135 dbus_message_get_path(message));
1137 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1138 log_error("Warning! D-Bus connection terminated.");
1139 dbus_connection_close(connection);
1141 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1144 dbus_bool_t success = true;
1146 if (!dbus_message_get_args(message, &error,
1147 DBUS_TYPE_UINT32, &id,
1148 DBUS_TYPE_OBJECT_PATH, &path,
1149 DBUS_TYPE_BOOLEAN, &success,
1151 log_error("Failed to parse message: %s", bus_error_message(&error));
1155 if ((p = set_remove(d->set, (char*) path)))
1163 dbus_error_free(&error);
1164 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1167 static int enable_wait_for_jobs(DBusConnection *bus) {
1175 dbus_error_init(&error);
1176 dbus_bus_add_match(bus,
1178 "sender='org.freedesktop.systemd1',"
1179 "interface='org.freedesktop.systemd1.Manager',"
1180 "member='JobRemoved',"
1181 "path='/org/freedesktop/systemd1'",
1184 if (dbus_error_is_set(&error)) {
1185 log_error("Failed to add match: %s", bus_error_message(&error));
1186 dbus_error_free(&error);
1190 /* This is slightly dirty, since we don't undo the match registrations. */
1194 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1205 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1206 log_error("Failed to add filter.");
1211 while (!set_isempty(s) &&
1212 dbus_connection_read_write_dispatch(bus, -1))
1215 if (!arg_quiet && d.failed)
1216 log_error("Job failed. See system logs and 'systemctl status' for details.");
1218 r = d.failed ? -EIO : 0;
1221 /* This is slightly dirty, since we don't undo the filter registration. */
1226 static int start_unit_one(
1227 DBusConnection *bus,
1234 DBusMessage *m = NULL, *reply = NULL;
1243 assert(arg_no_block || s);
1245 if (!(m = dbus_message_new_method_call(
1246 "org.freedesktop.systemd1",
1247 "/org/freedesktop/systemd1",
1248 "org.freedesktop.systemd1.Manager",
1250 log_error("Could not allocate message.");
1255 if (!dbus_message_append_args(m,
1256 DBUS_TYPE_STRING, &name,
1257 DBUS_TYPE_STRING, &mode,
1258 DBUS_TYPE_INVALID)) {
1259 log_error("Could not append arguments to message.");
1264 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1266 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1267 /* There's always a fallback possible for
1268 * legacy actions. */
1273 log_error("Failed to issue method call: %s", bus_error_message(error));
1278 if (!dbus_message_get_args(reply, error,
1279 DBUS_TYPE_OBJECT_PATH, &path,
1280 DBUS_TYPE_INVALID)) {
1281 log_error("Failed to parse reply: %s", bus_error_message(error));
1286 if (need_daemon_reload(bus, name))
1287 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1288 arg_user ? "--user" : "--system");
1290 if (!arg_no_block) {
1293 if (!(p = strdup(path))) {
1294 log_error("Failed to duplicate path.");
1299 if ((r = set_put(s, p)) < 0) {
1301 log_error("Failed to add path to set.");
1310 dbus_message_unref(m);
1313 dbus_message_unref(reply);
1318 static enum action verb_to_action(const char *verb) {
1319 if (streq(verb, "halt"))
1321 else if (streq(verb, "poweroff"))
1322 return ACTION_POWEROFF;
1323 else if (streq(verb, "reboot"))
1324 return ACTION_REBOOT;
1325 else if (streq(verb, "kexec"))
1326 return ACTION_KEXEC;
1327 else if (streq(verb, "rescue"))
1328 return ACTION_RESCUE;
1329 else if (streq(verb, "emergency"))
1330 return ACTION_EMERGENCY;
1331 else if (streq(verb, "default"))
1332 return ACTION_DEFAULT;
1333 else if (streq(verb, "exit"))
1336 return ACTION_INVALID;
1339 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1341 static const char * const table[_ACTION_MAX] = {
1342 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1343 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1344 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1345 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1346 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1347 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1348 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1349 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1350 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1351 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1352 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1353 [ACTION_EXIT] = SPECIAL_EXIT_TARGET
1358 const char *method, *mode, *one_name;
1362 dbus_error_init(&error);
1366 spawn_ask_password_agent();
1368 if (arg_action == ACTION_SYSTEMCTL) {
1370 streq(args[0], "stop") ? "StopUnit" :
1371 streq(args[0], "reload") ? "ReloadUnit" :
1372 streq(args[0], "restart") ? "RestartUnit" :
1373 streq(args[0], "try-restart") ||
1374 streq(args[0], "condrestart") ? "TryRestartUnit" :
1375 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1376 streq(args[0], "reload-or-try-restart") ||
1377 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1381 (streq(args[0], "isolate") ||
1382 streq(args[0], "rescue") ||
1383 streq(args[0], "emergency")) ? "isolate" :
1387 one_name = table[verb_to_action(args[0])];
1390 assert(arg_action < ELEMENTSOF(table));
1391 assert(table[arg_action]);
1393 method = "StartUnit";
1395 mode = (arg_action == ACTION_EMERGENCY ||
1396 arg_action == ACTION_RESCUE ||
1397 arg_action == ACTION_RUNLEVEL2 ||
1398 arg_action == ACTION_RUNLEVEL3 ||
1399 arg_action == ACTION_RUNLEVEL4 ||
1400 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1402 one_name = table[arg_action];
1405 if (!arg_no_block) {
1406 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1407 log_error("Could not watch jobs: %s", strerror(-ret));
1411 if (!(s = set_new(string_hash_func, string_compare_func))) {
1412 log_error("Failed to allocate set.");
1419 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1422 for (i = 1; i < n; i++)
1423 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1424 ret = translate_bus_error_to_exit_status(r, &error);
1425 dbus_error_free(&error);
1430 if ((r = wait_for_jobs(bus, s)) < 0) {
1439 dbus_error_free(&error);
1444 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1451 (streq(args[0], "halt") ||
1452 streq(args[0], "poweroff") ||
1453 streq(args[0], "reboot") ||
1454 streq(args[0], "kexec") ||
1455 streq(args[0], "exit")))
1456 return daemon_reload(bus, args, n);
1458 r = start_unit(bus, args, n);
1461 warn_wall(verb_to_action(args[0]));
1466 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1467 DBusMessage *m = NULL, *reply = NULL;
1469 *interface = "org.freedesktop.systemd1.Unit",
1470 *property = "ActiveState";
1471 int r = 3; /* According to LSB: "program is not running" */
1478 dbus_error_init(&error);
1480 for (i = 1; i < n; i++) {
1481 const char *path = NULL;
1483 DBusMessageIter iter, sub;
1485 if (!(m = dbus_message_new_method_call(
1486 "org.freedesktop.systemd1",
1487 "/org/freedesktop/systemd1",
1488 "org.freedesktop.systemd1.Manager",
1490 log_error("Could not allocate message.");
1495 if (!dbus_message_append_args(m,
1496 DBUS_TYPE_STRING, &args[i],
1497 DBUS_TYPE_INVALID)) {
1498 log_error("Could not append arguments to message.");
1503 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1505 /* Hmm, cannot figure out anything about this unit... */
1509 dbus_error_free(&error);
1510 dbus_message_unref(m);
1514 if (!dbus_message_get_args(reply, &error,
1515 DBUS_TYPE_OBJECT_PATH, &path,
1516 DBUS_TYPE_INVALID)) {
1517 log_error("Failed to parse reply: %s", bus_error_message(&error));
1522 dbus_message_unref(m);
1523 if (!(m = dbus_message_new_method_call(
1524 "org.freedesktop.systemd1",
1526 "org.freedesktop.DBus.Properties",
1528 log_error("Could not allocate message.");
1533 if (!dbus_message_append_args(m,
1534 DBUS_TYPE_STRING, &interface,
1535 DBUS_TYPE_STRING, &property,
1536 DBUS_TYPE_INVALID)) {
1537 log_error("Could not append arguments to message.");
1542 dbus_message_unref(reply);
1543 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1544 log_error("Failed to issue method call: %s", bus_error_message(&error));
1549 if (!dbus_message_iter_init(reply, &iter) ||
1550 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1551 log_error("Failed to parse reply.");
1556 dbus_message_iter_recurse(&iter, &sub);
1558 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1559 log_error("Failed to parse reply.");
1564 dbus_message_iter_get_basic(&sub, &state);
1569 if (streq(state, "active") || streq(state, "reloading"))
1572 dbus_message_unref(m);
1573 dbus_message_unref(reply);
1579 dbus_message_unref(m);
1582 dbus_message_unref(reply);
1584 dbus_error_free(&error);
1589 static int kill_unit(DBusConnection *bus, char **args, unsigned n) {
1590 DBusMessage *m = NULL, *reply = NULL;
1598 dbus_error_init(&error);
1601 arg_kill_who = "all";
1604 arg_kill_mode = streq(arg_kill_who, "all") ? "control-group" : "process";
1606 for (i = 1; i < n; i++) {
1608 if (!(m = dbus_message_new_method_call(
1609 "org.freedesktop.systemd1",
1610 "/org/freedesktop/systemd1",
1611 "org.freedesktop.systemd1.Manager",
1613 log_error("Could not allocate message.");
1618 if (!dbus_message_append_args(m,
1619 DBUS_TYPE_STRING, &args[i],
1620 DBUS_TYPE_STRING, &arg_kill_who,
1621 DBUS_TYPE_STRING, &arg_kill_mode,
1622 DBUS_TYPE_INT32, &arg_signal,
1623 DBUS_TYPE_INVALID)) {
1624 log_error("Could not append arguments to message.");
1629 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1630 log_error("Failed to issue method call: %s", bus_error_message(&error));
1631 dbus_error_free(&error);
1635 dbus_message_unref(m);
1638 dbus_message_unref(reply);
1644 dbus_message_unref(m);
1647 dbus_message_unref(reply);
1649 dbus_error_free(&error);
1654 typedef struct ExecStatusInfo {
1662 usec_t start_timestamp;
1663 usec_t exit_timestamp;
1668 LIST_FIELDS(struct ExecStatusInfo, exec);
1671 static void exec_status_info_free(ExecStatusInfo *i) {
1680 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1681 uint64_t start_timestamp, exit_timestamp;
1682 DBusMessageIter sub2, sub3;
1686 int32_t code, status;
1692 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1695 dbus_message_iter_recurse(sub, &sub2);
1697 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1700 if (!(i->path = strdup(path)))
1703 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1704 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1708 dbus_message_iter_recurse(&sub2, &sub3);
1709 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1710 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1711 dbus_message_iter_next(&sub3);
1716 if (!(i->argv = new0(char*, n+1)))
1720 dbus_message_iter_recurse(&sub2, &sub3);
1721 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1724 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1725 dbus_message_iter_get_basic(&sub3, &s);
1726 dbus_message_iter_next(&sub3);
1728 if (!(i->argv[n++] = strdup(s)))
1732 if (!dbus_message_iter_next(&sub2) ||
1733 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1734 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1735 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1736 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1737 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1738 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1742 i->start_timestamp = (usec_t) start_timestamp;
1743 i->exit_timestamp = (usec_t) exit_timestamp;
1744 i->pid = (pid_t) pid;
1751 typedef struct UnitStatusInfo {
1753 const char *load_state;
1754 const char *active_state;
1755 const char *sub_state;
1757 const char *description;
1758 const char *following;
1761 const char *default_control_group;
1763 usec_t inactive_exit_timestamp;
1764 usec_t active_enter_timestamp;
1765 usec_t active_exit_timestamp;
1766 usec_t inactive_enter_timestamp;
1768 bool need_daemon_reload;
1773 const char *status_text;
1775 #ifdef HAVE_SYSV_COMPAT
1779 usec_t start_timestamp;
1780 usec_t exit_timestamp;
1782 int exit_code, exit_status;
1785 unsigned n_accepted;
1786 unsigned n_connections;
1790 const char *sysfs_path;
1792 /* Mount, Automount */
1798 LIST_HEAD(ExecStatusInfo, exec);
1801 static void print_status_info(UnitStatusInfo *i) {
1803 const char *on, *off, *ss;
1805 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1806 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1810 /* This shows pretty information about a unit. See
1811 * print_property() for a low-level property printer */
1813 printf("%s", strna(i->id));
1815 if (i->description && !streq_ptr(i->id, i->description))
1816 printf(" - %s", i->description);
1821 printf("\t Follow: unit currently follows state of %s\n", i->following);
1823 if (streq_ptr(i->load_state, "failed") ||
1824 streq_ptr(i->load_state, "banned")) {
1825 on = ansi_highlight(true);
1826 off = ansi_highlight(false);
1831 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1833 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1835 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1837 if (streq_ptr(i->active_state, "failed")) {
1838 on = ansi_highlight(true);
1839 off = ansi_highlight(false);
1840 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1841 on = ansi_highlight_green(true);
1842 off = ansi_highlight_green(false);
1847 printf("\t Active: %s%s (%s)%s",
1849 strna(i->active_state),
1853 printf("\t Active: %s%s%s",
1855 strna(i->active_state),
1858 timestamp = (streq_ptr(i->active_state, "active") ||
1859 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1860 (streq_ptr(i->active_state, "inactive") ||
1861 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1862 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1863 i->active_exit_timestamp;
1865 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1866 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1869 printf(" since %s; %s\n", s2, s1);
1871 printf(" since %s\n", s2);
1876 printf("\t Device: %s\n", i->sysfs_path);
1878 printf("\t Where: %s\n", i->where);
1880 printf("\t What: %s\n", i->what);
1883 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1885 LIST_FOREACH(exec, p, i->exec) {
1889 /* Only show exited processes here */
1893 t = strv_join(p->argv, " ");
1894 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
1897 #ifdef HAVE_SYSV_COMPAT
1899 good = is_clean_exit_lsb(p->code, p->status);
1902 good = is_clean_exit(p->code, p->status);
1905 on = ansi_highlight(true);
1906 off = ansi_highlight(false);
1910 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
1912 if (p->code == CLD_EXITED) {
1915 printf("status=%i", p->status);
1917 #ifdef HAVE_SYSV_COMPAT
1918 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1920 if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1925 printf("signal=%s", signal_to_string(p->status));
1927 printf(")%s\n", off);
1931 if (i->main_pid == p->pid &&
1932 i->start_timestamp == p->start_timestamp &&
1933 i->exit_timestamp == p->start_timestamp)
1934 /* Let's not show this twice */
1937 if (p->pid == i->control_pid)
1941 if (i->main_pid > 0 || i->control_pid > 0) {
1944 if (i->main_pid > 0) {
1945 printf("Main PID: %u", (unsigned) i->main_pid);
1949 get_process_name(i->main_pid, &t);
1954 } else if (i->exit_code > 0) {
1955 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1957 if (i->exit_code == CLD_EXITED) {
1960 printf("status=%i", i->exit_status);
1962 #ifdef HAVE_SYSV_COMPAT
1963 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1965 if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
1970 printf("signal=%s", signal_to_string(i->exit_status));
1975 if (i->main_pid > 0 && i->control_pid > 0)
1978 if (i->control_pid > 0) {
1981 printf(" Control: %u", (unsigned) i->control_pid);
1983 get_process_name(i->control_pid, &t);
1994 printf("\t Status: \"%s\"\n", i->status_text);
1996 if (i->default_control_group) {
1999 printf("\t CGroup: %s\n", i->default_control_group);
2001 if ((c = columns()) > 18)
2006 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
2009 if (i->need_daemon_reload)
2010 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2011 ansi_highlight(true),
2012 ansi_highlight(false),
2013 arg_user ? "--user" : "--system");
2016 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2018 switch (dbus_message_iter_get_arg_type(iter)) {
2020 case DBUS_TYPE_STRING: {
2023 dbus_message_iter_get_basic(iter, &s);
2026 if (streq(name, "Id"))
2028 else if (streq(name, "LoadState"))
2030 else if (streq(name, "ActiveState"))
2031 i->active_state = s;
2032 else if (streq(name, "SubState"))
2034 else if (streq(name, "Description"))
2036 else if (streq(name, "FragmentPath"))
2038 #ifdef HAVE_SYSV_COMPAT
2039 else if (streq(name, "SysVPath")) {
2044 else if (streq(name, "DefaultControlGroup"))
2045 i->default_control_group = s;
2046 else if (streq(name, "StatusText"))
2048 else if (streq(name, "SysFSPath"))
2050 else if (streq(name, "Where"))
2052 else if (streq(name, "What"))
2054 else if (streq(name, "Following"))
2061 case DBUS_TYPE_BOOLEAN: {
2064 dbus_message_iter_get_basic(iter, &b);
2066 if (streq(name, "Accept"))
2068 else if (streq(name, "NeedDaemonReload"))
2069 i->need_daemon_reload = b;
2074 case DBUS_TYPE_UINT32: {
2077 dbus_message_iter_get_basic(iter, &u);
2079 if (streq(name, "MainPID")) {
2081 i->main_pid = (pid_t) u;
2084 } else if (streq(name, "ControlPID"))
2085 i->control_pid = (pid_t) u;
2086 else if (streq(name, "ExecMainPID")) {
2088 i->main_pid = (pid_t) u;
2089 } else if (streq(name, "NAccepted"))
2091 else if (streq(name, "NConnections"))
2092 i->n_connections = u;
2097 case DBUS_TYPE_INT32: {
2100 dbus_message_iter_get_basic(iter, &j);
2102 if (streq(name, "ExecMainCode"))
2103 i->exit_code = (int) j;
2104 else if (streq(name, "ExecMainStatus"))
2105 i->exit_status = (int) j;
2110 case DBUS_TYPE_UINT64: {
2113 dbus_message_iter_get_basic(iter, &u);
2115 if (streq(name, "ExecMainStartTimestamp"))
2116 i->start_timestamp = (usec_t) u;
2117 else if (streq(name, "ExecMainExitTimestamp"))
2118 i->exit_timestamp = (usec_t) u;
2119 else if (streq(name, "ActiveEnterTimestamp"))
2120 i->active_enter_timestamp = (usec_t) u;
2121 else if (streq(name, "InactiveEnterTimestamp"))
2122 i->inactive_enter_timestamp = (usec_t) u;
2123 else if (streq(name, "InactiveExitTimestamp"))
2124 i->inactive_exit_timestamp = (usec_t) u;
2125 else if (streq(name, "ActiveExitTimestamp"))
2126 i->active_exit_timestamp = (usec_t) u;
2131 case DBUS_TYPE_ARRAY: {
2133 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2134 startswith(name, "Exec")) {
2135 DBusMessageIter sub;
2137 dbus_message_iter_recurse(iter, &sub);
2138 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2139 ExecStatusInfo *info;
2142 if (!(info = new0(ExecStatusInfo, 1)))
2145 if (!(info->name = strdup(name))) {
2150 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2155 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2157 dbus_message_iter_next(&sub);
2168 static int print_property(const char *name, DBusMessageIter *iter) {
2172 /* This is a low-level property printer, see
2173 * print_status_info() for the nicer output */
2175 if (arg_property && !strv_find(arg_property, name))
2178 switch (dbus_message_iter_get_arg_type(iter)) {
2180 case DBUS_TYPE_STRING: {
2182 dbus_message_iter_get_basic(iter, &s);
2184 if (arg_all || s[0])
2185 printf("%s=%s\n", name, s);
2190 case DBUS_TYPE_BOOLEAN: {
2192 dbus_message_iter_get_basic(iter, &b);
2193 printf("%s=%s\n", name, yes_no(b));
2198 case DBUS_TYPE_UINT64: {
2200 dbus_message_iter_get_basic(iter, &u);
2202 /* Yes, heuristics! But we can change this check
2203 * should it turn out to not be sufficient */
2205 if (strstr(name, "Timestamp")) {
2206 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
2208 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
2209 printf("%s=%s\n", name, strempty(t));
2210 } else if (strstr(name, "USec")) {
2211 char timespan[FORMAT_TIMESPAN_MAX];
2213 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
2215 printf("%s=%llu\n", name, (unsigned long long) u);
2220 case DBUS_TYPE_UINT32: {
2222 dbus_message_iter_get_basic(iter, &u);
2224 if (strstr(name, "UMask") || strstr(name, "Mode"))
2225 printf("%s=%04o\n", name, u);
2227 printf("%s=%u\n", name, (unsigned) u);
2232 case DBUS_TYPE_INT32: {
2234 dbus_message_iter_get_basic(iter, &i);
2236 printf("%s=%i\n", name, (int) i);
2240 case DBUS_TYPE_DOUBLE: {
2242 dbus_message_iter_get_basic(iter, &d);
2244 printf("%s=%g\n", name, d);
2248 case DBUS_TYPE_STRUCT: {
2249 DBusMessageIter sub;
2250 dbus_message_iter_recurse(iter, &sub);
2252 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2255 dbus_message_iter_get_basic(&sub, &u);
2258 printf("%s=%u\n", name, (unsigned) u);
2260 printf("%s=\n", name);
2263 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2266 dbus_message_iter_get_basic(&sub, &s);
2268 if (arg_all || s[0])
2269 printf("%s=%s\n", name, s);
2277 case DBUS_TYPE_ARRAY:
2279 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2280 DBusMessageIter sub;
2283 dbus_message_iter_recurse(iter, &sub);
2285 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2286 printf("%s=", name);
2288 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2291 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2292 dbus_message_iter_get_basic(&sub, &s);
2293 printf("%s%s", space ? " " : "", s);
2296 dbus_message_iter_next(&sub);
2304 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2305 DBusMessageIter sub;
2307 dbus_message_iter_recurse(iter, &sub);
2309 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2310 printf("%s=", name);
2312 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2315 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2316 dbus_message_iter_get_basic(&sub, &u);
2319 dbus_message_iter_next(&sub);
2327 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2328 DBusMessageIter sub, sub2;
2330 dbus_message_iter_recurse(iter, &sub);
2331 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2332 const char *type, *path;
2334 dbus_message_iter_recurse(&sub, &sub2);
2336 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2337 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2338 printf("%s=%s\n", type, path);
2340 dbus_message_iter_next(&sub);
2345 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2346 DBusMessageIter sub, sub2;
2348 dbus_message_iter_recurse(iter, &sub);
2349 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2351 uint64_t value, next_elapse;
2353 dbus_message_iter_recurse(&sub, &sub2);
2355 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2356 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2357 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2358 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2360 printf("%s={ value=%s ; next_elapse=%s }\n",
2362 format_timespan(timespan1, sizeof(timespan1), value),
2363 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2366 dbus_message_iter_next(&sub);
2371 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2372 DBusMessageIter sub;
2374 dbus_message_iter_recurse(iter, &sub);
2375 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2376 ExecStatusInfo info;
2379 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2380 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2383 t = strv_join(info.argv, " ");
2385 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2389 yes_no(info.ignore),
2390 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2391 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2392 (unsigned) info. pid,
2393 sigchld_code_to_string(info.code),
2395 info.code == CLD_EXITED ? "" : "/",
2396 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2402 strv_free(info.argv);
2404 dbus_message_iter_next(&sub);
2414 printf("%s=[unprintable]\n", name);
2419 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2420 DBusMessage *m = NULL, *reply = NULL;
2421 const char *interface = "";
2424 DBusMessageIter iter, sub, sub2, sub3;
2425 UnitStatusInfo info;
2433 dbus_error_init(&error);
2435 if (!(m = dbus_message_new_method_call(
2436 "org.freedesktop.systemd1",
2438 "org.freedesktop.DBus.Properties",
2440 log_error("Could not allocate message.");
2445 if (!dbus_message_append_args(m,
2446 DBUS_TYPE_STRING, &interface,
2447 DBUS_TYPE_INVALID)) {
2448 log_error("Could not append arguments to message.");
2453 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2454 log_error("Failed to issue method call: %s", bus_error_message(&error));
2459 if (!dbus_message_iter_init(reply, &iter) ||
2460 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2461 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2462 log_error("Failed to parse reply.");
2467 dbus_message_iter_recurse(&iter, &sub);
2474 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2477 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2478 log_error("Failed to parse reply.");
2483 dbus_message_iter_recurse(&sub, &sub2);
2485 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2486 log_error("Failed to parse reply.");
2491 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2492 log_error("Failed to parse reply.");
2497 dbus_message_iter_recurse(&sub2, &sub3);
2499 if (show_properties)
2500 r = print_property(name, &sub3);
2502 r = status_property(name, &sub3, &info);
2505 log_error("Failed to parse reply.");
2510 dbus_message_iter_next(&sub);
2515 if (!show_properties)
2516 print_status_info(&info);
2518 if (!streq_ptr(info.active_state, "active") &&
2519 !streq_ptr(info.active_state, "reloading") &&
2520 streq(verb, "status"))
2521 /* According to LSB: "program not running" */
2524 while ((p = info.exec)) {
2525 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2526 exec_status_info_free(p);
2531 dbus_message_unref(m);
2534 dbus_message_unref(reply);
2536 dbus_error_free(&error);
2541 static int show(DBusConnection *bus, char **args, unsigned n) {
2542 DBusMessage *m = NULL, *reply = NULL;
2546 bool show_properties, new_line = false;
2551 dbus_error_init(&error);
2553 show_properties = !streq(args[0], "status");
2555 if (show_properties)
2558 if (show_properties && n <= 1) {
2559 /* If not argument is specified inspect the manager
2562 ret = show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2566 for (i = 1; i < n; i++) {
2567 const char *path = NULL;
2570 if (safe_atou32(args[i], &id) < 0) {
2572 /* Interpret as unit name */
2574 if (!(m = dbus_message_new_method_call(
2575 "org.freedesktop.systemd1",
2576 "/org/freedesktop/systemd1",
2577 "org.freedesktop.systemd1.Manager",
2579 log_error("Could not allocate message.");
2584 if (!dbus_message_append_args(m,
2585 DBUS_TYPE_STRING, &args[i],
2586 DBUS_TYPE_INVALID)) {
2587 log_error("Could not append arguments to message.");
2592 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2594 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2595 log_error("Failed to issue method call: %s", bus_error_message(&error));
2600 dbus_error_free(&error);
2602 dbus_message_unref(m);
2603 if (!(m = dbus_message_new_method_call(
2604 "org.freedesktop.systemd1",
2605 "/org/freedesktop/systemd1",
2606 "org.freedesktop.systemd1.Manager",
2608 log_error("Could not allocate message.");
2613 if (!dbus_message_append_args(m,
2614 DBUS_TYPE_STRING, &args[i],
2615 DBUS_TYPE_INVALID)) {
2616 log_error("Could not append arguments to message.");
2621 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2622 log_error("Failed to issue method call: %s", bus_error_message(&error));
2624 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2625 ret = 4; /* According to LSB: "program or service status is unknown" */
2632 } else if (show_properties) {
2634 /* Interpret as job id */
2636 if (!(m = dbus_message_new_method_call(
2637 "org.freedesktop.systemd1",
2638 "/org/freedesktop/systemd1",
2639 "org.freedesktop.systemd1.Manager",
2641 log_error("Could not allocate message.");
2646 if (!dbus_message_append_args(m,
2647 DBUS_TYPE_UINT32, &id,
2648 DBUS_TYPE_INVALID)) {
2649 log_error("Could not append arguments to message.");
2654 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2655 log_error("Failed to issue method call: %s", bus_error_message(&error));
2661 /* Interpret as PID */
2663 if (!(m = dbus_message_new_method_call(
2664 "org.freedesktop.systemd1",
2665 "/org/freedesktop/systemd1",
2666 "org.freedesktop.systemd1.Manager",
2668 log_error("Could not allocate message.");
2673 if (!dbus_message_append_args(m,
2674 DBUS_TYPE_UINT32, &id,
2675 DBUS_TYPE_INVALID)) {
2676 log_error("Could not append arguments to message.");
2681 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2682 log_error("Failed to issue method call: %s", bus_error_message(&error));
2688 if (!dbus_message_get_args(reply, &error,
2689 DBUS_TYPE_OBJECT_PATH, &path,
2690 DBUS_TYPE_INVALID)) {
2691 log_error("Failed to parse reply: %s", bus_error_message(&error));
2696 if ((r = show_one(args[0], bus, path, show_properties, &new_line)) != 0)
2699 dbus_message_unref(m);
2700 dbus_message_unref(reply);
2706 dbus_message_unref(m);
2709 dbus_message_unref(reply);
2711 dbus_error_free(&error);
2716 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2718 DBusMessage *m = NULL, *reply = NULL;
2723 dbus_error_init(&error);
2725 log_debug("Got D-Bus request: %s.%s() on %s",
2726 dbus_message_get_interface(message),
2727 dbus_message_get_member(message),
2728 dbus_message_get_path(message));
2730 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2731 log_error("Warning! D-Bus connection terminated.");
2732 dbus_connection_close(connection);
2734 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2735 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2736 const char *id, *path;
2738 if (!dbus_message_get_args(message, &error,
2739 DBUS_TYPE_STRING, &id,
2740 DBUS_TYPE_OBJECT_PATH, &path,
2742 log_error("Failed to parse message: %s", bus_error_message(&error));
2743 else if (streq(dbus_message_get_member(message), "UnitNew"))
2744 printf("Unit %s added.\n", id);
2746 printf("Unit %s removed.\n", id);
2748 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2749 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2753 if (!dbus_message_get_args(message, &error,
2754 DBUS_TYPE_UINT32, &id,
2755 DBUS_TYPE_OBJECT_PATH, &path,
2757 log_error("Failed to parse message: %s", bus_error_message(&error));
2758 else if (streq(dbus_message_get_member(message), "JobNew"))
2759 printf("Job %u added.\n", id);
2761 printf("Job %u removed.\n", id);
2764 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2766 const char *path, *interface, *property = "Id";
2767 DBusMessageIter iter, sub;
2769 path = dbus_message_get_path(message);
2771 if (!dbus_message_get_args(message, &error,
2772 DBUS_TYPE_STRING, &interface,
2773 DBUS_TYPE_INVALID)) {
2774 log_error("Failed to parse message: %s", bus_error_message(&error));
2778 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2779 !streq(interface, "org.freedesktop.systemd1.Unit"))
2782 if (!(m = dbus_message_new_method_call(
2783 "org.freedesktop.systemd1",
2785 "org.freedesktop.DBus.Properties",
2787 log_error("Could not allocate message.");
2791 if (!dbus_message_append_args(m,
2792 DBUS_TYPE_STRING, &interface,
2793 DBUS_TYPE_STRING, &property,
2794 DBUS_TYPE_INVALID)) {
2795 log_error("Could not append arguments to message.");
2799 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2800 log_error("Failed to issue method call: %s", bus_error_message(&error));
2804 if (!dbus_message_iter_init(reply, &iter) ||
2805 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2806 log_error("Failed to parse reply.");
2810 dbus_message_iter_recurse(&iter, &sub);
2812 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2815 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2816 log_error("Failed to parse reply.");
2820 dbus_message_iter_get_basic(&sub, &id);
2821 printf("Unit %s changed.\n", id);
2825 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2826 log_error("Failed to parse reply.");
2830 dbus_message_iter_get_basic(&sub, &id);
2831 printf("Job %u changed.\n", id);
2837 dbus_message_unref(m);
2840 dbus_message_unref(reply);
2842 dbus_error_free(&error);
2843 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2847 dbus_message_unref(m);
2850 dbus_message_unref(reply);
2852 dbus_error_free(&error);
2853 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2856 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2857 DBusMessage *m = NULL, *reply = NULL;
2861 dbus_error_init(&error);
2864 dbus_bus_add_match(bus,
2866 "sender='org.freedesktop.systemd1',"
2867 "interface='org.freedesktop.systemd1.Manager',"
2868 "path='/org/freedesktop/systemd1'",
2871 if (dbus_error_is_set(&error)) {
2872 log_error("Failed to add match: %s", bus_error_message(&error));
2877 dbus_bus_add_match(bus,
2879 "sender='org.freedesktop.systemd1',"
2880 "interface='org.freedesktop.DBus.Properties',"
2881 "member='PropertiesChanged'",
2884 if (dbus_error_is_set(&error)) {
2885 log_error("Failed to add match: %s", bus_error_message(&error));
2891 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2892 log_error("Failed to add filter.");
2897 if (!(m = dbus_message_new_method_call(
2898 "org.freedesktop.systemd1",
2899 "/org/freedesktop/systemd1",
2900 "org.freedesktop.systemd1.Manager",
2902 log_error("Could not allocate message.");
2907 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2908 log_error("Failed to issue method call: %s", bus_error_message(&error));
2913 while (dbus_connection_read_write_dispatch(bus, -1))
2920 /* This is slightly dirty, since we don't undo the filter or the matches. */
2923 dbus_message_unref(m);
2926 dbus_message_unref(reply);
2928 dbus_error_free(&error);
2933 static int dump(DBusConnection *bus, char **args, unsigned n) {
2934 DBusMessage *m = NULL, *reply = NULL;
2939 dbus_error_init(&error);
2943 if (!(m = dbus_message_new_method_call(
2944 "org.freedesktop.systemd1",
2945 "/org/freedesktop/systemd1",
2946 "org.freedesktop.systemd1.Manager",
2948 log_error("Could not allocate message.");
2952 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2953 log_error("Failed to issue method call: %s", bus_error_message(&error));
2958 if (!dbus_message_get_args(reply, &error,
2959 DBUS_TYPE_STRING, &text,
2960 DBUS_TYPE_INVALID)) {
2961 log_error("Failed to parse reply: %s", bus_error_message(&error));
2966 fputs(text, stdout);
2972 dbus_message_unref(m);
2975 dbus_message_unref(reply);
2977 dbus_error_free(&error);
2982 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2983 DBusMessage *m = NULL, *reply = NULL;
2986 const char *name = "", *path, *id;
2987 dbus_bool_t cleanup = FALSE;
2988 DBusMessageIter iter, sub;
2990 *interface = "org.freedesktop.systemd1.Unit",
2993 dbus_error_init(&error);
2995 if (!(m = dbus_message_new_method_call(
2996 "org.freedesktop.systemd1",
2997 "/org/freedesktop/systemd1",
2998 "org.freedesktop.systemd1.Manager",
2999 "CreateSnapshot"))) {
3000 log_error("Could not allocate message.");
3007 if (!dbus_message_append_args(m,
3008 DBUS_TYPE_STRING, &name,
3009 DBUS_TYPE_BOOLEAN, &cleanup,
3010 DBUS_TYPE_INVALID)) {
3011 log_error("Could not append arguments to message.");
3016 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3017 log_error("Failed to issue method call: %s", bus_error_message(&error));
3022 if (!dbus_message_get_args(reply, &error,
3023 DBUS_TYPE_OBJECT_PATH, &path,
3024 DBUS_TYPE_INVALID)) {
3025 log_error("Failed to parse reply: %s", bus_error_message(&error));
3030 dbus_message_unref(m);
3031 if (!(m = dbus_message_new_method_call(
3032 "org.freedesktop.systemd1",
3034 "org.freedesktop.DBus.Properties",
3036 log_error("Could not allocate message.");
3040 if (!dbus_message_append_args(m,
3041 DBUS_TYPE_STRING, &interface,
3042 DBUS_TYPE_STRING, &property,
3043 DBUS_TYPE_INVALID)) {
3044 log_error("Could not append arguments to message.");
3049 dbus_message_unref(reply);
3050 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3051 log_error("Failed to issue method call: %s", bus_error_message(&error));
3056 if (!dbus_message_iter_init(reply, &iter) ||
3057 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3058 log_error("Failed to parse reply.");
3063 dbus_message_iter_recurse(&iter, &sub);
3065 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3066 log_error("Failed to parse reply.");
3071 dbus_message_iter_get_basic(&sub, &id);
3079 dbus_message_unref(m);
3082 dbus_message_unref(reply);
3084 dbus_error_free(&error);
3089 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
3090 DBusMessage *m = NULL, *reply = NULL;
3098 dbus_error_init(&error);
3100 for (i = 1; i < n; i++) {
3101 const char *path = NULL;
3103 if (!(m = dbus_message_new_method_call(
3104 "org.freedesktop.systemd1",
3105 "/org/freedesktop/systemd1",
3106 "org.freedesktop.systemd1.Manager",
3108 log_error("Could not allocate message.");
3113 if (!dbus_message_append_args(m,
3114 DBUS_TYPE_STRING, &args[i],
3115 DBUS_TYPE_INVALID)) {
3116 log_error("Could not append arguments to message.");
3121 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3122 log_error("Failed to issue method call: %s", bus_error_message(&error));
3127 if (!dbus_message_get_args(reply, &error,
3128 DBUS_TYPE_OBJECT_PATH, &path,
3129 DBUS_TYPE_INVALID)) {
3130 log_error("Failed to parse reply: %s", bus_error_message(&error));
3135 dbus_message_unref(m);
3136 if (!(m = dbus_message_new_method_call(
3137 "org.freedesktop.systemd1",
3139 "org.freedesktop.systemd1.Snapshot",
3141 log_error("Could not allocate message.");
3146 dbus_message_unref(reply);
3147 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3148 log_error("Failed to issue method call: %s", bus_error_message(&error));
3153 dbus_message_unref(m);
3154 dbus_message_unref(reply);
3162 dbus_message_unref(m);
3165 dbus_message_unref(reply);
3167 dbus_error_free(&error);
3172 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
3173 DBusMessage *m = NULL, *reply = NULL;
3178 dbus_error_init(&error);
3180 if (arg_action == ACTION_RELOAD)
3182 else if (arg_action == ACTION_REEXEC)
3183 method = "Reexecute";
3185 assert(arg_action == ACTION_SYSTEMCTL);
3188 streq(args[0], "clear-jobs") ||
3189 streq(args[0], "cancel") ? "ClearJobs" :
3190 streq(args[0], "daemon-reexec") ? "Reexecute" :
3191 streq(args[0], "reset-failed") ? "ResetFailed" :
3192 streq(args[0], "halt") ? "Halt" :
3193 streq(args[0], "poweroff") ? "PowerOff" :
3194 streq(args[0], "reboot") ? "Reboot" :
3195 streq(args[0], "kexec") ? "KExec" :
3196 streq(args[0], "exit") ? "Exit" :
3197 /* "daemon-reload" */ "Reload";
3200 if (!(m = dbus_message_new_method_call(
3201 "org.freedesktop.systemd1",
3202 "/org/freedesktop/systemd1",
3203 "org.freedesktop.systemd1.Manager",
3205 log_error("Could not allocate message.");
3209 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3211 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3212 /* There's always a fallback possible for
3213 * legacy actions. */
3218 log_error("Failed to issue method call: %s", bus_error_message(&error));
3227 dbus_message_unref(m);
3230 dbus_message_unref(reply);
3232 dbus_error_free(&error);
3237 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3238 DBusMessage *m = NULL, *reply = NULL;
3244 dbus_error_init(&error);
3247 return daemon_reload(bus, args, n);
3249 for (i = 1; i < n; i++) {
3251 if (!(m = dbus_message_new_method_call(
3252 "org.freedesktop.systemd1",
3253 "/org/freedesktop/systemd1",
3254 "org.freedesktop.systemd1.Manager",
3255 "ResetFailedUnit"))) {
3256 log_error("Could not allocate message.");
3261 if (!dbus_message_append_args(m,
3262 DBUS_TYPE_STRING, args + i,
3263 DBUS_TYPE_INVALID)) {
3264 log_error("Could not append arguments to message.");
3269 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3270 log_error("Failed to issue method call: %s", bus_error_message(&error));
3275 dbus_message_unref(m);
3276 dbus_message_unref(reply);
3284 dbus_message_unref(m);
3287 dbus_message_unref(reply);
3289 dbus_error_free(&error);
3294 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3295 DBusMessage *m = NULL, *reply = NULL;
3297 DBusMessageIter iter, sub, sub2;
3300 *interface = "org.freedesktop.systemd1.Manager",
3301 *property = "Environment";
3303 dbus_error_init(&error);
3307 if (!(m = dbus_message_new_method_call(
3308 "org.freedesktop.systemd1",
3309 "/org/freedesktop/systemd1",
3310 "org.freedesktop.DBus.Properties",
3312 log_error("Could not allocate message.");
3316 if (!dbus_message_append_args(m,
3317 DBUS_TYPE_STRING, &interface,
3318 DBUS_TYPE_STRING, &property,
3319 DBUS_TYPE_INVALID)) {
3320 log_error("Could not append arguments to message.");
3325 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3326 log_error("Failed to issue method call: %s", bus_error_message(&error));
3331 if (!dbus_message_iter_init(reply, &iter) ||
3332 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3333 log_error("Failed to parse reply.");
3338 dbus_message_iter_recurse(&iter, &sub);
3340 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3341 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3342 log_error("Failed to parse reply.");
3347 dbus_message_iter_recurse(&sub, &sub2);
3349 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3352 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3353 log_error("Failed to parse reply.");
3358 dbus_message_iter_get_basic(&sub2, &text);
3359 printf("%s\n", text);
3361 dbus_message_iter_next(&sub2);
3368 dbus_message_unref(m);
3371 dbus_message_unref(reply);
3373 dbus_error_free(&error);
3378 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3379 DBusMessage *m = NULL, *reply = NULL;
3383 DBusMessageIter iter, sub;
3386 dbus_error_init(&error);
3388 method = streq(args[0], "set-environment")
3390 : "UnsetEnvironment";
3392 if (!(m = dbus_message_new_method_call(
3393 "org.freedesktop.systemd1",
3394 "/org/freedesktop/systemd1",
3395 "org.freedesktop.systemd1.Manager",
3398 log_error("Could not allocate message.");
3402 dbus_message_iter_init_append(m, &iter);
3404 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3405 log_error("Could not append arguments to message.");
3410 for (i = 1; i < n; i++)
3411 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3412 log_error("Could not append arguments to message.");
3417 if (!dbus_message_iter_close_container(&iter, &sub)) {
3418 log_error("Could not append arguments to message.");
3423 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3424 log_error("Failed to issue method call: %s", bus_error_message(&error));
3433 dbus_message_unref(m);
3436 dbus_message_unref(reply);
3438 dbus_error_free(&error);
3451 static Hashmap *will_install = NULL, *have_installed = NULL;
3452 static Set *remove_symlinks_to = NULL;
3453 static unsigned n_symlinks = 0;
3455 static void install_info_free(InstallInfo *i) {
3460 strv_free(i->aliases);
3461 strv_free(i->wanted_by);
3465 static void install_info_hashmap_free(Hashmap *m) {
3468 while ((i = hashmap_steal_first(m)))
3469 install_info_free(i);
3474 static int install_info_add(const char *name) {
3478 assert(will_install);
3480 if (!unit_name_is_valid_no_type(name, true)) {
3481 log_warning("Unit name %s is not a valid unit name.", name);
3485 if (hashmap_get(have_installed, name) ||
3486 hashmap_get(will_install, name))
3489 if (!(i = new0(InstallInfo, 1))) {
3494 if (!(i->name = strdup(name))) {
3499 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3506 install_info_free(i);
3511 static int config_parse_also(
3512 const char *filename,
3514 const char *section,
3528 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3532 if (!(n = strndup(w, l)))
3535 if ((r = install_info_add(n)) < 0) {
3536 log_warning("Cannot install unit %s: %s", n, strerror(-r));
3547 static int mark_symlink_for_removal(const char *p) {
3552 assert(path_is_absolute(p));
3554 if (!remove_symlinks_to)
3557 if (!(n = strdup(p)))
3560 path_kill_slashes(n);
3562 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3564 return r == -EEXIST ? 0 : r;
3570 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3579 if (!(d = fdopendir(fd))) {
3580 close_nointr_nofail(fd);
3586 while ((de = readdir(d))) {
3587 bool is_dir = false, is_link = false;
3589 if (ignore_file(de->d_name))
3592 if (de->d_type == DT_LNK)
3594 else if (de->d_type == DT_DIR)
3596 else if (de->d_type == DT_UNKNOWN) {
3599 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3600 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3607 is_link = S_ISLNK(st.st_mode);
3608 is_dir = S_ISDIR(st.st_mode);
3616 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3617 log_error("Failed to open %s/%s: %m", root, de->d_name);
3624 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3625 log_error("Failed to allocate directory string.");
3626 close_nointr_nofail(nfd);
3631 /* This will close nfd, regardless whether it succeeds or not */
3632 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3638 } else if (is_link) {
3642 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3643 log_error("Failed to allocate symlink string.");
3648 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3649 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3657 if ((c = canonicalize_file_name(dest))) {
3658 /* This might fail if the destination
3659 * is already removed */
3665 path_kill_slashes(dest);
3666 if (set_get(remove_symlinks_to, dest)) {
3669 log_info("rm '%s'", p);
3671 if (unlink(p) < 0) {
3672 log_error("Cannot unlink symlink %s: %m", p);
3677 rmdir_parents(p, config_path);
3678 path_kill_slashes(p);
3680 if (!set_get(remove_symlinks_to, p)) {
3682 if ((r = mark_symlink_for_removal(p)) < 0) {
3701 static int remove_marked_symlinks(const char *config_path) {
3705 assert(config_path);
3707 if (set_size(remove_symlinks_to) <= 0)
3710 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3717 if ((cfd = dup(fd)) < 0) {
3722 /* This takes possession of cfd and closes it */
3723 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3729 close_nointr_nofail(fd);
3734 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3741 if (streq(verb, "enable")) {
3744 mkdir_parents(new_path, 0755);
3746 if (symlink(old_path, new_path) >= 0) {
3749 log_info("ln -s '%s' '%s'", old_path, new_path);
3754 if (errno != EEXIST) {
3755 log_error("Cannot link %s to %s: %m", old_path, new_path);
3759 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3761 if (errno == EINVAL) {
3762 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3766 log_error("readlink() failed: %s", strerror(-r));
3770 if (streq(dest, old_path)) {
3776 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3785 log_info("ln -s '%s' '%s'", old_path, new_path);
3787 if (symlink(old_path, new_path) >= 0)
3790 log_error("Cannot link %s to %s: %m", old_path, new_path);
3793 } else if (streq(verb, "disable")) {
3796 if ((r = mark_symlink_for_removal(old_path)) < 0)
3799 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3800 if (errno == ENOENT)
3803 if (errno == EINVAL) {
3804 log_warning("File %s not a symlink, ignoring.", old_path);
3808 log_error("readlink() failed: %s", strerror(-r));
3812 if (!streq(dest, old_path)) {
3813 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3820 if ((r = mark_symlink_for_removal(new_path)) < 0)
3824 log_info("rm '%s'", new_path);
3826 if (unlink(new_path) >= 0)
3829 log_error("Cannot unlink %s: %m", new_path);
3832 } else if (streq(verb, "is-enabled")) {
3835 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3837 if (errno == ENOENT || errno == EINVAL)
3840 log_error("readlink() failed: %s", strerror(-r));
3844 if (streq(dest, old_path)) {
3852 assert_not_reached("Unknown action.");
3855 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3857 char *alias_path = NULL;
3862 assert(config_path);
3864 STRV_FOREACH(s, i->aliases) {
3867 if (!(alias_path = path_make_absolute(*s, config_path))) {
3868 log_error("Out of memory");
3873 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3876 if (streq(verb, "disable"))
3877 rmdir_parents(alias_path, config_path);
3887 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3889 char *alias_path = NULL;
3894 assert(config_path);
3896 STRV_FOREACH(s, i->wanted_by) {
3897 if (!unit_name_is_valid_no_type(*s, true)) {
3898 log_error("Invalid name %s.", *s);
3906 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3907 log_error("Out of memory");
3912 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3915 if (streq(verb, "disable"))
3916 rmdir_parents(alias_path, config_path);
3927 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3929 const ConfigItem items[] = {
3930 { "Alias", config_parse_strv, &i->aliases, "Install" },
3931 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3932 { "Also", config_parse_also, NULL, "Install" },
3934 { NULL, NULL, NULL, NULL }
3938 char *filename = NULL;
3945 STRV_FOREACH(p, paths->unit_path) {
3948 if (!(filename = path_make_absolute(i->name, *p))) {
3949 log_error("Out of memory");
3953 /* Ensure that we don't follow symlinks */
3954 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3955 if ((f = fdopen(fd, "re")))
3958 if (errno == ELOOP) {
3959 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3964 if (errno != ENOENT) {
3965 log_error("Failed to open %s: %m", filename);
3975 #if defined(TARGET_FEDORA) && defined (HAVE_SYSV_COMPAT)
3977 if (endswith(i->name, ".service")) {
3981 if (asprintf(&sysv, SYSTEM_SYSVINIT_PATH "/%s", i->name) < 0) {
3982 log_error("Out of memory");
3986 sysv[strlen(sysv) - sizeof(".service") + 1] = 0;
3987 exists = access(sysv, F_OK) >= 0;
3993 const char *argv[] = {
4000 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", i->name);
4002 argv[1] = file_name_from_path(sysv);
4004 streq(verb, "enable") ? "on" :
4005 streq(verb, "disable") ? "off" : NULL;
4007 log_info("Executing %s %s %s", argv[0], argv[1], strempty(argv[2]));
4009 if ((pid = fork()) < 0) {
4010 log_error("Failed to fork: %m");
4013 } else if (pid == 0) {
4014 execv(argv[0], (char**) argv);
4015 _exit(EXIT_FAILURE);
4020 if ((r = wait_for_terminate(pid, &status)) < 0)
4023 if (status.si_code == CLD_EXITED) {
4024 if (status.si_status == 0 && (streq(verb, "enable") || streq(verb, "disable")))
4027 return status.si_status == 0 ? 0 : -EINVAL;
4037 log_error("Couldn't find %s.", i->name);
4043 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
4048 n_symlinks += strv_length(i->aliases);
4049 n_symlinks += strv_length(i->wanted_by);
4053 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
4056 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
4059 if ((r = mark_symlink_for_removal(filename)) < 0)
4062 if ((r = remove_marked_symlinks(config_path)) < 0)
4068 static char *get_config_path(void) {
4070 if (arg_user && arg_global)
4071 return strdup(USER_CONFIG_UNIT_PATH);
4076 if (user_config_home(&p) < 0)
4082 return strdup(SYSTEM_CONFIG_UNIT_PATH);
4085 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
4089 char *config_path = NULL;
4092 const char *verb = args[0];
4094 dbus_error_init(&error);
4097 if ((r = lookup_paths_init(&paths, arg_user ? MANAGER_USER : MANAGER_SYSTEM)) < 0) {
4098 log_error("Failed to determine lookup paths: %s", strerror(-r));
4102 if (!(config_path = get_config_path())) {
4103 log_error("Failed to determine config path");
4108 will_install = hashmap_new(string_hash_func, string_compare_func);
4109 have_installed = hashmap_new(string_hash_func, string_compare_func);
4111 if (!will_install || !have_installed) {
4112 log_error("Failed to allocate unit sets.");
4117 if (!arg_defaults && streq(verb, "disable"))
4118 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
4119 log_error("Failed to allocate symlink sets.");
4124 for (j = 1; j < n; j++)
4125 if ((r = install_info_add(args[j])) < 0) {
4126 log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
4130 while ((i = hashmap_first(will_install))) {
4133 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
4135 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
4143 /* In test mode and found something */
4149 if (streq(verb, "is-enabled"))
4150 r = r > 0 ? 0 : -ENOENT;
4152 if (n_symlinks <= 0)
4153 log_warning("Unit files contain no applicable installation information. Ignoring.");
4156 /* Don't try to reload anything if the user asked us to not do this */
4158 /* Don't try to reload anything when updating a unit globally */
4160 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
4161 (arg_user || sd_booted() > 0) &&
4162 /* Don't try to reload anything if we are running in a chroot environment */
4163 (arg_user || running_in_chroot() <= 0) ) {
4166 if ((q = daemon_reload(bus, args, n)) < 0)
4172 install_info_hashmap_free(will_install);
4173 install_info_hashmap_free(have_installed);
4175 set_free_free(remove_symlinks_to);
4177 lookup_paths_free(&paths);
4184 static int systemctl_help(void) {
4186 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4187 "Send control commands to or query the systemd manager.\n\n"
4188 " -h --help Show this help\n"
4189 " --version Show package version\n"
4190 " -t --type=TYPE List only units of a particular type\n"
4191 " -p --property=NAME Show only properties by this name\n"
4192 " -a --all Show all units/properties, including dead/empty ones\n"
4193 " --full Don't ellipsize unit names on output\n"
4194 " --fail When queueing a new job, fail if conflicting jobs are\n"
4196 " -q --quiet Suppress output\n"
4197 " --no-block Do not wait until operation finished\n"
4198 " --no-pager Do not pipe output into a pager.\n"
4199 " --system Connect to system manager\n"
4200 " --user Connect to user service manager\n"
4201 " --order When generating graph for dot, show only order\n"
4202 " --require When generating graph for dot, show only requirement\n"
4203 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4204 " --global Enable/disable unit files globally\n"
4205 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4207 " --no-ask-password\n"
4208 " Do not ask for system passwords\n"
4209 " --kill-mode=MODE How to send signal\n"
4210 " --kill-who=WHO Who to send signal to\n"
4211 " -s --signal=SIGNAL Which signal to send\n"
4212 " -f --force When enabling unit files, override existing symlinks\n"
4213 " When shutting down, execute action immediately\n"
4214 " --defaults When disabling unit files, remove default symlinks only\n\n"
4216 " list-units List units\n"
4217 " start [NAME...] Start (activate) one or more units\n"
4218 " stop [NAME...] Stop (deactivate) one or more units\n"
4219 " reload [NAME...] Reload one or more units\n"
4220 " restart [NAME...] Start or restart one or more units\n"
4221 " try-restart [NAME...] Restart one or more units if active\n"
4222 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4223 " otherwise start or restart\n"
4224 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4225 " otherwise restart if active\n"
4226 " isolate [NAME] Start one unit and stop all others\n"
4227 " kill [NAME...] Send signal to processes of a unit\n"
4228 " is-active [NAME...] Check whether units are active\n"
4229 " status [NAME...|PID...] Show runtime status of one or more units\n"
4230 " show [NAME...|JOB...] Show properties of one or more\n"
4231 " units/jobs or the manager\n"
4232 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4234 " enable [NAME...] Enable one or more unit files\n"
4235 " disable [NAME...] Disable one or more unit files\n"
4236 " is-enabled [NAME...] Check whether unit files are enabled\n"
4237 " load [NAME...] Load one or more units\n"
4238 " list-jobs List jobs\n"
4239 " cancel [JOB...] Cancel all, one, or more jobs\n"
4240 " monitor Monitor unit/job changes\n"
4241 " dump Dump server status\n"
4242 " dot Dump dependency graph for dot(1)\n"
4243 " snapshot [NAME] Create a snapshot\n"
4244 " delete [NAME...] Remove one or more snapshots\n"
4245 " daemon-reload Reload systemd manager configuration\n"
4246 " daemon-reexec Reexecute systemd manager\n"
4247 " show-environment Dump environment\n"
4248 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4249 " unset-environment [NAME...] Unset one or more environment variables\n"
4250 " default Enter system default mode\n"
4251 " rescue Enter system rescue mode\n"
4252 " emergency Enter system emergency mode\n"
4253 " halt Shut down and halt the system\n"
4254 " poweroff Shut down and power-off the system\n"
4255 " reboot Shut down and reboot the system\n"
4256 " kexec Shut down and reboot the system with kexec\n"
4257 " exit Ask for user instance termination\n",
4258 program_invocation_short_name);
4263 static int halt_help(void) {
4265 printf("%s [OPTIONS...]\n\n"
4266 "%s the system.\n\n"
4267 " --help Show this help\n"
4268 " --halt Halt the machine\n"
4269 " -p --poweroff Switch off the machine\n"
4270 " --reboot Reboot the machine\n"
4271 " -f --force Force immediate halt/power-off/reboot\n"
4272 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4273 " -d --no-wtmp Don't write wtmp record\n"
4274 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4275 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4276 program_invocation_short_name,
4277 arg_action == ACTION_REBOOT ? "Reboot" :
4278 arg_action == ACTION_POWEROFF ? "Power off" :
4284 static int shutdown_help(void) {
4286 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4287 "Shut down the system.\n\n"
4288 " --help Show this help\n"
4289 " -H --halt Halt the machine\n"
4290 " -P --poweroff Power-off the machine\n"
4291 " -r --reboot Reboot the machine\n"
4292 " -h Equivalent to --poweroff, overriden by --halt\n"
4293 " -k Don't halt/power-off/reboot, just send warnings\n"
4294 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4295 " -c Cancel a pending shutdown\n",
4296 program_invocation_short_name);
4301 static int telinit_help(void) {
4303 printf("%s [OPTIONS...] {COMMAND}\n\n"
4304 "Send control commands to the init daemon.\n\n"
4305 " --help Show this help\n"
4306 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4308 " 0 Power-off the machine\n"
4309 " 6 Reboot the machine\n"
4310 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4311 " 1, s, S Enter rescue mode\n"
4312 " q, Q Reload init daemon configuration\n"
4313 " u, U Reexecute init daemon\n",
4314 program_invocation_short_name);
4319 static int runlevel_help(void) {
4321 printf("%s [OPTIONS...]\n\n"
4322 "Prints the previous and current runlevel of the init system.\n\n"
4323 " --help Show this help\n",
4324 program_invocation_short_name);
4329 static int systemctl_parse_argv(int argc, char *argv[]) {
4350 static const struct option options[] = {
4351 { "help", no_argument, NULL, 'h' },
4352 { "version", no_argument, NULL, ARG_VERSION },
4353 { "type", required_argument, NULL, 't' },
4354 { "property", required_argument, NULL, 'p' },
4355 { "all", no_argument, NULL, 'a' },
4356 { "full", no_argument, NULL, ARG_FULL },
4357 { "fail", no_argument, NULL, ARG_FAIL },
4358 { "user", no_argument, NULL, ARG_USER },
4359 { "system", no_argument, NULL, ARG_SYSTEM },
4360 { "global", no_argument, NULL, ARG_GLOBAL },
4361 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4362 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4363 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4364 { "quiet", no_argument, NULL, 'q' },
4365 { "order", no_argument, NULL, ARG_ORDER },
4366 { "require", no_argument, NULL, ARG_REQUIRE },
4367 { "force", no_argument, NULL, 'f' },
4368 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4369 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4370 { "kill-mode", required_argument, NULL, ARG_KILL_MODE },
4371 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4372 { "signal", required_argument, NULL, 's' },
4373 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4374 { NULL, 0, NULL, 0 }
4382 /* Only when running as systemctl we ask for passwords */
4383 arg_ask_password = true;
4385 while ((c = getopt_long(argc, argv, "ht:p:aqfs:", options, NULL)) >= 0) {
4394 puts(PACKAGE_STRING);
4396 puts(SYSTEMD_FEATURES);
4406 if (!(l = strv_append(arg_property, optarg)))
4409 strv_free(arg_property);
4412 /* If the user asked for a particular
4413 * property, show it to him, even if it is
4436 arg_no_block = true;
4440 arg_no_pager = true;
4448 arg_dot = DOT_ORDER;
4452 arg_dot = DOT_REQUIRE;
4468 arg_no_reload = true;
4477 arg_defaults = true;
4481 arg_kill_who = optarg;
4485 arg_kill_mode = optarg;
4489 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4490 log_error("Failed to parse signal string %s.", optarg);
4495 case ARG_NO_ASK_PASSWORD:
4496 arg_ask_password = false;
4503 log_error("Unknown option code %c", c);
4511 static int halt_parse_argv(int argc, char *argv[]) {
4520 static const struct option options[] = {
4521 { "help", no_argument, NULL, ARG_HELP },
4522 { "halt", no_argument, NULL, ARG_HALT },
4523 { "poweroff", no_argument, NULL, 'p' },
4524 { "reboot", no_argument, NULL, ARG_REBOOT },
4525 { "force", no_argument, NULL, 'f' },
4526 { "wtmp-only", no_argument, NULL, 'w' },
4527 { "no-wtmp", no_argument, NULL, 'd' },
4528 { "no-sync", no_argument, NULL, 'n' },
4529 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4530 { NULL, 0, NULL, 0 }
4538 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4539 if (runlevel == '0' || runlevel == '6')
4540 arg_immediate = true;
4542 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4550 arg_action = ACTION_HALT;
4554 if (arg_action != ACTION_REBOOT)
4555 arg_action = ACTION_POWEROFF;
4559 arg_action = ACTION_REBOOT;
4563 arg_immediate = true;
4584 /* Compatibility nops */
4591 log_error("Unknown option code %c", c);
4596 if (optind < argc) {
4597 log_error("Too many arguments.");
4604 static int parse_time_spec(const char *t, usec_t *_u) {
4608 if (streq(t, "now"))
4610 else if (t[0] == '+') {
4613 if (safe_atou64(t + 1, &u) < 0)
4616 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4625 hour = strtol(t, &e, 10);
4626 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4629 minute = strtol(e+1, &e, 10);
4630 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4633 n = now(CLOCK_REALTIME);
4634 s = (time_t) (n / USEC_PER_SEC);
4637 assert_se(localtime_r(&s, &tm));
4639 tm.tm_hour = (int) hour;
4640 tm.tm_min = (int) minute;
4643 assert_se(s = mktime(&tm));
4645 *_u = (usec_t) s * USEC_PER_SEC;
4648 *_u += USEC_PER_DAY;
4654 static int shutdown_parse_argv(int argc, char *argv[]) {
4661 static const struct option options[] = {
4662 { "help", no_argument, NULL, ARG_HELP },
4663 { "halt", no_argument, NULL, 'H' },
4664 { "poweroff", no_argument, NULL, 'P' },
4665 { "reboot", no_argument, NULL, 'r' },
4666 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4667 { NULL, 0, NULL, 0 }
4675 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4683 arg_action = ACTION_HALT;
4687 arg_action = ACTION_POWEROFF;
4691 arg_action = ACTION_REBOOT;
4695 if (arg_action != ACTION_HALT)
4696 arg_action = ACTION_POWEROFF;
4709 /* Compatibility nops */
4713 arg_action = ACTION_CANCEL_SHUTDOWN;
4720 log_error("Unknown option code %c", c);
4725 if (argc > optind) {
4726 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4727 log_error("Failed to parse time specification: %s", argv[optind]);
4731 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4733 /* We skip the time argument */
4734 if (argc > optind + 1)
4735 arg_wall = argv + optind + 1;
4742 static int telinit_parse_argv(int argc, char *argv[]) {
4749 static const struct option options[] = {
4750 { "help", no_argument, NULL, ARG_HELP },
4751 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4752 { NULL, 0, NULL, 0 }
4755 static const struct {
4759 { '0', ACTION_POWEROFF },
4760 { '6', ACTION_REBOOT },
4761 { '1', ACTION_RESCUE },
4762 { '2', ACTION_RUNLEVEL2 },
4763 { '3', ACTION_RUNLEVEL3 },
4764 { '4', ACTION_RUNLEVEL4 },
4765 { '5', ACTION_RUNLEVEL5 },
4766 { 's', ACTION_RESCUE },
4767 { 'S', ACTION_RESCUE },
4768 { 'q', ACTION_RELOAD },
4769 { 'Q', ACTION_RELOAD },
4770 { 'u', ACTION_REEXEC },
4771 { 'U', ACTION_REEXEC }
4780 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4795 log_error("Unknown option code %c", c);
4800 if (optind >= argc) {
4805 if (optind + 1 < argc) {
4806 log_error("Too many arguments.");
4810 if (strlen(argv[optind]) != 1) {
4811 log_error("Expected single character argument.");
4815 for (i = 0; i < ELEMENTSOF(table); i++)
4816 if (table[i].from == argv[optind][0])
4819 if (i >= ELEMENTSOF(table)) {
4820 log_error("Unknown command %s.", argv[optind]);
4824 arg_action = table[i].to;
4831 static int runlevel_parse_argv(int argc, char *argv[]) {
4837 static const struct option options[] = {
4838 { "help", no_argument, NULL, ARG_HELP },
4839 { NULL, 0, NULL, 0 }
4847 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4858 log_error("Unknown option code %c", c);
4863 if (optind < argc) {
4864 log_error("Too many arguments.");
4871 static int parse_argv(int argc, char *argv[]) {
4875 if (program_invocation_short_name) {
4877 if (strstr(program_invocation_short_name, "halt")) {
4878 arg_action = ACTION_HALT;
4879 return halt_parse_argv(argc, argv);
4880 } else if (strstr(program_invocation_short_name, "poweroff")) {
4881 arg_action = ACTION_POWEROFF;
4882 return halt_parse_argv(argc, argv);
4883 } else if (strstr(program_invocation_short_name, "reboot")) {
4884 arg_action = ACTION_REBOOT;
4885 return halt_parse_argv(argc, argv);
4886 } else if (strstr(program_invocation_short_name, "shutdown")) {
4887 arg_action = ACTION_POWEROFF;
4888 return shutdown_parse_argv(argc, argv);
4889 } else if (strstr(program_invocation_short_name, "init")) {
4891 if (sd_booted() > 0) {
4892 arg_action = ACTION_INVALID;
4893 return telinit_parse_argv(argc, argv);
4895 /* Hmm, so some other init system is
4896 * running, we need to forward this
4897 * request to it. For now we simply
4898 * guess that it is Upstart. */
4900 execv("/lib/upstart/telinit", argv);
4902 log_error("Couldn't find an alternative telinit implementation to spawn.");
4906 } else if (strstr(program_invocation_short_name, "runlevel")) {
4907 arg_action = ACTION_RUNLEVEL;
4908 return runlevel_parse_argv(argc, argv);
4912 arg_action = ACTION_SYSTEMCTL;
4913 return systemctl_parse_argv(argc, argv);
4916 static int action_to_runlevel(void) {
4918 static const char table[_ACTION_MAX] = {
4919 [ACTION_HALT] = '0',
4920 [ACTION_POWEROFF] = '0',
4921 [ACTION_REBOOT] = '6',
4922 [ACTION_RUNLEVEL2] = '2',
4923 [ACTION_RUNLEVEL3] = '3',
4924 [ACTION_RUNLEVEL4] = '4',
4925 [ACTION_RUNLEVEL5] = '5',
4926 [ACTION_RESCUE] = '1'
4929 assert(arg_action < _ACTION_MAX);
4931 return table[arg_action];
4934 static int talk_upstart(void) {
4935 DBusMessage *m = NULL, *reply = NULL;
4937 int previous, rl, r;
4939 env1_buf[] = "RUNLEVEL=X",
4940 env2_buf[] = "PREVLEVEL=X";
4941 char *env1 = env1_buf, *env2 = env2_buf;
4942 const char *emit = "runlevel";
4943 dbus_bool_t b_false = FALSE;
4944 DBusMessageIter iter, sub;
4945 DBusConnection *bus;
4947 dbus_error_init(&error);
4949 if (!(rl = action_to_runlevel()))
4952 if (utmp_get_runlevel(&previous, NULL) < 0)
4955 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4956 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4961 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4966 if ((r = bus_check_peercred(bus)) < 0) {
4967 log_error("Failed to verify owner of bus.");
4971 if (!(m = dbus_message_new_method_call(
4972 "com.ubuntu.Upstart",
4973 "/com/ubuntu/Upstart",
4974 "com.ubuntu.Upstart0_6",
4977 log_error("Could not allocate message.");
4982 dbus_message_iter_init_append(m, &iter);
4984 env1_buf[sizeof(env1_buf)-2] = rl;
4985 env2_buf[sizeof(env2_buf)-2] = previous;
4987 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4988 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4989 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4990 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4991 !dbus_message_iter_close_container(&iter, &sub) ||
4992 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4993 log_error("Could not append arguments to message.");
4998 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5000 if (error_is_no_service(&error)) {
5005 log_error("Failed to issue method call: %s", bus_error_message(&error));
5014 dbus_message_unref(m);
5017 dbus_message_unref(reply);
5020 dbus_connection_flush(bus);
5021 dbus_connection_close(bus);
5022 dbus_connection_unref(bus);
5025 dbus_error_free(&error);
5030 static int talk_initctl(void) {
5031 struct init_request request;
5035 if (!(rl = action_to_runlevel()))
5039 request.magic = INIT_MAGIC;
5040 request.sleeptime = 0;
5041 request.cmd = INIT_CMD_RUNLVL;
5042 request.runlevel = rl;
5044 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5046 if (errno == ENOENT)
5049 log_error("Failed to open "INIT_FIFO": %m");
5054 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5055 close_nointr_nofail(fd);
5058 log_error("Failed to write to "INIT_FIFO": %m");
5059 return errno ? -errno : -EIO;
5065 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5067 static const struct {
5075 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
5077 { "list-units", LESS, 1, list_units },
5078 { "list-jobs", EQUAL, 1, list_jobs },
5079 { "clear-jobs", EQUAL, 1, daemon_reload },
5080 { "load", MORE, 2, load_unit },
5081 { "cancel", MORE, 2, cancel_job },
5082 { "start", MORE, 2, start_unit },
5083 { "stop", MORE, 2, start_unit },
5084 { "reload", MORE, 2, start_unit },
5085 { "restart", MORE, 2, start_unit },
5086 { "try-restart", MORE, 2, start_unit },
5087 { "reload-or-restart", MORE, 2, start_unit },
5088 { "reload-or-try-restart", MORE, 2, start_unit },
5089 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5090 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5091 { "isolate", EQUAL, 2, start_unit },
5092 { "kill", MORE, 2, kill_unit },
5093 { "is-active", MORE, 2, check_unit },
5094 { "check", MORE, 2, check_unit },
5095 { "show", MORE, 1, show },
5096 { "status", MORE, 2, show },
5097 { "monitor", EQUAL, 1, monitor },
5098 { "dump", EQUAL, 1, dump },
5099 { "dot", EQUAL, 1, dot },
5100 { "snapshot", LESS, 2, snapshot },
5101 { "delete", MORE, 2, delete_snapshot },
5102 { "daemon-reload", EQUAL, 1, daemon_reload },
5103 { "daemon-reexec", EQUAL, 1, daemon_reload },
5104 { "show-environment", EQUAL, 1, show_enviroment },
5105 { "set-environment", MORE, 2, set_environment },
5106 { "unset-environment", MORE, 2, set_environment },
5107 { "halt", EQUAL, 1, start_special },
5108 { "poweroff", EQUAL, 1, start_special },
5109 { "reboot", EQUAL, 1, start_special },
5110 { "kexec", EQUAL, 1, start_special },
5111 { "default", EQUAL, 1, start_special },
5112 { "rescue", EQUAL, 1, start_special },
5113 { "emergency", EQUAL, 1, start_special },
5114 { "exit", EQUAL, 1, start_special },
5115 { "reset-failed", MORE, 1, reset_failed },
5116 { "enable", MORE, 2, enable_unit },
5117 { "disable", MORE, 2, enable_unit },
5118 { "is-enabled", MORE, 2, enable_unit }
5128 left = argc - optind;
5131 /* Special rule: no arguments means "list-units" */
5134 if (streq(argv[optind], "help")) {
5139 for (i = 0; i < ELEMENTSOF(verbs); i++)
5140 if (streq(argv[optind], verbs[i].verb))
5143 if (i >= ELEMENTSOF(verbs)) {
5144 log_error("Unknown operation %s", argv[optind]);
5149 switch (verbs[i].argc_cmp) {
5152 if (left != verbs[i].argc) {
5153 log_error("Invalid number of arguments.");
5160 if (left < verbs[i].argc) {
5161 log_error("Too few arguments.");
5168 if (left > verbs[i].argc) {
5169 log_error("Too many arguments.");
5176 assert_not_reached("Unknown comparison operator.");
5179 /* Require a bus connection for all operations but
5181 if (!streq(verbs[i].verb, "enable") &&
5182 !streq(verbs[i].verb, "disable") &&
5184 log_error("Failed to get D-Bus connection: %s", error->message);
5188 return verbs[i].dispatch(bus, argv + optind, left);
5191 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
5193 struct msghdr msghdr;
5195 union sockaddr_union sockaddr;
5196 struct shutdownd_command c;
5204 strncpy(c.wall_message, message, sizeof(c.wall_message));
5206 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
5210 sockaddr.sa.sa_family = AF_UNIX;
5211 sockaddr.un.sun_path[0] = 0;
5212 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
5215 iovec.iov_base = (char*) &c;
5216 iovec.iov_len = sizeof(c);
5219 msghdr.msg_name = &sockaddr;
5220 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
5222 msghdr.msg_iov = &iovec;
5223 msghdr.msg_iovlen = 1;
5225 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5226 close_nointr_nofail(fd);
5230 close_nointr_nofail(fd);
5234 static int reload_with_fallback(DBusConnection *bus) {
5237 /* First, try systemd via D-Bus. */
5238 if (daemon_reload(bus, NULL, 0) > 0)
5242 /* Nothing else worked, so let's try signals */
5243 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5245 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5246 log_error("kill() failed: %m");
5253 static int start_with_fallback(DBusConnection *bus) {
5256 /* First, try systemd via D-Bus. */
5257 if (start_unit(bus, NULL, 0) >= 0)
5261 /* Hmm, talking to systemd via D-Bus didn't work. Then
5262 * let's try to talk to Upstart via D-Bus. */
5263 if (talk_upstart() > 0)
5266 /* Nothing else worked, so let's try
5268 if (talk_initctl() > 0)
5271 log_error("Failed to talk to init daemon.");
5275 warn_wall(arg_action);
5279 static int halt_main(DBusConnection *bus) {
5282 if (geteuid() != 0) {
5283 log_error("Must be root.");
5289 char date[FORMAT_TIMESTAMP_MAX];
5291 m = strv_join(arg_wall, " ");
5292 r = send_shutdownd(arg_when,
5293 arg_action == ACTION_HALT ? 'H' :
5294 arg_action == ACTION_POWEROFF ? 'P' :
5301 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5303 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5304 format_timestamp(date, sizeof(date), arg_when));
5309 if (!arg_dry && !arg_immediate)
5310 return start_with_fallback(bus);
5313 if (sd_booted() > 0)
5314 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5315 else if ((r = utmp_put_shutdown(0)) < 0)
5316 log_warning("Failed to write utmp record: %s", strerror(-r));
5325 /* Make sure C-A-D is handled by the kernel from this
5327 reboot(RB_ENABLE_CAD);
5329 switch (arg_action) {
5332 log_info("Halting.");
5333 reboot(RB_HALT_SYSTEM);
5336 case ACTION_POWEROFF:
5337 log_info("Powering off.");
5338 reboot(RB_POWER_OFF);
5342 log_info("Rebooting.");
5343 reboot(RB_AUTOBOOT);
5347 assert_not_reached("Unknown halt action.");
5350 /* We should never reach this. */
5354 static int runlevel_main(void) {
5355 int r, runlevel, previous;
5357 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5358 printf("unknown\n");
5363 previous <= 0 ? 'N' : previous,
5364 runlevel <= 0 ? 'N' : runlevel);
5369 static void pager_open(void) {
5376 if (!on_tty() || arg_no_pager)
5379 if ((pager = getenv("PAGER")))
5380 if (!*pager || streq(pager, "cat"))
5383 /* Determine and cache number of columns before we spawn the
5384 * pager so that we get the value from the actual tty */
5388 log_error("Failed to create pager pipe: %m");
5393 if (pager_pid < 0) {
5394 log_error("Failed to fork pager: %m");
5399 /* In the child start the pager */
5400 if (pager_pid == 0) {
5402 dup2(fd[0], STDIN_FILENO);
5405 setenv("LESS", "FRSX", 0);
5407 prctl(PR_SET_PDEATHSIG, SIGTERM);
5410 execlp(pager, pager, NULL);
5411 execl("/bin/sh", "sh", "-c", pager, NULL);
5413 /* Debian's alternatives command for pagers is
5414 * called 'pager'. Note that we do not call
5415 * sensible-pagers here, since that is just a
5416 * shell script that implements a logic that
5417 * is similar to this one anyway, but is
5418 * Debian-specific. */
5419 execlp("pager", "pager", NULL);
5421 execlp("less", "less", NULL);
5422 execlp("more", "more", NULL);
5425 log_error("Unable to execute pager: %m");
5426 _exit(EXIT_FAILURE);
5429 /* Return in the parent */
5430 if (dup2(fd[1], STDOUT_FILENO) < 0)
5431 log_error("Failed to duplicate pager pipe: %m");
5436 static void pager_close(void) {
5442 /* Inform pager that we are done */
5444 wait_for_terminate(pager_pid, &dummy);
5448 int main(int argc, char*argv[]) {
5449 int r, retval = EXIT_FAILURE;
5450 DBusConnection *bus = NULL;
5453 dbus_error_init(&error);
5455 log_parse_environment();
5458 if ((r = parse_argv(argc, argv)) < 0)
5461 retval = EXIT_SUCCESS;
5465 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5466 * let's shortcut this */
5467 if (arg_action == ACTION_RUNLEVEL) {
5468 r = runlevel_main();
5469 retval = r < 0 ? EXIT_FAILURE : r;
5473 bus_connect(arg_user ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5475 switch (arg_action) {
5477 case ACTION_SYSTEMCTL:
5478 r = systemctl_main(bus, argc, argv, &error);
5482 case ACTION_POWEROFF:
5487 case ACTION_RUNLEVEL2:
5488 case ACTION_RUNLEVEL3:
5489 case ACTION_RUNLEVEL4:
5490 case ACTION_RUNLEVEL5:
5492 case ACTION_EMERGENCY:
5493 case ACTION_DEFAULT:
5494 r = start_with_fallback(bus);
5499 r = reload_with_fallback(bus);
5502 case ACTION_CANCEL_SHUTDOWN:
5503 r = send_shutdownd(0, 0, false, NULL);
5506 case ACTION_INVALID:
5507 case ACTION_RUNLEVEL:
5509 assert_not_reached("Unknown action");
5512 retval = r < 0 ? EXIT_FAILURE : r;
5517 dbus_connection_flush(bus);
5518 dbus_connection_close(bus);
5519 dbus_connection_unref(bus);
5522 dbus_error_free(&error);
5526 strv_free(arg_property);