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 Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <sys/reboot.h>
28 #include <sys/ioctl.h>
32 #include <sys/socket.h>
35 #include <sys/prctl.h>
36 #include <dbus/dbus.h>
38 #include <systemd/sd-daemon.h>
39 #include <systemd/sd-shutdown.h>
45 #include "utmp-wtmp.h"
48 #include "path-util.h"
50 #include "dbus-common.h"
51 #include "cgroup-show.h"
52 #include "cgroup-util.h"
54 #include "path-lookup.h"
55 #include "conf-parser.h"
56 #include "exit-status.h"
57 #include "bus-errors.h"
59 #include "unit-name.h"
61 #include "spawn-ask-password-agent.h"
62 #include "spawn-polkit-agent.h"
64 #include "logs-show.h"
65 #include "path-util.h"
67 static const char *arg_type = NULL;
68 static const char *arg_load_state = NULL;
69 static char **arg_property = NULL;
70 static bool arg_all = false;
71 static const char *arg_job_mode = "replace";
72 static UnitFileScope arg_scope = UNIT_FILE_SYSTEM;
73 static bool arg_no_block = false;
74 static bool arg_no_legend = false;
75 static bool arg_no_pager = false;
76 static bool arg_no_wtmp = false;
77 static bool arg_no_wall = false;
78 static bool arg_no_reload = false;
79 static bool arg_dry = false;
80 static bool arg_quiet = false;
81 static bool arg_full = false;
82 static int arg_force = 0;
83 static bool arg_ask_password = true;
84 static bool arg_failed = false;
85 static bool arg_runtime = false;
86 static char **arg_wall = NULL;
87 static const char *arg_kill_who = NULL;
88 static int arg_signal = SIGTERM;
89 static const char *arg_root = NULL;
90 static usec_t arg_when = 0;
111 ACTION_CANCEL_SHUTDOWN,
113 } arg_action = ACTION_SYSTEMCTL;
119 static enum transport {
123 } arg_transport = TRANSPORT_NORMAL;
124 static const char *arg_host = NULL;
125 static bool arg_follow = false;
126 static unsigned arg_lines = 10;
127 static OutputMode arg_output = OUTPUT_SHORT;
129 static bool private_bus = false;
131 static int daemon_reload(DBusConnection *bus, char **args);
132 static void halt_now(enum action a);
134 static bool on_tty(void) {
137 /* Note that this is invoked relatively early, before we start
138 * the pager. That means the value we return reflects whether
139 * we originally were started on a tty, not if we currently
140 * are. But this is intended, since we want colour and so on
141 * when run in our own pager. */
143 if (_unlikely_(t < 0))
144 t = isatty(STDOUT_FILENO) > 0;
149 static void pager_open_if_enabled(void) {
151 /* Cache result before we open the pager */
160 static void ask_password_agent_open_if_enabled(void) {
162 /* Open the password agent as a child process if necessary */
164 if (!arg_ask_password)
167 if (arg_scope != UNIT_FILE_SYSTEM)
170 ask_password_agent_open();
174 static void polkit_agent_open_if_enabled(void) {
176 /* Open the polkit agent as a child process if necessary */
178 if (!arg_ask_password)
181 if (arg_scope != UNIT_FILE_SYSTEM)
188 static const char *ansi_highlight_red(bool b) {
193 return b ? ANSI_HIGHLIGHT_RED_ON : ANSI_HIGHLIGHT_OFF;
196 static const char *ansi_highlight_green(bool b) {
201 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
204 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
207 if (!dbus_error_is_set(error))
210 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
211 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
212 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
213 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
214 return EXIT_NOPERMISSION;
216 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
217 return EXIT_NOTINSTALLED;
219 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
220 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
221 return EXIT_NOTIMPLEMENTED;
223 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
224 return EXIT_NOTCONFIGURED;
232 static void warn_wall(enum action a) {
233 static const char *table[_ACTION_MAX] = {
234 [ACTION_HALT] = "The system is going down for system halt NOW!",
235 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
236 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
237 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
238 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
239 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!",
240 [ACTION_CANCEL_SHUTDOWN] = "The system shutdown has been cancelled NOW!"
249 p = strv_join(arg_wall, " ");
251 log_error("Failed to join strings.");
267 utmp_wall(table[a], NULL);
270 static bool avoid_bus(void) {
272 if (running_in_chroot() > 0)
275 if (sd_booted() <= 0)
278 if (!isempty(arg_root))
281 if (arg_scope == UNIT_FILE_GLOBAL)
289 const char *description;
290 const char *load_state;
291 const char *active_state;
292 const char *sub_state;
293 const char *following;
294 const char *unit_path;
296 const char *job_type;
297 const char *job_path;
300 static int compare_unit_info(const void *a, const void *b) {
302 const struct unit_info *u = a, *v = b;
304 d1 = strrchr(u->id, '.');
305 d2 = strrchr(v->id, '.');
310 if ((r = strcasecmp(d1, d2)) != 0)
314 return strcasecmp(u->id, v->id);
317 static bool output_show_unit(const struct unit_info *u) {
321 return streq(u->active_state, "failed");
323 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
324 streq(dot+1, arg_type))) &&
325 (!arg_load_state || streq(u->load_state, arg_load_state)) &&
326 (arg_all || !(streq(u->active_state, "inactive")
327 || u->following[0]) || u->job_id > 0);
330 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
331 unsigned id_len, max_id_len, active_len, sub_len, job_len, desc_len, n_shown = 0;
332 const struct unit_info *u;
334 max_id_len = sizeof("UNIT")-1;
335 active_len = sizeof("ACTIVE")-1;
336 sub_len = sizeof("SUB")-1;
337 job_len = sizeof("JOB")-1;
340 for (u = unit_infos; u < unit_infos + c; u++) {
341 if (!output_show_unit(u))
344 max_id_len = MAX(max_id_len, strlen(u->id));
345 active_len = MAX(active_len, strlen(u->active_state));
346 sub_len = MAX(sub_len, strlen(u->sub_state));
348 job_len = MAX(job_len, strlen(u->job_type));
353 id_len = MIN(max_id_len, 25);
354 basic_len = 5 + id_len + 6 + active_len + sub_len + job_len;
355 if (basic_len < (unsigned) columns()) {
356 unsigned extra_len, incr;
357 extra_len = columns() - basic_len;
358 /* Either UNIT already got 25, or is fully satisfied.
359 * Grant up to 25 to DESC now. */
360 incr = MIN(extra_len, 25);
363 /* split the remaining space between UNIT and DESC,
364 * but do not give UNIT more than it needs. */
366 incr = MIN(extra_len / 2, max_id_len - id_len);
368 desc_len += extra_len - incr;
374 if (!arg_no_legend) {
375 printf("%-*s %-6s %-*s %-*s %-*s ", id_len, "UNIT", "LOAD",
376 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
377 if (!arg_full && arg_no_pager)
378 printf("%.*s\n", desc_len, "DESCRIPTION");
380 printf("%s\n", "DESCRIPTION");
383 for (u = unit_infos; u < unit_infos + c; u++) {
385 const char *on_loaded, *off_loaded;
386 const char *on_active, *off_active;
388 if (!output_show_unit(u))
393 if (streq(u->load_state, "error")) {
394 on_loaded = ansi_highlight_red(true);
395 off_loaded = ansi_highlight_red(false);
397 on_loaded = off_loaded = "";
399 if (streq(u->active_state, "failed")) {
400 on_active = ansi_highlight_red(true);
401 off_active = ansi_highlight_red(false);
403 on_active = off_active = "";
405 e = arg_full ? NULL : ellipsize(u->id, id_len, 33);
407 printf("%-*s %s%-6s%s %s%-*s %-*s%s %-*s ",
408 id_len, e ? e : u->id,
409 on_loaded, u->load_state, off_loaded,
410 on_active, active_len, u->active_state,
411 sub_len, u->sub_state, off_active,
412 job_len, u->job_id ? u->job_type : "");
413 if (!arg_full && arg_no_pager)
414 printf("%.*s\n", desc_len, u->description);
416 printf("%s\n", u->description);
421 if (!arg_no_legend) {
422 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
423 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
424 "SUB = The low-level unit activation state, values depend on unit type.\n"
425 "JOB = Pending job for the unit.\n");
428 printf("\n%u units listed.\n", n_shown);
430 printf("\n%u units listed. Pass --all to see inactive units, too.\n", n_shown);
434 static int list_units(DBusConnection *bus, char **args) {
435 DBusMessage *reply = NULL;
437 DBusMessageIter iter, sub, sub2;
438 unsigned c = 0, n_units = 0;
439 struct unit_info *unit_infos = NULL;
441 pager_open_if_enabled();
443 r = bus_method_call_with_reply (
445 "org.freedesktop.systemd1",
446 "/org/freedesktop/systemd1",
447 "org.freedesktop.systemd1.Manager",
455 if (!dbus_message_iter_init(reply, &iter) ||
456 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
457 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
458 log_error("Failed to parse reply.");
463 dbus_message_iter_recurse(&iter, &sub);
465 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
468 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
469 log_error("Failed to parse reply.");
477 n_units = MAX(2*c, 16);
478 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
481 log_error("Failed to allocate unit array.");
491 dbus_message_iter_recurse(&sub, &sub2);
493 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
494 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
495 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
496 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
497 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
498 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
499 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
500 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
501 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
502 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
503 log_error("Failed to parse reply.");
508 dbus_message_iter_next(&sub);
513 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
514 output_units_list(unit_infos, c);
519 dbus_message_unref(reply);
526 static int compare_unit_file_list(const void *a, const void *b) {
528 const UnitFileList *u = a, *v = b;
530 d1 = strrchr(u->path, '.');
531 d2 = strrchr(v->path, '.');
536 r = strcasecmp(d1, d2);
541 return strcasecmp(path_get_file_name(u->path), path_get_file_name(v->path));
544 static bool output_show_unit_file(const UnitFileList *u) {
547 return !arg_type || ((dot = strrchr(u->path, '.')) && streq(dot+1, arg_type));
550 static void output_unit_file_list(const UnitFileList *units, unsigned c) {
551 unsigned max_id_len, id_cols, state_cols, n_shown = 0;
552 const UnitFileList *u;
554 max_id_len = sizeof("UNIT FILE")-1;
555 state_cols = sizeof("STATE")-1;
556 for (u = units; u < units + c; u++) {
557 if (!output_show_unit_file(u))
560 max_id_len = MAX(max_id_len, strlen(path_get_file_name(u->path)));
561 state_cols = MAX(state_cols, strlen(unit_file_state_to_string(u->state)));
566 id_cols = MIN(max_id_len, 25);
567 basic_cols = 1 + id_cols + state_cols;
568 if (basic_cols < (unsigned) columns())
569 id_cols += MIN(columns() - basic_cols, max_id_len - id_cols);
571 id_cols = max_id_len;
574 printf("%-*s %-*s\n", id_cols, "UNIT FILE", state_cols, "STATE");
576 for (u = units; u < units + c; u++) {
578 const char *on, *off;
581 if (!output_show_unit_file(u))
586 if (u->state == UNIT_FILE_MASKED ||
587 u->state == UNIT_FILE_MASKED_RUNTIME ||
588 u->state == UNIT_FILE_DISABLED ||
589 u->state == UNIT_FILE_INVALID) {
590 on = ansi_highlight_red(true);
591 off = ansi_highlight_red(false);
592 } else if (u->state == UNIT_FILE_ENABLED) {
593 on = ansi_highlight_green(true);
594 off = ansi_highlight_green(false);
598 id = path_get_file_name(u->path);
600 e = arg_full ? NULL : ellipsize(id, id_cols, 33);
602 printf("%-*s %s%-*s%s\n",
604 on, state_cols, unit_file_state_to_string(u->state), off);
610 printf("\n%u unit files listed.\n", n_shown);
613 static int list_unit_files(DBusConnection *bus, char **args) {
614 DBusMessage *reply = NULL;
616 DBusMessageIter iter, sub, sub2;
617 unsigned c = 0, n_units = 0;
618 UnitFileList *units = NULL;
620 pager_open_if_enabled();
627 h = hashmap_new(string_hash_func, string_compare_func);
631 r = unit_file_get_list(arg_scope, arg_root, h);
633 unit_file_list_free(h);
634 log_error("Failed to get unit file list: %s", strerror(-r));
638 n_units = hashmap_size(h);
639 units = new(UnitFileList, n_units);
641 unit_file_list_free(h);
645 HASHMAP_FOREACH(u, h, i) {
646 memcpy(units + c++, u, sizeof(UnitFileList));
652 r = bus_method_call_with_reply (
654 "org.freedesktop.systemd1",
655 "/org/freedesktop/systemd1",
656 "org.freedesktop.systemd1.Manager",
664 if (!dbus_message_iter_init(reply, &iter) ||
665 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
666 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
667 log_error("Failed to parse reply.");
672 dbus_message_iter_recurse(&iter, &sub);
674 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
678 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
679 log_error("Failed to parse reply.");
687 n_units = MAX(2*c, 16);
688 w = realloc(units, sizeof(struct UnitFileList) * n_units);
691 log_error("Failed to allocate unit array.");
701 dbus_message_iter_recurse(&sub, &sub2);
703 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->path, true) < 0 ||
704 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, false) < 0) {
705 log_error("Failed to parse reply.");
710 u->state = unit_file_state_from_string(state);
712 dbus_message_iter_next(&sub);
718 qsort(units, c, sizeof(UnitFileList), compare_unit_file_list);
719 output_unit_file_list(units, c);
726 dbus_message_unref(reply);
733 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
734 static const char * const colors[] = {
735 "Requires", "[color=\"black\"]",
736 "RequiresOverridable", "[color=\"black\"]",
737 "Requisite", "[color=\"darkblue\"]",
738 "RequisiteOverridable", "[color=\"darkblue\"]",
739 "Wants", "[color=\"grey66\"]",
740 "Conflicts", "[color=\"red\"]",
741 "ConflictedBy", "[color=\"red\"]",
742 "After", "[color=\"green\"]"
745 const char *c = NULL;
752 for (i = 0; i < ELEMENTSOF(colors); i += 2)
753 if (streq(colors[i], prop)) {
761 if (arg_dot != DOT_ALL)
762 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
765 switch (dbus_message_iter_get_arg_type(iter)) {
767 case DBUS_TYPE_ARRAY:
769 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
772 dbus_message_iter_recurse(iter, &sub);
774 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
777 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
778 dbus_message_iter_get_basic(&sub, &s);
779 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
781 dbus_message_iter_next(&sub);
791 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
792 DBusMessage *reply = NULL;
793 const char *interface = "org.freedesktop.systemd1.Unit";
795 DBusMessageIter iter, sub, sub2, sub3;
799 r = bus_method_call_with_reply (
801 "org.freedesktop.systemd1",
803 "org.freedesktop.DBus.Properties",
807 DBUS_TYPE_STRING, &interface,
812 if (!dbus_message_iter_init(reply, &iter) ||
813 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
814 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
815 log_error("Failed to parse reply.");
820 dbus_message_iter_recurse(&iter, &sub);
822 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
825 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
826 log_error("Failed to parse reply.");
831 dbus_message_iter_recurse(&sub, &sub2);
833 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
834 log_error("Failed to parse reply.");
839 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
840 log_error("Failed to parse reply.");
845 dbus_message_iter_recurse(&sub2, &sub3);
847 if (dot_one_property(name, prop, &sub3)) {
848 log_error("Failed to parse reply.");
853 dbus_message_iter_next(&sub);
858 dbus_message_unref(reply);
863 static int dot(DBusConnection *bus, char **args) {
864 DBusMessage *reply = NULL;
866 DBusMessageIter iter, sub, sub2;
868 r = bus_method_call_with_reply (
870 "org.freedesktop.systemd1",
871 "/org/freedesktop/systemd1",
872 "org.freedesktop.systemd1.Manager",
880 if (!dbus_message_iter_init(reply, &iter) ||
881 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
882 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
883 log_error("Failed to parse reply.");
888 printf("digraph systemd {\n");
890 dbus_message_iter_recurse(&iter, &sub);
891 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
892 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
894 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
895 log_error("Failed to parse reply.");
900 dbus_message_iter_recurse(&sub, &sub2);
902 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
903 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
904 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
905 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
906 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
907 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
908 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
909 log_error("Failed to parse reply.");
914 if ((r = dot_one(bus, id, unit_path)) < 0)
917 /* printf("\t\"%s\";\n", id); */
918 dbus_message_iter_next(&sub);
923 log_info(" Color legend: black = Requires\n"
924 " dark blue = Requisite\n"
925 " dark grey = Wants\n"
930 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
931 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
937 dbus_message_unref(reply);
942 static int list_jobs(DBusConnection *bus, char **args) {
943 DBusMessage *reply = NULL;
945 DBusMessageIter iter, sub, sub2;
948 pager_open_if_enabled();
950 r = bus_method_call_with_reply (
952 "org.freedesktop.systemd1",
953 "/org/freedesktop/systemd1",
954 "org.freedesktop.systemd1.Manager",
962 if (!dbus_message_iter_init(reply, &iter) ||
963 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
964 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
965 log_error("Failed to parse reply.");
970 dbus_message_iter_recurse(&iter, &sub);
973 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
975 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
976 const char *name, *type, *state, *job_path, *unit_path;
980 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
981 log_error("Failed to parse reply.");
986 dbus_message_iter_recurse(&sub, &sub2);
988 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
989 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
990 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
991 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
992 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
993 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
994 log_error("Failed to parse reply.");
999 e = arg_full ? NULL : ellipsize(name, 25, 33);
1000 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
1005 dbus_message_iter_next(&sub);
1009 printf("\n%u jobs listed.\n", k);
1015 dbus_message_unref(reply);
1020 static int load_unit(DBusConnection *bus, char **args) {
1026 STRV_FOREACH(name, args+1) {
1027 n = unit_name_mangle(*name);
1028 r = bus_method_call_with_reply (
1030 "org.freedesktop.systemd1",
1031 "/org/freedesktop/systemd1",
1032 "org.freedesktop.systemd1.Manager",
1036 DBUS_TYPE_STRING, n ? &n : name,
1047 static int cancel_job(DBusConnection *bus, char **args) {
1048 DBusMessage *reply = NULL;
1054 if (strv_length(args) <= 1)
1055 return daemon_reload(bus, args);
1057 STRV_FOREACH(name, args+1) {
1061 r = safe_atou(*name, &id);
1063 log_error("Failed to parse job id: %s", strerror(-r));
1066 assert_cc(sizeof(uint32_t) == sizeof(id));
1068 r = bus_method_call_with_reply (
1070 "org.freedesktop.systemd1",
1071 "/org/freedesktop/systemd1",
1072 "org.freedesktop.systemd1.Manager",
1076 DBUS_TYPE_UINT32, &id,
1081 if (!dbus_message_get_args(reply, NULL,
1082 DBUS_TYPE_OBJECT_PATH, &path,
1083 DBUS_TYPE_INVALID)) {
1084 log_error("Failed to parse reply");
1085 dbus_message_unref(reply);
1089 dbus_message_unref(reply);
1091 r = bus_method_call_with_reply (
1093 "org.freedesktop.systemd1",
1095 "org.freedesktop.systemd1.Job",
1108 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1109 DBusMessage *reply = NULL;
1110 dbus_bool_t b = FALSE;
1111 DBusMessageIter iter, sub;
1113 *interface = "org.freedesktop.systemd1.Unit",
1114 *property = "NeedDaemonReload",
1119 /* We ignore all errors here, since this is used to show a warning only */
1121 n = unit_name_mangle(unit);
1122 r = bus_method_call_with_reply (
1124 "org.freedesktop.systemd1",
1125 "/org/freedesktop/systemd1",
1126 "org.freedesktop.systemd1.Manager",
1130 DBUS_TYPE_STRING, n ? (const char**) &n : &unit,
1136 if (!dbus_message_get_args(reply, NULL,
1137 DBUS_TYPE_OBJECT_PATH, &path,
1141 dbus_message_unref(reply);
1142 r = bus_method_call_with_reply (
1144 "org.freedesktop.systemd1",
1146 "org.freedesktop.DBus.Properties",
1150 DBUS_TYPE_STRING, &interface,
1151 DBUS_TYPE_STRING, &property,
1156 if (!dbus_message_iter_init(reply, &iter) ||
1157 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1160 dbus_message_iter_recurse(&iter, &sub);
1162 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1165 dbus_message_iter_get_basic(&sub, &b);
1169 dbus_message_unref(reply);
1174 typedef struct WaitData {
1179 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1187 dbus_error_init(&error);
1189 log_debug("Got D-Bus request: %s.%s() on %s",
1190 dbus_message_get_interface(message),
1191 dbus_message_get_member(message),
1192 dbus_message_get_path(message));
1194 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1195 log_error("Warning! D-Bus connection terminated.");
1196 dbus_connection_close(connection);
1198 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1200 const char *path, *result, *unit;
1201 dbus_bool_t success = true;
1203 if (dbus_message_get_args(message, &error,
1204 DBUS_TYPE_UINT32, &id,
1205 DBUS_TYPE_OBJECT_PATH, &path,
1206 DBUS_TYPE_STRING, &unit,
1207 DBUS_TYPE_STRING, &result,
1208 DBUS_TYPE_INVALID)) {
1211 p = set_remove(d->set, (char*) path);
1215 d->result = strdup(result);
1220 dbus_error_free(&error);
1221 if (dbus_message_get_args(message, &error,
1222 DBUS_TYPE_UINT32, &id,
1223 DBUS_TYPE_OBJECT_PATH, &path,
1224 DBUS_TYPE_STRING, &result,
1225 DBUS_TYPE_INVALID)) {
1228 /* Compatibility with older systemd versions <
1229 * 183 during upgrades. This should be dropped
1231 p = set_remove(d->set, (char*) path);
1235 d->result = strdup(result);
1240 dbus_error_free(&error);
1241 if (dbus_message_get_args(message, &error,
1242 DBUS_TYPE_UINT32, &id,
1243 DBUS_TYPE_OBJECT_PATH, &path,
1244 DBUS_TYPE_BOOLEAN, &success,
1245 DBUS_TYPE_INVALID)) {
1248 /* Compatibility with older systemd versions <
1249 * 19 during upgrades. This should be dropped
1252 p = set_remove(d->set, (char*) path);
1256 d->result = strdup("failed");
1262 log_error("Failed to parse message: %s", bus_error_message(&error));
1266 dbus_error_free(&error);
1267 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1270 static int enable_wait_for_jobs(DBusConnection *bus) {
1278 dbus_error_init(&error);
1279 dbus_bus_add_match(bus,
1281 "sender='org.freedesktop.systemd1',"
1282 "interface='org.freedesktop.systemd1.Manager',"
1283 "member='JobRemoved',"
1284 "path='/org/freedesktop/systemd1'",
1287 if (dbus_error_is_set(&error)) {
1288 log_error("Failed to add match: %s", bus_error_message(&error));
1289 dbus_error_free(&error);
1293 /* This is slightly dirty, since we don't undo the match registrations. */
1297 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1307 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1308 log_error("Failed to add filter.");
1313 while (!set_isempty(s) &&
1314 dbus_connection_read_write_dispatch(bus, -1))
1317 if (!arg_quiet && d.result) {
1318 if (streq(d.result, "timeout"))
1319 log_error("Job timed out.");
1320 else if (streq(d.result, "canceled"))
1321 log_error("Job canceled.");
1322 else if (streq(d.result, "dependency"))
1323 log_error("A dependency job failed. See system journal for details.");
1324 else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
1325 log_error("Job failed. See system journal and 'systemctl status' for details.");
1328 if (streq_ptr(d.result, "timeout"))
1330 else if (streq_ptr(d.result, "canceled"))
1332 else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
1340 /* This is slightly dirty, since we don't undo the filter registration. */
1345 static int check_one_unit(DBusConnection *bus, char *name, bool quiet) {
1346 DBusMessage *reply = NULL;
1347 DBusMessageIter iter, sub;
1349 *interface = "org.freedesktop.systemd1.Unit",
1350 *property = "ActiveState";
1351 const char *path = NULL;
1358 n = unit_name_mangle(name);
1359 r = bus_method_call_with_reply (
1361 "org.freedesktop.systemd1",
1362 "/org/freedesktop/systemd1",
1363 "org.freedesktop.systemd1.Manager",
1367 DBUS_TYPE_STRING, n ? &n : &name,
1371 if ((r != -ENOMEM) && (!quiet))
1376 if (!dbus_message_get_args(reply, NULL,
1377 DBUS_TYPE_OBJECT_PATH, &path,
1378 DBUS_TYPE_INVALID)) {
1379 log_error("Failed to parse reply.");
1384 dbus_message_unref(reply);
1385 r = bus_method_call_with_reply (
1387 "org.freedesktop.systemd1",
1389 "org.freedesktop.DBus.Properties",
1393 DBUS_TYPE_STRING, &interface,
1394 DBUS_TYPE_STRING, &property,
1399 if (!dbus_message_iter_init(reply, &iter) ||
1400 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1401 log_error("Failed to parse reply.");
1406 dbus_message_iter_recurse(&iter, &sub);
1408 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1409 log_error("Failed to parse reply.");
1414 dbus_message_iter_get_basic(&sub, &state);
1419 if (streq(state, "active") || streq(state, "reloading"))
1422 r = 3; /* According to LSB: "program is not running" */
1426 dbus_message_unref(reply);
1431 static void check_triggering_units(
1432 DBusConnection *bus,
1433 const char *unit_name) {
1435 DBusMessage *reply = NULL;
1436 DBusMessageIter iter, sub;
1437 char *service_trigger = NULL;
1438 const char *interface = "org.freedesktop.systemd1.Unit",
1439 *triggered_by_property = "TriggeredBy";
1441 char *unit_path = NULL, *n = NULL;
1442 bool print_warning_label = true;
1445 n = unit_name_mangle(unit_name);
1446 unit_path = unit_dbus_path_from_name(n ? n : unit_name);
1449 log_error("Could not allocate dbus path.");
1453 r = bus_method_call_with_reply (
1455 "org.freedesktop.systemd1",
1457 "org.freedesktop.DBus.Properties",
1461 DBUS_TYPE_STRING, &interface,
1462 DBUS_TYPE_STRING, &triggered_by_property,
1467 if (!dbus_message_iter_init(reply, &iter) ||
1468 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1469 log_error("Failed to parse reply.");
1474 dbus_message_iter_recurse(&iter, &sub);
1475 dbus_message_iter_recurse(&sub, &iter);
1478 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1480 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1481 log_error("Failed to parse reply.");
1485 dbus_message_iter_get_basic(&sub, &service_trigger);
1487 r = check_one_unit(bus, service_trigger, true);
1491 if (print_warning_label) {
1492 log_warning("Warning: Stopping %s, but it can still be activated by:", unit_name);
1493 print_warning_label = false;
1495 log_warning(" %s", service_trigger);
1498 dbus_message_iter_next(&sub);
1502 dbus_message_unref(reply);
1507 static int start_unit_one(
1508 DBusConnection *bus,
1515 DBusMessage *reply = NULL;
1524 assert(arg_no_block || s);
1526 n = unit_name_mangle(name);
1527 r = bus_method_call_with_reply (
1529 "org.freedesktop.systemd1",
1530 "/org/freedesktop/systemd1",
1531 "org.freedesktop.systemd1.Manager",
1535 DBUS_TYPE_STRING, n ? (const char **) &n : &name,
1536 DBUS_TYPE_STRING, &mode,
1540 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL )
1541 /* There's always a fallback possible for
1542 * legacy actions. */
1545 log_error("Failed to issue method call: %s", bus_error_message(error));
1549 if (!dbus_message_get_args(reply, error,
1550 DBUS_TYPE_OBJECT_PATH, &path,
1551 DBUS_TYPE_INVALID)) {
1552 log_error("Failed to parse reply: %s", bus_error_message(error));
1557 if (need_daemon_reload(bus, name))
1558 log_warning("Warning: Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1559 arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
1561 if (!arg_no_block) {
1564 if (!(p = strdup(path))) {
1565 log_error("Failed to duplicate path.");
1570 if ((r = set_put(s, p)) < 0) {
1572 log_error("Failed to add path to set.");
1577 /* When stopping a unit warn if it can still be triggered by
1578 * another active unit (socket, path, timer) */
1579 if (!arg_quiet && streq(method, "StopUnit"))
1580 check_triggering_units(bus, name);
1586 dbus_message_unref(reply);
1591 static enum action verb_to_action(const char *verb) {
1592 if (streq(verb, "halt"))
1594 else if (streq(verb, "poweroff"))
1595 return ACTION_POWEROFF;
1596 else if (streq(verb, "reboot"))
1597 return ACTION_REBOOT;
1598 else if (streq(verb, "kexec"))
1599 return ACTION_KEXEC;
1600 else if (streq(verb, "rescue"))
1601 return ACTION_RESCUE;
1602 else if (streq(verb, "emergency"))
1603 return ACTION_EMERGENCY;
1604 else if (streq(verb, "default"))
1605 return ACTION_DEFAULT;
1606 else if (streq(verb, "exit"))
1608 else if (streq(verb, "suspend"))
1609 return ACTION_SUSPEND;
1610 else if (streq(verb, "hibernate"))
1611 return ACTION_HIBERNATE;
1613 return ACTION_INVALID;
1616 static int start_unit(DBusConnection *bus, char **args) {
1618 static const char * const table[_ACTION_MAX] = {
1619 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1620 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1621 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1622 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1623 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1624 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1625 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1626 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1627 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1628 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1629 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1630 [ACTION_EXIT] = SPECIAL_EXIT_TARGET,
1631 [ACTION_SUSPEND] = SPECIAL_SUSPEND_TARGET,
1632 [ACTION_HIBERNATE] = SPECIAL_HIBERNATE_TARGET
1636 const char *method, *mode, *one_name;
1641 dbus_error_init(&error);
1645 ask_password_agent_open_if_enabled();
1647 if (arg_action == ACTION_SYSTEMCTL) {
1649 streq(args[0], "stop") ||
1650 streq(args[0], "condstop") ? "StopUnit" :
1651 streq(args[0], "reload") ? "ReloadUnit" :
1652 streq(args[0], "restart") ? "RestartUnit" :
1654 streq(args[0], "try-restart") ||
1655 streq(args[0], "condrestart") ? "TryRestartUnit" :
1657 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1659 streq(args[0], "reload-or-try-restart") ||
1660 streq(args[0], "condreload") ||
1662 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1666 (streq(args[0], "isolate") ||
1667 streq(args[0], "rescue") ||
1668 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1670 one_name = table[verb_to_action(args[0])];
1673 assert(arg_action < ELEMENTSOF(table));
1674 assert(table[arg_action]);
1676 method = "StartUnit";
1678 mode = (arg_action == ACTION_EMERGENCY ||
1679 arg_action == ACTION_RESCUE ||
1680 arg_action == ACTION_RUNLEVEL2 ||
1681 arg_action == ACTION_RUNLEVEL3 ||
1682 arg_action == ACTION_RUNLEVEL4 ||
1683 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1685 one_name = table[arg_action];
1688 if (!arg_no_block) {
1689 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1690 log_error("Could not watch jobs: %s", strerror(-ret));
1694 if (!(s = set_new(string_hash_func, string_compare_func))) {
1695 log_error("Failed to allocate set.");
1702 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1705 STRV_FOREACH(name, args+1)
1706 if ((r = start_unit_one(bus, method, *name, mode, &error, s)) != 0) {
1707 ret = translate_bus_error_to_exit_status(r, &error);
1708 dbus_error_free(&error);
1713 if ((r = wait_for_jobs(bus, s)) < 0) {
1722 dbus_error_free(&error);
1727 /* Ask systemd-logind, which might grant access to unprivileged users
1728 * through PolicyKit */
1729 static int reboot_with_logind(DBusConnection *bus, enum action a) {
1732 dbus_bool_t interactive = true;
1734 polkit_agent_open_if_enabled();
1742 case ACTION_POWEROFF:
1743 method = "PowerOff";
1746 case ACTION_SUSPEND:
1750 case ACTION_HIBERNATE:
1751 method = "Hibernate";
1758 return bus_method_call_with_reply (
1760 "org.freedesktop.login1",
1761 "/org/freedesktop/login1",
1762 "org.freedesktop.login1.Manager",
1766 DBUS_TYPE_BOOLEAN, &interactive,
1773 static int start_special(DBusConnection *bus, char **args) {
1779 a = verb_to_action(args[0]);
1781 if (arg_force >= 2 && geteuid() != 0) {
1782 log_error("Must be root.");
1786 if (arg_force >= 2 &&
1787 (a == ACTION_HALT ||
1788 a == ACTION_POWEROFF ||
1789 a == ACTION_REBOOT))
1792 if (arg_force >= 1 &&
1793 (a == ACTION_HALT ||
1794 a == ACTION_POWEROFF ||
1795 a == ACTION_REBOOT ||
1796 a == ACTION_KEXEC ||
1798 return daemon_reload(bus, args);
1800 /* first try logind, to allow authentication with polkit */
1801 if (geteuid() != 0 &&
1802 (a == ACTION_POWEROFF ||
1803 a == ACTION_REBOOT ||
1804 a == ACTION_SUSPEND ||
1805 a == ACTION_HIBERNATE)) {
1806 r = reboot_with_logind(bus, a);
1811 r = start_unit(bus, args);
1818 static int check_unit(DBusConnection *bus, char **args) {
1820 int r = 3; /* According to LSB: "program is not running" */
1825 STRV_FOREACH(name, args+1) {
1826 int state = check_one_unit(bus, *name, arg_quiet);
1836 static int kill_unit(DBusConnection *bus, char **args) {
1843 arg_kill_who = "all";
1845 STRV_FOREACH(name, args+1) {
1846 n = unit_name_mangle(*name);
1847 r = bus_method_call_with_reply (
1849 "org.freedesktop.systemd1",
1850 "/org/freedesktop/systemd1",
1851 "org.freedesktop.systemd1.Manager",
1855 DBUS_TYPE_STRING, n ? &n : name,
1856 DBUS_TYPE_STRING, &arg_kill_who,
1857 DBUS_TYPE_INT32, &arg_signal,
1866 typedef struct ExecStatusInfo {
1874 usec_t start_timestamp;
1875 usec_t exit_timestamp;
1880 LIST_FIELDS(struct ExecStatusInfo, exec);
1883 static void exec_status_info_free(ExecStatusInfo *i) {
1892 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1893 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
1894 DBusMessageIter sub2, sub3;
1898 int32_t code, status;
1904 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1907 dbus_message_iter_recurse(sub, &sub2);
1909 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1912 if (!(i->path = strdup(path)))
1915 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1916 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1920 dbus_message_iter_recurse(&sub2, &sub3);
1921 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1922 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1923 dbus_message_iter_next(&sub3);
1928 if (!(i->argv = new0(char*, n+1)))
1932 dbus_message_iter_recurse(&sub2, &sub3);
1933 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1936 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1937 dbus_message_iter_get_basic(&sub3, &s);
1938 dbus_message_iter_next(&sub3);
1940 if (!(i->argv[n++] = strdup(s)))
1944 if (!dbus_message_iter_next(&sub2) ||
1945 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1946 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1947 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
1948 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1949 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
1950 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1951 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1952 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1956 i->start_timestamp = (usec_t) start_timestamp;
1957 i->exit_timestamp = (usec_t) exit_timestamp;
1958 i->pid = (pid_t) pid;
1965 typedef struct UnitStatusInfo {
1967 const char *load_state;
1968 const char *active_state;
1969 const char *sub_state;
1970 const char *unit_file_state;
1972 const char *description;
1973 const char *following;
1975 char **documentation;
1977 const char *fragment_path;
1978 const char *source_path;
1979 const char *default_control_group;
1981 const char *load_error;
1984 usec_t inactive_exit_timestamp;
1985 usec_t inactive_exit_timestamp_monotonic;
1986 usec_t active_enter_timestamp;
1987 usec_t active_exit_timestamp;
1988 usec_t inactive_enter_timestamp;
1990 bool need_daemon_reload;
1995 const char *status_text;
1998 usec_t start_timestamp;
1999 usec_t exit_timestamp;
2001 int exit_code, exit_status;
2003 usec_t condition_timestamp;
2004 bool condition_result;
2007 unsigned n_accepted;
2008 unsigned n_connections;
2012 const char *sysfs_path;
2014 /* Mount, Automount */
2020 LIST_HEAD(ExecStatusInfo, exec);
2023 static void print_status_info(UnitStatusInfo *i) {
2025 const char *on, *off, *ss;
2027 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
2028 char since2[FORMAT_TIMESTAMP_MAX], *s2;
2033 /* This shows pretty information about a unit. See
2034 * print_property() for a low-level property printer */
2036 printf("%s", strna(i->id));
2038 if (i->description && !streq_ptr(i->id, i->description))
2039 printf(" - %s", i->description);
2044 printf("\t Follow: unit currently follows state of %s\n", i->following);
2046 if (streq_ptr(i->load_state, "error")) {
2047 on = ansi_highlight_red(true);
2048 off = ansi_highlight_red(false);
2052 path = i->source_path ? i->source_path : i->fragment_path;
2055 printf("\t Loaded: %s%s%s (Reason: %s)\n", on, strna(i->load_state), off, i->load_error);
2056 else if (path && i->unit_file_state)
2057 printf("\t Loaded: %s%s%s (%s; %s)\n", on, strna(i->load_state), off, path, i->unit_file_state);
2059 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, path);
2061 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
2063 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
2065 if (streq_ptr(i->active_state, "failed")) {
2066 on = ansi_highlight_red(true);
2067 off = ansi_highlight_red(false);
2068 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
2069 on = ansi_highlight_green(true);
2070 off = ansi_highlight_green(false);
2075 printf("\t Active: %s%s (%s)%s",
2077 strna(i->active_state),
2081 printf("\t Active: %s%s%s",
2083 strna(i->active_state),
2086 if (!isempty(i->result) && !streq(i->result, "success"))
2087 printf(" (Result: %s)", i->result);
2089 timestamp = (streq_ptr(i->active_state, "active") ||
2090 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
2091 (streq_ptr(i->active_state, "inactive") ||
2092 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
2093 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
2094 i->active_exit_timestamp;
2096 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
2097 s2 = format_timestamp(since2, sizeof(since2), timestamp);
2100 printf(" since %s; %s\n", s2, s1);
2102 printf(" since %s\n", s2);
2106 if (!i->condition_result && i->condition_timestamp > 0) {
2107 s1 = format_timestamp_pretty(since1, sizeof(since1), i->condition_timestamp);
2108 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
2111 printf("\t start condition failed at %s; %s\n", s2, s1);
2113 printf("\t start condition failed at %s\n", s2);
2117 printf("\t Device: %s\n", i->sysfs_path);
2119 printf("\t Where: %s\n", i->where);
2121 printf("\t What: %s\n", i->what);
2123 if (!strv_isempty(i->documentation)) {
2127 STRV_FOREACH(t, i->documentation) {
2129 printf("\t Docs: %s\n", *t);
2132 printf("\t %s\n", *t);
2137 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
2139 LIST_FOREACH(exec, p, i->exec) {
2143 /* Only show exited processes here */
2147 t = strv_join(p->argv, " ");
2148 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
2151 good = is_clean_exit_lsb(p->code, p->status, NULL);
2153 on = ansi_highlight_red(true);
2154 off = ansi_highlight_red(false);
2158 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
2160 if (p->code == CLD_EXITED) {
2163 printf("status=%i", p->status);
2165 c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD);
2170 printf("signal=%s", signal_to_string(p->status));
2172 printf(")%s\n", off);
2174 if (i->main_pid == p->pid &&
2175 i->start_timestamp == p->start_timestamp &&
2176 i->exit_timestamp == p->start_timestamp)
2177 /* Let's not show this twice */
2180 if (p->pid == i->control_pid)
2184 if (i->main_pid > 0 || i->control_pid > 0) {
2187 if (i->main_pid > 0) {
2188 printf("Main PID: %u", (unsigned) i->main_pid);
2192 get_process_comm(i->main_pid, &t);
2197 } else if (i->exit_code > 0) {
2198 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2200 if (i->exit_code == CLD_EXITED) {
2203 printf("status=%i", i->exit_status);
2205 c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD);
2210 printf("signal=%s", signal_to_string(i->exit_status));
2215 if (i->main_pid > 0 && i->control_pid > 0)
2218 if (i->control_pid > 0) {
2221 printf(" Control: %u", (unsigned) i->control_pid);
2223 get_process_comm(i->control_pid, &t);
2234 printf("\t Status: \"%s\"\n", i->status_text);
2236 if (i->default_control_group) {
2239 printf("\t CGroup: %s\n", i->default_control_group);
2241 if (arg_transport != TRANSPORT_SSH) {
2251 if (i->main_pid > 0)
2252 extra[k++] = i->main_pid;
2254 if (i->control_pid > 0)
2255 extra[k++] = i->control_pid;
2257 show_cgroup_and_extra_by_spec(i->default_control_group, "\t\t ", c, false, arg_all, extra, k);
2261 if (i->id && arg_transport != TRANSPORT_SSH) {
2263 arg_all * OUTPUT_SHOW_ALL |
2264 arg_follow * OUTPUT_FOLLOW |
2265 !arg_quiet * OUTPUT_WARN_CUTOFF |
2266 on_tty() * OUTPUT_COLOR;
2269 show_journal_by_unit(i->id, arg_output, 0,
2270 i->inactive_exit_timestamp_monotonic,
2274 if (i->need_daemon_reload)
2275 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2276 ansi_highlight_red(true),
2277 ansi_highlight_red(false),
2278 arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
2281 static void show_unit_help(UnitStatusInfo *i) {
2286 if (!i->documentation) {
2287 log_info("Documentation for %s not known.", i->id);
2291 STRV_FOREACH(p, i->documentation) {
2293 if (startswith(*p, "man:")) {
2296 char *page = NULL, *section = NULL;
2297 const char *args[4] = { "man", NULL, NULL, NULL };
2302 if ((*p)[k-1] == ')')
2303 e = strrchr(*p, '(');
2306 page = strndup((*p) + 4, e - *p - 4);
2312 section = strndup(e + 1, *p + k - e - 2);
2326 log_error("Failed to fork: %m");
2334 execvp(args[0], (char**) args);
2335 log_error("Failed to execute man: %m");
2336 _exit(EXIT_FAILURE);
2342 wait_for_terminate(pid, NULL);
2344 log_info("Can't show: %s", *p);
2348 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2354 switch (dbus_message_iter_get_arg_type(iter)) {
2356 case DBUS_TYPE_STRING: {
2359 dbus_message_iter_get_basic(iter, &s);
2362 if (streq(name, "Id"))
2364 else if (streq(name, "LoadState"))
2366 else if (streq(name, "ActiveState"))
2367 i->active_state = s;
2368 else if (streq(name, "SubState"))
2370 else if (streq(name, "Description"))
2372 else if (streq(name, "FragmentPath"))
2373 i->fragment_path = s;
2374 else if (streq(name, "SourcePath"))
2376 else if (streq(name, "DefaultControlGroup"))
2377 i->default_control_group = s;
2378 else if (streq(name, "StatusText"))
2380 else if (streq(name, "SysFSPath"))
2382 else if (streq(name, "Where"))
2384 else if (streq(name, "What"))
2386 else if (streq(name, "Following"))
2388 else if (streq(name, "UnitFileState"))
2389 i->unit_file_state = s;
2390 else if (streq(name, "Result"))
2397 case DBUS_TYPE_BOOLEAN: {
2400 dbus_message_iter_get_basic(iter, &b);
2402 if (streq(name, "Accept"))
2404 else if (streq(name, "NeedDaemonReload"))
2405 i->need_daemon_reload = b;
2406 else if (streq(name, "ConditionResult"))
2407 i->condition_result = b;
2412 case DBUS_TYPE_UINT32: {
2415 dbus_message_iter_get_basic(iter, &u);
2417 if (streq(name, "MainPID")) {
2419 i->main_pid = (pid_t) u;
2422 } else if (streq(name, "ControlPID"))
2423 i->control_pid = (pid_t) u;
2424 else if (streq(name, "ExecMainPID")) {
2426 i->main_pid = (pid_t) u;
2427 } else if (streq(name, "NAccepted"))
2429 else if (streq(name, "NConnections"))
2430 i->n_connections = u;
2435 case DBUS_TYPE_INT32: {
2438 dbus_message_iter_get_basic(iter, &j);
2440 if (streq(name, "ExecMainCode"))
2441 i->exit_code = (int) j;
2442 else if (streq(name, "ExecMainStatus"))
2443 i->exit_status = (int) j;
2448 case DBUS_TYPE_UINT64: {
2451 dbus_message_iter_get_basic(iter, &u);
2453 if (streq(name, "ExecMainStartTimestamp"))
2454 i->start_timestamp = (usec_t) u;
2455 else if (streq(name, "ExecMainExitTimestamp"))
2456 i->exit_timestamp = (usec_t) u;
2457 else if (streq(name, "ActiveEnterTimestamp"))
2458 i->active_enter_timestamp = (usec_t) u;
2459 else if (streq(name, "InactiveEnterTimestamp"))
2460 i->inactive_enter_timestamp = (usec_t) u;
2461 else if (streq(name, "InactiveExitTimestamp"))
2462 i->inactive_exit_timestamp = (usec_t) u;
2463 else if (streq(name, "InactiveExitTimestampMonotonic"))
2464 i->inactive_exit_timestamp_monotonic = (usec_t) u;
2465 else if (streq(name, "ActiveExitTimestamp"))
2466 i->active_exit_timestamp = (usec_t) u;
2467 else if (streq(name, "ConditionTimestamp"))
2468 i->condition_timestamp = (usec_t) u;
2473 case DBUS_TYPE_ARRAY: {
2475 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2476 startswith(name, "Exec")) {
2477 DBusMessageIter sub;
2479 dbus_message_iter_recurse(iter, &sub);
2480 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2481 ExecStatusInfo *info;
2484 if (!(info = new0(ExecStatusInfo, 1)))
2487 if (!(info->name = strdup(name))) {
2492 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2497 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2499 dbus_message_iter_next(&sub);
2501 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING &&
2502 streq(name, "Documentation")) {
2504 DBusMessageIter sub;
2506 dbus_message_iter_recurse(iter, &sub);
2507 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING) {
2511 dbus_message_iter_get_basic(&sub, &s);
2513 l = strv_append(i->documentation, s);
2517 strv_free(i->documentation);
2518 i->documentation = l;
2520 dbus_message_iter_next(&sub);
2527 case DBUS_TYPE_STRUCT: {
2529 if (streq(name, "LoadError")) {
2530 DBusMessageIter sub;
2531 const char *n, *message;
2534 dbus_message_iter_recurse(iter, &sub);
2536 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &n, true);
2540 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &message, false);
2544 if (!isempty(message))
2545 i->load_error = message;
2555 static int print_property(const char *name, DBusMessageIter *iter) {
2559 /* This is a low-level property printer, see
2560 * print_status_info() for the nicer output */
2562 if (arg_property && !strv_find(arg_property, name))
2565 switch (dbus_message_iter_get_arg_type(iter)) {
2567 case DBUS_TYPE_STRUCT: {
2568 DBusMessageIter sub;
2569 dbus_message_iter_recurse(iter, &sub);
2571 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2574 dbus_message_iter_get_basic(&sub, &u);
2577 printf("%s=%u\n", name, (unsigned) u);
2579 printf("%s=\n", name);
2582 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2585 dbus_message_iter_get_basic(&sub, &s);
2587 if (arg_all || s[0])
2588 printf("%s=%s\n", name, s);
2591 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "LoadError")) {
2592 const char *a = NULL, *b = NULL;
2594 if (bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &a, true) >= 0)
2595 bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &b, false);
2597 if (arg_all || !isempty(a) || !isempty(b))
2598 printf("%s=%s \"%s\"\n", name, strempty(a), strempty(b));
2606 case DBUS_TYPE_ARRAY:
2608 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
2609 DBusMessageIter sub, sub2;
2611 dbus_message_iter_recurse(iter, &sub);
2612 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2616 dbus_message_iter_recurse(&sub, &sub2);
2618 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
2619 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
2620 printf("EnvironmentFile=%s (ignore_errors=%s)\n", path, yes_no(ignore));
2622 dbus_message_iter_next(&sub);
2627 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2628 DBusMessageIter sub, sub2;
2630 dbus_message_iter_recurse(iter, &sub);
2631 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2632 const char *type, *path;
2634 dbus_message_iter_recurse(&sub, &sub2);
2636 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2637 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2638 printf("%s=%s\n", type, path);
2640 dbus_message_iter_next(&sub);
2645 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2646 DBusMessageIter sub, sub2;
2648 dbus_message_iter_recurse(iter, &sub);
2649 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2651 uint64_t value, next_elapse;
2653 dbus_message_iter_recurse(&sub, &sub2);
2655 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2656 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2657 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2658 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2660 printf("%s={ value=%s ; next_elapse=%s }\n",
2662 format_timespan(timespan1, sizeof(timespan1), value),
2663 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2666 dbus_message_iter_next(&sub);
2671 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "ControlGroupAttributes")) {
2672 DBusMessageIter sub, sub2;
2674 dbus_message_iter_recurse(iter, &sub);
2675 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2676 const char *controller, *attr, *value;
2678 dbus_message_iter_recurse(&sub, &sub2);
2680 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &controller, true) >= 0 &&
2681 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &attr, true) >= 0 &&
2682 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &value, false) >= 0) {
2684 printf("ControlGroupAttribute={ controller=%s ; attribute=%s ; value=\"%s\" }\n",
2690 dbus_message_iter_next(&sub);
2695 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2696 DBusMessageIter sub;
2698 dbus_message_iter_recurse(iter, &sub);
2699 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2700 ExecStatusInfo info;
2703 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2704 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2707 t = strv_join(info.argv, " ");
2709 printf("%s={ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2713 yes_no(info.ignore),
2714 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2715 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2716 (unsigned) info. pid,
2717 sigchld_code_to_string(info.code),
2719 info.code == CLD_EXITED ? "" : "/",
2720 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2726 strv_free(info.argv);
2728 dbus_message_iter_next(&sub);
2737 if (generic_print_property(name, iter, arg_all) > 0)
2741 printf("%s=[unprintable]\n", name);
2746 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2747 DBusMessage *reply = NULL;
2748 const char *interface = "";
2750 DBusMessageIter iter, sub, sub2, sub3;
2751 UnitStatusInfo info;
2759 r = bus_method_call_with_reply (
2761 "org.freedesktop.systemd1",
2763 "org.freedesktop.DBus.Properties",
2767 DBUS_TYPE_STRING, &interface,
2772 if (!dbus_message_iter_init(reply, &iter) ||
2773 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2774 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2775 log_error("Failed to parse reply.");
2780 dbus_message_iter_recurse(&iter, &sub);
2787 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2790 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2791 log_error("Failed to parse reply.");
2796 dbus_message_iter_recurse(&sub, &sub2);
2798 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2799 log_error("Failed to parse reply.");
2804 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2805 log_error("Failed to parse reply.");
2810 dbus_message_iter_recurse(&sub2, &sub3);
2812 if (show_properties)
2813 r = print_property(name, &sub3);
2815 r = status_property(name, &sub3, &info);
2818 log_error("Failed to parse reply.");
2823 dbus_message_iter_next(&sub);
2828 if (!show_properties) {
2829 if (streq(verb, "help"))
2830 show_unit_help(&info);
2832 print_status_info(&info);
2835 strv_free(info.documentation);
2837 if (!streq_ptr(info.active_state, "active") &&
2838 !streq_ptr(info.active_state, "reloading") &&
2839 streq(verb, "status"))
2840 /* According to LSB: "program not running" */
2843 while ((p = info.exec)) {
2844 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2845 exec_status_info_free(p);
2850 dbus_message_unref(reply);
2855 static int show_one_by_pid(const char *verb, DBusConnection *bus, uint32_t pid, bool *new_line) {
2856 DBusMessage *reply = NULL;
2857 const char *path = NULL;
2861 dbus_error_init(&error);
2863 r = bus_method_call_with_reply (
2865 "org.freedesktop.systemd1",
2866 "/org/freedesktop/systemd1",
2867 "org.freedesktop.systemd1.Manager",
2871 DBUS_TYPE_UINT32, &pid,
2876 if (!dbus_message_get_args(reply, &error,
2877 DBUS_TYPE_OBJECT_PATH, &path,
2878 DBUS_TYPE_INVALID)) {
2879 log_error("Failed to parse reply: %s", bus_error_message(&error));
2884 r = show_one(verb, bus, path, false, new_line);
2888 dbus_message_unref(reply);
2890 dbus_error_free(&error);
2895 static int show(DBusConnection *bus, char **args) {
2897 bool show_properties, new_line = false;
2903 show_properties = streq(args[0], "show");
2905 if (show_properties)
2906 pager_open_if_enabled();
2908 if (show_properties && strv_length(args) <= 1) {
2909 /* If not argument is specified inspect the manager
2912 return show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2915 STRV_FOREACH(name, args+1) {
2918 if (safe_atou32(*name, &id) < 0) {
2920 /* Interpret as unit name */
2922 n = unit_name_mangle(*name);
2923 p = unit_dbus_path_from_name(n ? n : *name);
2928 r = show_one(args[0], bus, p, show_properties, &new_line);
2934 } else if (show_properties) {
2936 /* Interpret as job id */
2939 if (asprintf(&p, "/org/freedesktop/systemd1/job/%u", id) < 0)
2942 r = show_one(args[0], bus, p, show_properties, &new_line);
2950 /* Interpret as PID */
2952 r = show_one_by_pid(args[0], bus, id, &new_line);
2961 static int dump(DBusConnection *bus, char **args) {
2962 DBusMessage *reply = NULL;
2967 dbus_error_init(&error);
2969 pager_open_if_enabled();
2971 r = bus_method_call_with_reply (
2973 "org.freedesktop.systemd1",
2974 "/org/freedesktop/systemd1",
2975 "org.freedesktop.systemd1.Manager",
2983 if (!dbus_message_get_args(reply, &error,
2984 DBUS_TYPE_STRING, &text,
2985 DBUS_TYPE_INVALID)) {
2986 log_error("Failed to parse reply: %s", bus_error_message(&error));
2991 fputs(text, stdout);
2995 dbus_message_unref(reply);
2997 dbus_error_free(&error);
3002 static int snapshot(DBusConnection *bus, char **args) {
3003 DBusMessage *reply = NULL;
3006 dbus_bool_t cleanup = FALSE;
3007 DBusMessageIter iter, sub;
3009 *name = "", *path, *id,
3010 *interface = "org.freedesktop.systemd1.Unit",
3014 dbus_error_init(&error);
3016 if (strv_length(args) > 1)
3019 n = unit_name_mangle(name);
3020 r = bus_method_call_with_reply (
3022 "org.freedesktop.systemd1",
3023 "/org/freedesktop/systemd1",
3024 "org.freedesktop.systemd1.Manager",
3028 DBUS_TYPE_STRING, n ? (const char**) &n : &name,
3029 DBUS_TYPE_BOOLEAN, &cleanup,
3035 if (!dbus_message_get_args(reply, &error,
3036 DBUS_TYPE_OBJECT_PATH, &path,
3037 DBUS_TYPE_INVALID)) {
3038 log_error("Failed to parse reply: %s", bus_error_message(&error));
3043 dbus_message_unref(reply);
3044 r = bus_method_call_with_reply (
3046 "org.freedesktop.systemd1",
3048 "org.freedesktop.DBus.Properties",
3052 DBUS_TYPE_STRING, &interface,
3053 DBUS_TYPE_STRING, &property,
3058 if (!dbus_message_iter_init(reply, &iter) ||
3059 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3060 log_error("Failed to parse reply.");
3065 dbus_message_iter_recurse(&iter, &sub);
3067 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3068 log_error("Failed to parse reply.");
3073 dbus_message_iter_get_basic(&sub, &id);
3080 dbus_message_unref(reply);
3082 dbus_error_free(&error);
3087 static int delete_snapshot(DBusConnection *bus, char **args) {
3088 DBusMessage *reply = NULL;
3095 dbus_error_init(&error);
3097 STRV_FOREACH(name, args+1) {
3098 const char *path = NULL;
3101 n = unit_name_mangle(*name);
3102 r = bus_method_call_with_reply (
3104 "org.freedesktop.systemd1",
3105 "/org/freedesktop/systemd1",
3106 "org.freedesktop.systemd1.Manager",
3110 DBUS_TYPE_STRING, n ? &n : name,
3116 if (!dbus_message_get_args(reply, &error,
3117 DBUS_TYPE_OBJECT_PATH, &path,
3118 DBUS_TYPE_INVALID)) {
3119 log_error("Failed to parse reply: %s", bus_error_message(&error));
3121 dbus_message_unref(reply);
3122 dbus_error_free(&error);
3125 dbus_message_unref(reply);
3127 r = bus_method_call_with_reply (
3129 "org.freedesktop.systemd1",
3131 "org.freedesktop.systemd1.Snapshot",
3144 static int daemon_reload(DBusConnection *bus, char **args) {
3149 if (arg_action == ACTION_RELOAD)
3151 else if (arg_action == ACTION_REEXEC)
3152 method = "Reexecute";
3154 assert(arg_action == ACTION_SYSTEMCTL);
3157 streq(args[0], "clear-jobs") ||
3158 streq(args[0], "cancel") ? "ClearJobs" :
3159 streq(args[0], "daemon-reexec") ? "Reexecute" :
3160 streq(args[0], "reset-failed") ? "ResetFailed" :
3161 streq(args[0], "halt") ? "Halt" :
3162 streq(args[0], "poweroff") ? "PowerOff" :
3163 streq(args[0], "reboot") ? "Reboot" :
3164 streq(args[0], "kexec") ? "KExec" :
3165 streq(args[0], "exit") ? "Exit" :
3166 /* "daemon-reload" */ "Reload";
3169 r = bus_method_call_with_reply (
3171 "org.freedesktop.systemd1",
3172 "/org/freedesktop/systemd1",
3173 "org.freedesktop.systemd1.Manager",
3179 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
3180 /* There's always a fallback possible for
3181 * legacy actions. */
3183 else if (r == -ETIMEDOUT && streq(method, "Reexecute"))
3184 /* On reexecution, we expect a disconnect, not
3188 log_error("Failed to issue method call: %s", bus_error_message(&error));
3189 dbus_error_free(&error);
3194 static int reset_failed(DBusConnection *bus, char **args) {
3198 if (strv_length(args) <= 1)
3199 return daemon_reload(bus, args);
3201 STRV_FOREACH(name, args+1) {
3202 n = unit_name_mangle(*name);
3203 r = bus_method_call_with_reply (
3205 "org.freedesktop.systemd1",
3206 "/org/freedesktop/systemd1",
3207 "org.freedesktop.systemd1.Manager",
3211 DBUS_TYPE_STRING, n ? &n : name,
3222 static int show_enviroment(DBusConnection *bus, char **args) {
3223 DBusMessage *reply = NULL;
3224 DBusMessageIter iter, sub, sub2;
3227 *interface = "org.freedesktop.systemd1.Manager",
3228 *property = "Environment";
3230 pager_open_if_enabled();
3232 r = bus_method_call_with_reply (
3234 "org.freedesktop.systemd1",
3235 "/org/freedesktop/systemd1",
3236 "org.freedesktop.DBus.Properties",
3240 DBUS_TYPE_STRING, &interface,
3241 DBUS_TYPE_STRING, &property,
3246 if (!dbus_message_iter_init(reply, &iter) ||
3247 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3248 log_error("Failed to parse reply.");
3253 dbus_message_iter_recurse(&iter, &sub);
3255 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3256 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3257 log_error("Failed to parse reply.");
3262 dbus_message_iter_recurse(&sub, &sub2);
3264 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3267 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3268 log_error("Failed to parse reply.");
3273 dbus_message_iter_get_basic(&sub2, &text);
3274 printf("%s\n", text);
3276 dbus_message_iter_next(&sub2);
3283 dbus_message_unref(reply);
3288 static int switch_root(DBusConnection *bus, char **args) {
3290 const char *root, *init;
3292 l = strv_length(args);
3293 if (l < 2 || l > 3) {
3294 log_error("Wrong number of arguments.");
3299 init = l >= 3 ? args[2] : "";
3301 return bus_method_call_with_reply (
3303 "org.freedesktop.systemd1",
3304 "/org/freedesktop/systemd1",
3305 "org.freedesktop.systemd1.Manager",
3309 DBUS_TYPE_STRING, &root,
3310 DBUS_TYPE_STRING, &init,
3314 static int set_environment(DBusConnection *bus, char **args) {
3315 DBusMessage *m = NULL, *reply = NULL;
3319 DBusMessageIter iter, sub;
3322 dbus_error_init(&error);
3324 method = streq(args[0], "set-environment")
3326 : "UnsetEnvironment";
3328 if (!(m = dbus_message_new_method_call(
3329 "org.freedesktop.systemd1",
3330 "/org/freedesktop/systemd1",
3331 "org.freedesktop.systemd1.Manager",
3334 log_error("Could not allocate message.");
3338 dbus_message_iter_init_append(m, &iter);
3340 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3341 log_error("Could not append arguments to message.");
3346 STRV_FOREACH(name, args+1)
3347 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, name)) {
3348 log_error("Could not append arguments to message.");
3353 if (!dbus_message_iter_close_container(&iter, &sub)) {
3354 log_error("Could not append arguments to message.");
3359 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3360 log_error("Failed to issue method call: %s", bus_error_message(&error));
3369 dbus_message_unref(m);
3372 dbus_message_unref(reply);
3374 dbus_error_free(&error);
3379 static int enable_sysv_units(char **args) {
3382 #if defined (HAVE_SYSV_COMPAT) && (defined(TARGET_FEDORA) || defined(TARGET_MANDRIVA) || defined(TARGET_SUSE) || defined(TARGET_ALTLINUX) || defined(TARGET_MAGEIA))
3383 const char *verb = args[0];
3384 unsigned f = 1, t = 1;
3387 if (arg_scope != UNIT_FILE_SYSTEM)
3390 if (!streq(verb, "enable") &&
3391 !streq(verb, "disable") &&
3392 !streq(verb, "is-enabled"))
3395 /* Processes all SysV units, and reshuffles the array so that
3396 * afterwards only the native units remain */
3399 r = lookup_paths_init(&paths, MANAGER_SYSTEM, false, NULL, NULL, NULL);
3404 for (f = 1; args[f]; f++) {
3407 bool found_native = false, found_sysv;
3409 const char *argv[6] = { "/sbin/chkconfig", NULL, NULL, NULL, NULL };
3410 char **k, *l, *q = NULL;
3417 if (!endswith(name, ".service"))
3420 if (path_is_absolute(name))
3423 STRV_FOREACH(k, paths.unit_path) {
3426 if (!isempty(arg_root))
3427 asprintf(&p, "%s/%s/%s", arg_root, *k, name);
3429 asprintf(&p, "%s/%s", *k, name);
3436 found_native = access(p, F_OK) >= 0;
3447 if (!isempty(arg_root))
3448 asprintf(&p, "%s/" SYSTEM_SYSVINIT_PATH "/%s", arg_root, name);
3450 asprintf(&p, SYSTEM_SYSVINIT_PATH "/%s", name);
3456 p[strlen(p) - sizeof(".service") + 1] = 0;
3457 found_sysv = access(p, F_OK) >= 0;
3464 /* Mark this entry, so that we don't try enabling it as native unit */
3465 args[f] = (char*) "";
3467 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", name);
3469 if (!isempty(arg_root))
3470 argv[c++] = q = strappend("--root=", arg_root);
3472 argv[c++] = path_get_file_name(p);
3474 streq(verb, "enable") ? "on" :
3475 streq(verb, "disable") ? "off" : "--level=5";
3478 l = strv_join((char**)argv, " ");
3486 log_info("Executing %s", l);
3491 log_error("Failed to fork: %m");
3496 } else if (pid == 0) {
3499 execv(argv[0], (char**) argv);
3500 _exit(EXIT_FAILURE);
3506 j = wait_for_terminate(pid, &status);
3508 log_error("Failed to wait for child: %s", strerror(-r));
3513 if (status.si_code == CLD_EXITED) {
3514 if (streq(verb, "is-enabled")) {
3515 if (status.si_status == 0) {
3524 } else if (status.si_status != 0) {
3535 lookup_paths_free(&paths);
3537 /* Drop all SysV units */
3538 for (f = 1, t = 1; args[f]; f++) {
3540 if (isempty(args[f]))
3543 args[t++] = args[f];
3552 static int enable_unit(DBusConnection *bus, char **args) {
3553 const char *verb = args[0];
3554 UnitFileChange *changes = NULL;
3555 unsigned n_changes = 0, i;
3556 int carries_install_info = -1;
3557 DBusMessage *m = NULL, *reply = NULL;
3561 r = enable_sysv_units(args);
3568 dbus_error_init(&error);
3570 if (!bus || avoid_bus()) {
3571 if (streq(verb, "enable")) {
3572 r = unit_file_enable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3573 carries_install_info = r;
3574 } else if (streq(verb, "disable"))
3575 r = unit_file_disable(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
3576 else if (streq(verb, "reenable")) {
3577 r = unit_file_reenable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3578 carries_install_info = r;
3579 } else if (streq(verb, "link"))
3580 r = unit_file_link(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3581 else if (streq(verb, "preset")) {
3582 r = unit_file_preset(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3583 carries_install_info = r;
3584 } else if (streq(verb, "mask"))
3585 r = unit_file_mask(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3586 else if (streq(verb, "unmask"))
3587 r = unit_file_unmask(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
3589 assert_not_reached("Unknown verb");
3592 log_error("Operation failed: %s", strerror(-r));
3597 for (i = 0; i < n_changes; i++) {
3598 if (changes[i].type == UNIT_FILE_SYMLINK)
3599 log_info("ln -s '%s' '%s'", changes[i].source, changes[i].path);
3601 log_info("rm '%s'", changes[i].path);
3607 bool send_force = true, expect_carries_install_info = false;
3609 DBusMessageIter iter, sub, sub2;
3611 if (streq(verb, "enable")) {
3612 method = "EnableUnitFiles";
3613 expect_carries_install_info = true;
3614 } else if (streq(verb, "disable")) {
3615 method = "DisableUnitFiles";
3617 } else if (streq(verb, "reenable")) {
3618 method = "ReenableUnitFiles";
3619 expect_carries_install_info = true;
3620 } else if (streq(verb, "link"))
3621 method = "LinkUnitFiles";
3622 else if (streq(verb, "preset")) {
3623 method = "PresetUnitFiles";
3624 expect_carries_install_info = true;
3625 } else if (streq(verb, "mask"))
3626 method = "MaskUnitFiles";
3627 else if (streq(verb, "unmask")) {
3628 method = "UnmaskUnitFiles";
3631 assert_not_reached("Unknown verb");
3633 m = dbus_message_new_method_call(
3634 "org.freedesktop.systemd1",
3635 "/org/freedesktop/systemd1",
3636 "org.freedesktop.systemd1.Manager",
3643 dbus_message_iter_init_append(m, &iter);
3645 r = bus_append_strv_iter(&iter, args+1);
3647 log_error("Failed to append unit files.");
3652 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &a)) {
3653 log_error("Failed to append runtime boolean.");
3661 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b)) {
3662 log_error("Failed to append force boolean.");
3668 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3670 log_error("Failed to issue method call: %s", bus_error_message(&error));
3675 if (!dbus_message_iter_init(reply, &iter)) {
3676 log_error("Failed to initialize iterator.");
3680 if (expect_carries_install_info) {
3681 r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_BOOLEAN, &b, true);
3683 log_error("Failed to parse reply.");
3687 carries_install_info = b;
3690 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
3691 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
3692 log_error("Failed to parse reply.");
3697 dbus_message_iter_recurse(&iter, &sub);
3698 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
3699 const char *type, *path, *source;
3701 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
3702 log_error("Failed to parse reply.");
3707 dbus_message_iter_recurse(&sub, &sub2);
3709 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
3710 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0 ||
3711 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &source, false) < 0) {
3712 log_error("Failed to parse reply.");
3718 if (streq(type, "symlink"))
3719 log_info("ln -s '%s' '%s'", source, path);
3721 log_info("rm '%s'", path);
3724 dbus_message_iter_next(&sub);
3727 /* Try to reload if enabeld */
3729 r = daemon_reload(bus, args);
3732 if (carries_install_info == 0)
3733 log_warning("The unit files have no [Install] section. They are not meant to be enabled using systemctl.");
3737 dbus_message_unref(m);
3740 dbus_message_unref(reply);
3742 unit_file_changes_free(changes, n_changes);
3744 dbus_error_free(&error);
3748 static int unit_is_enabled(DBusConnection *bus, char **args) {
3751 DBusMessage *reply = NULL;
3755 dbus_error_init(&error);
3757 r = enable_sysv_units(args);
3763 if (!bus || avoid_bus()) {
3765 STRV_FOREACH(name, args+1) {
3766 UnitFileState state;
3768 state = unit_file_get_state(arg_scope, arg_root, *name);
3774 if (state == UNIT_FILE_ENABLED ||
3775 state == UNIT_FILE_ENABLED_RUNTIME ||
3776 state == UNIT_FILE_STATIC)
3780 puts(unit_file_state_to_string(state));
3784 STRV_FOREACH(name, args+1) {
3787 r = bus_method_call_with_reply (
3789 "org.freedesktop.systemd1",
3790 "/org/freedesktop/systemd1",
3791 "org.freedesktop.systemd1.Manager",
3795 DBUS_TYPE_STRING, name,
3800 if (!dbus_message_get_args(reply, &error,
3801 DBUS_TYPE_STRING, &s,
3802 DBUS_TYPE_INVALID)) {
3803 log_error("Failed to parse reply: %s", bus_error_message(&error));
3808 dbus_message_unref(reply);
3811 if (streq(s, "enabled") ||
3812 streq(s, "enabled-runtime") ||
3821 r = enabled ? 0 : 1;
3825 dbus_message_unref(reply);
3827 dbus_error_free(&error);
3831 static int systemctl_help(void) {
3833 pager_open_if_enabled();
3835 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3836 "Query or send control commands to the systemd manager.\n\n"
3837 " -h --help Show this help\n"
3838 " --version Show package version\n"
3839 " -t --type=TYPE List only units of a particular type\n"
3840 " -p --property=NAME Show only properties by this name\n"
3841 " -a --all Show all units/properties, including dead/empty ones\n"
3842 " --failed Show only failed units\n"
3843 " --full Don't ellipsize unit names on output\n"
3844 " --fail When queueing a new job, fail if conflicting jobs are\n"
3846 " --ignore-dependencies\n"
3847 " When queueing a new job, ignore all its dependencies\n"
3848 " --kill-who=WHO Who to send signal to\n"
3849 " -s --signal=SIGNAL Which signal to send\n"
3850 " -H --host=[USER@]HOST\n"
3851 " Show information for remote host\n"
3852 " -P --privileged Acquire privileges before execution\n"
3853 " -q --quiet Suppress output\n"
3854 " --no-block Do not wait until operation finished\n"
3855 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3856 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3858 " --no-legend Do not print a legend (column headers and hints)\n"
3859 " --no-pager Do not pipe output into a pager\n"
3860 " --no-ask-password\n"
3861 " Do not ask for system passwords\n"
3862 " --order When generating graph for dot, show only order\n"
3863 " --require When generating graph for dot, show only requirement\n"
3864 " --system Connect to system manager\n"
3865 " --user Connect to user service manager\n"
3866 " --global Enable/disable unit files globally\n"
3867 " -f --force When enabling unit files, override existing symlinks\n"
3868 " When shutting down, execute action immediately\n"
3869 " --root=PATH Enable unit files in the specified root directory\n"
3870 " --runtime Enable unit files only temporarily until next reboot\n"
3871 " -n --lines=INTEGER Journal entries to show\n"
3872 " --follow Follow journal\n"
3873 " -o --output=STRING Change journal output mode (short, short-monotonic,\n"
3874 " verbose, export, json, json-pretty, cat)\n\n"
3876 " list-units List loaded units\n"
3877 " start [NAME...] Start (activate) one or more units\n"
3878 " stop [NAME...] Stop (deactivate) one or more units\n"
3879 " reload [NAME...] Reload one or more units\n"
3880 " restart [NAME...] Start or restart one or more units\n"
3881 " try-restart [NAME...] Restart one or more units if active\n"
3882 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3883 " otherwise start or restart\n"
3884 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3885 " otherwise restart if active\n"
3886 " isolate [NAME] Start one unit and stop all others\n"
3887 " kill [NAME...] Send signal to processes of a unit\n"
3888 " is-active [NAME...] Check whether units are active\n"
3889 " status [NAME...|PID...] Show runtime status of one or more units\n"
3890 " show [NAME...|JOB...] Show properties of one or more\n"
3891 " units/jobs or the manager\n"
3892 " help [NAME...|PID...] Show manual for one or more units\n"
3893 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
3895 " load [NAME...] Load one or more units\n\n"
3896 "Unit File Commands:\n"
3897 " list-unit-files List installed unit files\n"
3898 " enable [NAME...] Enable one or more unit files\n"
3899 " disable [NAME...] Disable one or more unit files\n"
3900 " reenable [NAME...] Reenable one or more unit files\n"
3901 " preset [NAME...] Enable/disable one or more unit files\n"
3902 " based on preset configuration\n"
3903 " mask [NAME...] Mask one or more units\n"
3904 " unmask [NAME...] Unmask one or more units\n"
3905 " link [PATH...] Link one or more units files into\n"
3906 " the search path\n"
3907 " is-enabled [NAME...] Check whether unit files are enabled\n\n"
3909 " list-jobs List jobs\n"
3910 " cancel [JOB...] Cancel all, one, or more jobs\n\n"
3911 "Status Commands:\n"
3912 " dump Dump server status\n"
3913 " dot Dump dependency graph for dot(1)\n\n"
3914 "Snapshot Commands:\n"
3915 " snapshot [NAME] Create a snapshot\n"
3916 " delete [NAME...] Remove one or more snapshots\n\n"
3917 "Environment Commands:\n"
3918 " show-environment Dump environment\n"
3919 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3920 " unset-environment [NAME...] Unset one or more environment variables\n\n"
3921 "Manager Lifecycle Commands:\n"
3922 " daemon-reload Reload systemd manager configuration\n"
3923 " daemon-reexec Reexecute systemd manager\n\n"
3924 "System Commands:\n"
3925 " default Enter system default mode\n"
3926 " rescue Enter system rescue mode\n"
3927 " emergency Enter system emergency mode\n"
3928 " halt Shut down and halt the system\n"
3929 " poweroff Shut down and power-off the system\n"
3930 " reboot Shut down and reboot the system\n"
3931 " kexec Shut down and reboot the system with kexec\n"
3932 " exit Request user instance exit\n"
3933 " switch-root [ROOT] [INIT] Change to a different root file system\n"
3934 " suspend Suspend the system\n"
3935 " hibernate Hibernate the system\n",
3936 program_invocation_short_name);
3941 static int halt_help(void) {
3943 printf("%s [OPTIONS...]\n\n"
3944 "%s the system.\n\n"
3945 " --help Show this help\n"
3946 " --halt Halt the machine\n"
3947 " -p --poweroff Switch off the machine\n"
3948 " --reboot Reboot the machine\n"
3949 " -f --force Force immediate halt/power-off/reboot\n"
3950 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3951 " -d --no-wtmp Don't write wtmp record\n"
3952 " --no-wall Don't send wall message before halt/power-off/reboot\n",
3953 program_invocation_short_name,
3954 arg_action == ACTION_REBOOT ? "Reboot" :
3955 arg_action == ACTION_POWEROFF ? "Power off" :
3961 static int shutdown_help(void) {
3963 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3964 "Shut down the system.\n\n"
3965 " --help Show this help\n"
3966 " -H --halt Halt the machine\n"
3967 " -P --poweroff Power-off the machine\n"
3968 " -r --reboot Reboot the machine\n"
3969 " -h Equivalent to --poweroff, overridden by --halt\n"
3970 " -k Don't halt/power-off/reboot, just send warnings\n"
3971 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3972 " -c Cancel a pending shutdown\n",
3973 program_invocation_short_name);
3978 static int telinit_help(void) {
3980 printf("%s [OPTIONS...] {COMMAND}\n\n"
3981 "Send control commands to the init daemon.\n\n"
3982 " --help Show this help\n"
3983 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
3985 " 0 Power-off the machine\n"
3986 " 6 Reboot the machine\n"
3987 " 2, 3, 4, 5 Start runlevelX.target unit\n"
3988 " 1, s, S Enter rescue mode\n"
3989 " q, Q Reload init daemon configuration\n"
3990 " u, U Reexecute init daemon\n",
3991 program_invocation_short_name);
3996 static int runlevel_help(void) {
3998 printf("%s [OPTIONS...]\n\n"
3999 "Prints the previous and current runlevel of the init system.\n\n"
4000 " --help Show this help\n",
4001 program_invocation_short_name);
4006 static int systemctl_parse_argv(int argc, char *argv[]) {
4010 ARG_IGNORE_DEPENDENCIES,
4025 ARG_NO_ASK_PASSWORD,
4032 static const struct option options[] = {
4033 { "help", no_argument, NULL, 'h' },
4034 { "version", no_argument, NULL, ARG_VERSION },
4035 { "type", required_argument, NULL, 't' },
4036 { "property", required_argument, NULL, 'p' },
4037 { "all", no_argument, NULL, 'a' },
4038 { "failed", no_argument, NULL, ARG_FAILED },
4039 { "full", no_argument, NULL, ARG_FULL },
4040 { "fail", no_argument, NULL, ARG_FAIL },
4041 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4042 { "user", no_argument, NULL, ARG_USER },
4043 { "system", no_argument, NULL, ARG_SYSTEM },
4044 { "global", no_argument, NULL, ARG_GLOBAL },
4045 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4046 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
4047 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4048 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4049 { "quiet", no_argument, NULL, 'q' },
4050 { "order", no_argument, NULL, ARG_ORDER },
4051 { "require", no_argument, NULL, ARG_REQUIRE },
4052 { "root", required_argument, NULL, ARG_ROOT },
4053 { "force", no_argument, NULL, ARG_FORCE },
4054 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4055 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4056 { "signal", required_argument, NULL, 's' },
4057 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4058 { "host", required_argument, NULL, 'H' },
4059 { "privileged",no_argument, NULL, 'P' },
4060 { "runtime", no_argument, NULL, ARG_RUNTIME },
4061 { "lines", required_argument, NULL, 'n' },
4062 { "follow", no_argument, NULL, ARG_FOLLOW },
4063 { "output", required_argument, NULL, 'o' },
4064 { NULL, 0, NULL, 0 }
4072 while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:Pn:o:", options, NULL)) >= 0) {
4081 puts(PACKAGE_STRING);
4083 puts(SYSTEMD_FEATURES);
4087 if (unit_type_from_string(optarg) >= 0) {
4091 if (unit_load_state_from_string(optarg) >= 0) {
4092 arg_load_state = optarg;
4095 log_error("Unkown unit type or load state '%s'.",
4101 if (!(l = strv_append(arg_property, optarg)))
4104 strv_free(arg_property);
4107 /* If the user asked for a particular
4108 * property, show it to him, even if it is
4119 arg_job_mode = "fail";
4122 case ARG_IGNORE_DEPENDENCIES:
4123 arg_job_mode = "ignore-dependencies";
4127 arg_scope = UNIT_FILE_USER;
4131 arg_scope = UNIT_FILE_SYSTEM;
4135 arg_scope = UNIT_FILE_GLOBAL;
4139 arg_no_block = true;
4143 arg_no_legend = true;
4147 arg_no_pager = true;
4155 arg_dot = DOT_ORDER;
4159 arg_dot = DOT_REQUIRE;
4187 /* -f is short for both --follow and --force! */
4193 arg_no_reload = true;
4197 arg_kill_who = optarg;
4201 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4202 log_error("Failed to parse signal string %s.", optarg);
4207 case ARG_NO_ASK_PASSWORD:
4208 arg_ask_password = false;
4212 arg_transport = TRANSPORT_POLKIT;
4216 arg_transport = TRANSPORT_SSH;
4225 if (safe_atou(optarg, &arg_lines) < 0) {
4226 log_error("Failed to parse lines '%s'", optarg);
4232 arg_output = output_mode_from_string(optarg);
4233 if (arg_output < 0) {
4234 log_error("Unknown output '%s'.", optarg);
4243 log_error("Unknown option code '%c'.", c);
4248 if (arg_transport != TRANSPORT_NORMAL && arg_scope != UNIT_FILE_SYSTEM) {
4249 log_error("Cannot access user instance remotely.");
4256 static int halt_parse_argv(int argc, char *argv[]) {
4265 static const struct option options[] = {
4266 { "help", no_argument, NULL, ARG_HELP },
4267 { "halt", no_argument, NULL, ARG_HALT },
4268 { "poweroff", no_argument, NULL, 'p' },
4269 { "reboot", no_argument, NULL, ARG_REBOOT },
4270 { "force", no_argument, NULL, 'f' },
4271 { "wtmp-only", no_argument, NULL, 'w' },
4272 { "no-wtmp", no_argument, NULL, 'd' },
4273 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4274 { NULL, 0, NULL, 0 }
4282 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4283 if (runlevel == '0' || runlevel == '6')
4286 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4294 arg_action = ACTION_HALT;
4298 if (arg_action != ACTION_REBOOT)
4299 arg_action = ACTION_POWEROFF;
4303 arg_action = ACTION_REBOOT;
4325 /* Compatibility nops */
4332 log_error("Unknown option code '%c'.", c);
4337 if (optind < argc) {
4338 log_error("Too many arguments.");
4345 static int parse_time_spec(const char *t, usec_t *_u) {
4349 if (streq(t, "now"))
4351 else if (!strchr(t, ':')) {
4354 if (safe_atou64(t, &u) < 0)
4357 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4366 hour = strtol(t, &e, 10);
4367 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4370 minute = strtol(e+1, &e, 10);
4371 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4374 n = now(CLOCK_REALTIME);
4375 s = (time_t) (n / USEC_PER_SEC);
4378 assert_se(localtime_r(&s, &tm));
4380 tm.tm_hour = (int) hour;
4381 tm.tm_min = (int) minute;
4384 assert_se(s = mktime(&tm));
4386 *_u = (usec_t) s * USEC_PER_SEC;
4389 *_u += USEC_PER_DAY;
4395 static int shutdown_parse_argv(int argc, char *argv[]) {
4402 static const struct option options[] = {
4403 { "help", no_argument, NULL, ARG_HELP },
4404 { "halt", no_argument, NULL, 'H' },
4405 { "poweroff", no_argument, NULL, 'P' },
4406 { "reboot", no_argument, NULL, 'r' },
4407 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
4408 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4409 { NULL, 0, NULL, 0 }
4417 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4425 arg_action = ACTION_HALT;
4429 arg_action = ACTION_POWEROFF;
4434 arg_action = ACTION_KEXEC;
4436 arg_action = ACTION_REBOOT;
4440 arg_action = ACTION_KEXEC;
4444 if (arg_action != ACTION_HALT)
4445 arg_action = ACTION_POWEROFF;
4458 /* Compatibility nops */
4462 arg_action = ACTION_CANCEL_SHUTDOWN;
4469 log_error("Unknown option code '%c'.", c);
4474 if (argc > optind && arg_action != ACTION_CANCEL_SHUTDOWN) {
4475 r = parse_time_spec(argv[optind], &arg_when);
4477 log_error("Failed to parse time specification: %s", argv[optind]);
4481 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4483 if (argc > optind && arg_action == ACTION_CANCEL_SHUTDOWN)
4484 /* No time argument for shutdown cancel */
4485 arg_wall = argv + optind;
4486 else if (argc > optind + 1)
4487 /* We skip the time argument */
4488 arg_wall = argv + optind + 1;
4495 static int telinit_parse_argv(int argc, char *argv[]) {
4502 static const struct option options[] = {
4503 { "help", no_argument, NULL, ARG_HELP },
4504 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4505 { NULL, 0, NULL, 0 }
4508 static const struct {
4512 { '0', ACTION_POWEROFF },
4513 { '6', ACTION_REBOOT },
4514 { '1', ACTION_RESCUE },
4515 { '2', ACTION_RUNLEVEL2 },
4516 { '3', ACTION_RUNLEVEL3 },
4517 { '4', ACTION_RUNLEVEL4 },
4518 { '5', ACTION_RUNLEVEL5 },
4519 { 's', ACTION_RESCUE },
4520 { 'S', ACTION_RESCUE },
4521 { 'q', ACTION_RELOAD },
4522 { 'Q', ACTION_RELOAD },
4523 { 'u', ACTION_REEXEC },
4524 { 'U', ACTION_REEXEC }
4533 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4548 log_error("Unknown option code '%c'.", c);
4553 if (optind >= argc) {
4558 if (optind + 1 < argc) {
4559 log_error("Too many arguments.");
4563 if (strlen(argv[optind]) != 1) {
4564 log_error("Expected single character argument.");
4568 for (i = 0; i < ELEMENTSOF(table); i++)
4569 if (table[i].from == argv[optind][0])
4572 if (i >= ELEMENTSOF(table)) {
4573 log_error("Unknown command '%s'.", argv[optind]);
4577 arg_action = table[i].to;
4584 static int runlevel_parse_argv(int argc, char *argv[]) {
4590 static const struct option options[] = {
4591 { "help", no_argument, NULL, ARG_HELP },
4592 { NULL, 0, NULL, 0 }
4600 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4611 log_error("Unknown option code '%c'.", c);
4616 if (optind < argc) {
4617 log_error("Too many arguments.");
4624 static int parse_argv(int argc, char *argv[]) {
4628 if (program_invocation_short_name) {
4630 if (strstr(program_invocation_short_name, "halt")) {
4631 arg_action = ACTION_HALT;
4632 return halt_parse_argv(argc, argv);
4633 } else if (strstr(program_invocation_short_name, "poweroff")) {
4634 arg_action = ACTION_POWEROFF;
4635 return halt_parse_argv(argc, argv);
4636 } else if (strstr(program_invocation_short_name, "reboot")) {
4638 arg_action = ACTION_KEXEC;
4640 arg_action = ACTION_REBOOT;
4641 return halt_parse_argv(argc, argv);
4642 } else if (strstr(program_invocation_short_name, "shutdown")) {
4643 arg_action = ACTION_POWEROFF;
4644 return shutdown_parse_argv(argc, argv);
4645 } else if (strstr(program_invocation_short_name, "init")) {
4647 if (sd_booted() > 0) {
4648 arg_action = ACTION_INVALID;
4649 return telinit_parse_argv(argc, argv);
4651 /* Hmm, so some other init system is
4652 * running, we need to forward this
4653 * request to it. For now we simply
4654 * guess that it is Upstart. */
4656 execv("/lib/upstart/telinit", argv);
4658 log_error("Couldn't find an alternative telinit implementation to spawn.");
4662 } else if (strstr(program_invocation_short_name, "runlevel")) {
4663 arg_action = ACTION_RUNLEVEL;
4664 return runlevel_parse_argv(argc, argv);
4668 arg_action = ACTION_SYSTEMCTL;
4669 return systemctl_parse_argv(argc, argv);
4672 static int action_to_runlevel(void) {
4674 static const char table[_ACTION_MAX] = {
4675 [ACTION_HALT] = '0',
4676 [ACTION_POWEROFF] = '0',
4677 [ACTION_REBOOT] = '6',
4678 [ACTION_RUNLEVEL2] = '2',
4679 [ACTION_RUNLEVEL3] = '3',
4680 [ACTION_RUNLEVEL4] = '4',
4681 [ACTION_RUNLEVEL5] = '5',
4682 [ACTION_RESCUE] = '1'
4685 assert(arg_action < _ACTION_MAX);
4687 return table[arg_action];
4690 static int talk_upstart(void) {
4691 DBusMessage *m = NULL, *reply = NULL;
4693 int previous, rl, r;
4695 env1_buf[] = "RUNLEVEL=X",
4696 env2_buf[] = "PREVLEVEL=X";
4697 char *env1 = env1_buf, *env2 = env2_buf;
4698 const char *emit = "runlevel";
4699 dbus_bool_t b_false = FALSE;
4700 DBusMessageIter iter, sub;
4701 DBusConnection *bus;
4703 dbus_error_init(&error);
4705 if (!(rl = action_to_runlevel()))
4708 if (utmp_get_runlevel(&previous, NULL) < 0)
4711 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4712 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4717 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4722 if ((r = bus_check_peercred(bus)) < 0) {
4723 log_error("Failed to verify owner of bus.");
4727 if (!(m = dbus_message_new_method_call(
4728 "com.ubuntu.Upstart",
4729 "/com/ubuntu/Upstart",
4730 "com.ubuntu.Upstart0_6",
4733 log_error("Could not allocate message.");
4738 dbus_message_iter_init_append(m, &iter);
4740 env1_buf[sizeof(env1_buf)-2] = rl;
4741 env2_buf[sizeof(env2_buf)-2] = previous;
4743 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4744 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4745 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4746 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4747 !dbus_message_iter_close_container(&iter, &sub) ||
4748 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4749 log_error("Could not append arguments to message.");
4754 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4756 if (bus_error_is_no_service(&error)) {
4761 log_error("Failed to issue method call: %s", bus_error_message(&error));
4770 dbus_message_unref(m);
4773 dbus_message_unref(reply);
4776 dbus_connection_flush(bus);
4777 dbus_connection_close(bus);
4778 dbus_connection_unref(bus);
4781 dbus_error_free(&error);
4786 static int talk_initctl(void) {
4787 struct init_request request;
4791 if (!(rl = action_to_runlevel()))
4795 request.magic = INIT_MAGIC;
4796 request.sleeptime = 0;
4797 request.cmd = INIT_CMD_RUNLVL;
4798 request.runlevel = rl;
4800 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4802 if (errno == ENOENT)
4805 log_error("Failed to open "INIT_FIFO": %m");
4810 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4811 close_nointr_nofail(fd);
4814 log_error("Failed to write to "INIT_FIFO": %m");
4815 return errno ? -errno : -EIO;
4821 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4823 static const struct {
4831 int (* const dispatch)(DBusConnection *bus, char **args);
4833 { "list-units", LESS, 1, list_units },
4834 { "list-unit-files", EQUAL, 1, list_unit_files },
4835 { "list-jobs", EQUAL, 1, list_jobs },
4836 { "clear-jobs", EQUAL, 1, daemon_reload },
4837 { "load", MORE, 2, load_unit },
4838 { "cancel", MORE, 2, cancel_job },
4839 { "start", MORE, 2, start_unit },
4840 { "stop", MORE, 2, start_unit },
4841 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
4842 { "reload", MORE, 2, start_unit },
4843 { "restart", MORE, 2, start_unit },
4844 { "try-restart", MORE, 2, start_unit },
4845 { "reload-or-restart", MORE, 2, start_unit },
4846 { "reload-or-try-restart", MORE, 2, start_unit },
4847 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4848 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
4849 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4850 { "isolate", EQUAL, 2, start_unit },
4851 { "kill", MORE, 2, kill_unit },
4852 { "is-active", MORE, 2, check_unit },
4853 { "check", MORE, 2, check_unit },
4854 { "show", MORE, 1, show },
4855 { "status", MORE, 2, show },
4856 { "help", MORE, 2, show },
4857 { "dump", EQUAL, 1, dump },
4858 { "dot", EQUAL, 1, dot },
4859 { "snapshot", LESS, 2, snapshot },
4860 { "delete", MORE, 2, delete_snapshot },
4861 { "daemon-reload", EQUAL, 1, daemon_reload },
4862 { "daemon-reexec", EQUAL, 1, daemon_reload },
4863 { "show-environment", EQUAL, 1, show_enviroment },
4864 { "set-environment", MORE, 2, set_environment },
4865 { "unset-environment", MORE, 2, set_environment },
4866 { "halt", EQUAL, 1, start_special },
4867 { "poweroff", EQUAL, 1, start_special },
4868 { "reboot", EQUAL, 1, start_special },
4869 { "kexec", EQUAL, 1, start_special },
4870 { "suspend", EQUAL, 1, start_special },
4871 { "hibernate", EQUAL, 1, start_special },
4872 { "default", EQUAL, 1, start_special },
4873 { "rescue", EQUAL, 1, start_special },
4874 { "emergency", EQUAL, 1, start_special },
4875 { "exit", EQUAL, 1, start_special },
4876 { "reset-failed", MORE, 1, reset_failed },
4877 { "enable", MORE, 2, enable_unit },
4878 { "disable", MORE, 2, enable_unit },
4879 { "is-enabled", MORE, 2, unit_is_enabled },
4880 { "reenable", MORE, 2, enable_unit },
4881 { "preset", MORE, 2, enable_unit },
4882 { "mask", MORE, 2, enable_unit },
4883 { "unmask", MORE, 2, enable_unit },
4884 { "link", MORE, 2, enable_unit },
4885 { "switch-root", MORE, 2, switch_root },
4895 left = argc - optind;
4898 /* Special rule: no arguments means "list-units" */
4901 if (streq(argv[optind], "help") && !argv[optind+1]) {
4902 log_error("This command expects one or more "
4903 "unit names. Did you mean --help?");
4907 for (i = 0; i < ELEMENTSOF(verbs); i++)
4908 if (streq(argv[optind], verbs[i].verb))
4911 if (i >= ELEMENTSOF(verbs)) {
4912 log_error("Unknown operation '%s'.", argv[optind]);
4917 switch (verbs[i].argc_cmp) {
4920 if (left != verbs[i].argc) {
4921 log_error("Invalid number of arguments.");
4928 if (left < verbs[i].argc) {
4929 log_error("Too few arguments.");
4936 if (left > verbs[i].argc) {
4937 log_error("Too many arguments.");
4944 assert_not_reached("Unknown comparison operator.");
4947 /* Require a bus connection for all operations but
4949 if (!streq(verbs[i].verb, "enable") &&
4950 !streq(verbs[i].verb, "disable") &&
4951 !streq(verbs[i].verb, "is-enabled") &&
4952 !streq(verbs[i].verb, "list-unit-files") &&
4953 !streq(verbs[i].verb, "reenable") &&
4954 !streq(verbs[i].verb, "preset") &&
4955 !streq(verbs[i].verb, "mask") &&
4956 !streq(verbs[i].verb, "unmask") &&
4957 !streq(verbs[i].verb, "link")) {
4959 if (running_in_chroot() > 0) {
4960 log_info("Running in chroot, ignoring request.");
4964 if (((!streq(verbs[i].verb, "reboot") &&
4965 !streq(verbs[i].verb, "halt") &&
4966 !streq(verbs[i].verb, "poweroff")) || arg_force <= 0) && !bus) {
4967 log_error("Failed to get D-Bus connection: %s",
4968 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
4974 if (!bus && !avoid_bus()) {
4975 log_error("Failed to get D-Bus connection: %s",
4976 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
4981 return verbs[i].dispatch(bus, argv + optind);
4984 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
4986 struct msghdr msghdr;
4987 struct iovec iovec[2];
4988 union sockaddr_union sockaddr;
4989 struct sd_shutdown_command c;
4991 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
4998 c.dry_run = dry_run;
5002 sockaddr.sa.sa_family = AF_UNIX;
5003 strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5006 msghdr.msg_name = &sockaddr;
5007 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5010 iovec[0].iov_base = (char*) &c;
5011 iovec[0].iov_len = offsetof(struct sd_shutdown_command, wall_message);
5013 if (isempty(message))
5014 msghdr.msg_iovlen = 1;
5016 iovec[1].iov_base = (char*) message;
5017 iovec[1].iov_len = strlen(message);
5018 msghdr.msg_iovlen = 2;
5020 msghdr.msg_iov = iovec;
5022 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5023 close_nointr_nofail(fd);
5027 close_nointr_nofail(fd);
5031 static int reload_with_fallback(DBusConnection *bus) {
5034 /* First, try systemd via D-Bus. */
5035 if (daemon_reload(bus, NULL) >= 0)
5039 /* Nothing else worked, so let's try signals */
5040 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5042 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5043 log_error("kill() failed: %m");
5050 static int start_with_fallback(DBusConnection *bus) {
5053 /* First, try systemd via D-Bus. */
5054 if (start_unit(bus, NULL) >= 0)
5058 /* Hmm, talking to systemd via D-Bus didn't work. Then
5059 * let's try to talk to Upstart via D-Bus. */
5060 if (talk_upstart() > 0)
5063 /* Nothing else worked, so let's try
5065 if (talk_initctl() > 0)
5068 log_error("Failed to talk to init daemon.");
5072 warn_wall(arg_action);
5076 static _noreturn_ void halt_now(enum action a) {
5078 /* Make sure C-A-D is handled by the kernel from this
5080 reboot(RB_ENABLE_CAD);
5085 log_info("Halting.");
5086 reboot(RB_HALT_SYSTEM);
5089 case ACTION_POWEROFF:
5090 log_info("Powering off.");
5091 reboot(RB_POWER_OFF);
5095 log_info("Rebooting.");
5096 reboot(RB_AUTOBOOT);
5100 assert_not_reached("Unknown halt action.");
5103 assert_not_reached("Uh? This shouldn't happen.");
5106 static int halt_main(DBusConnection *bus) {
5109 if (geteuid() != 0) {
5110 /* Try logind if we are a normal user and no special
5111 * mode applies. Maybe PolicyKit allows us to shutdown
5114 if (arg_when <= 0 &&
5117 (arg_action == ACTION_POWEROFF ||
5118 arg_action == ACTION_REBOOT)) {
5119 r = reboot_with_logind(bus, arg_action);
5124 log_error("Must be root.");
5131 m = strv_join(arg_wall, " ");
5132 r = send_shutdownd(arg_when,
5133 arg_action == ACTION_HALT ? 'H' :
5134 arg_action == ACTION_POWEROFF ? 'P' :
5135 arg_action == ACTION_KEXEC ? 'K' :
5143 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5145 char date[FORMAT_TIMESTAMP_MAX];
5147 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5148 format_timestamp(date, sizeof(date), arg_when));
5153 if (!arg_dry && !arg_force)
5154 return start_with_fallback(bus);
5157 if (sd_booted() > 0)
5158 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5160 r = utmp_put_shutdown();
5162 log_warning("Failed to write utmp record: %s", strerror(-r));
5169 halt_now(arg_action);
5170 /* We should never reach this. */
5174 static int runlevel_main(void) {
5175 int r, runlevel, previous;
5177 r = utmp_get_runlevel(&runlevel, &previous);
5184 previous <= 0 ? 'N' : previous,
5185 runlevel <= 0 ? 'N' : runlevel);
5190 int main(int argc, char*argv[]) {
5191 int r, retval = EXIT_FAILURE;
5192 DBusConnection *bus = NULL;
5195 dbus_error_init(&error);
5197 log_parse_environment();
5200 r = parse_argv(argc, argv);
5204 retval = EXIT_SUCCESS;
5208 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5209 * let's shortcut this */
5210 if (arg_action == ACTION_RUNLEVEL) {
5211 r = runlevel_main();
5212 retval = r < 0 ? EXIT_FAILURE : r;
5216 if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5217 log_info("Running in chroot, ignoring request.");
5223 if (arg_transport == TRANSPORT_NORMAL)
5224 bus_connect(arg_scope == UNIT_FILE_SYSTEM ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, &bus, &private_bus, &error);
5225 else if (arg_transport == TRANSPORT_POLKIT) {
5226 bus_connect_system_polkit(&bus, &error);
5227 private_bus = false;
5228 } else if (arg_transport == TRANSPORT_SSH) {
5229 bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5230 private_bus = false;
5232 assert_not_reached("Uh, invalid transport...");
5235 switch (arg_action) {
5237 case ACTION_SYSTEMCTL:
5238 r = systemctl_main(bus, argc, argv, &error);
5242 case ACTION_POWEROFF:
5248 case ACTION_RUNLEVEL2:
5249 case ACTION_RUNLEVEL3:
5250 case ACTION_RUNLEVEL4:
5251 case ACTION_RUNLEVEL5:
5253 case ACTION_EMERGENCY:
5254 case ACTION_DEFAULT:
5255 r = start_with_fallback(bus);
5260 r = reload_with_fallback(bus);
5263 case ACTION_CANCEL_SHUTDOWN: {
5267 m = strv_join(arg_wall, " ");
5269 retval = EXIT_FAILURE;
5273 r = send_shutdownd(arg_when, SD_SHUTDOWN_NONE, false, !arg_no_wall, m);
5275 log_warning("Failed to talk to shutdownd, shutdown hasn't been cancelled: %s", strerror(-r));
5280 case ACTION_INVALID:
5281 case ACTION_RUNLEVEL:
5283 assert_not_reached("Unknown action");
5286 retval = r < 0 ? EXIT_FAILURE : r;
5290 dbus_connection_flush(bus);
5291 dbus_connection_close(bus);
5292 dbus_connection_unref(bus);
5295 dbus_error_free(&error);
5299 strv_free(arg_property);
5302 ask_password_agent_close();
5303 polkit_agent_close();