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_sync = false;
78 static bool arg_no_wall = false;
79 static bool arg_no_reload = false;
80 static bool arg_dry = false;
81 static bool arg_quiet = false;
82 static bool arg_full = false;
83 static int arg_force = 0;
84 static bool arg_ask_password = true;
85 static bool arg_failed = false;
86 static bool arg_runtime = false;
87 static char **arg_wall = NULL;
88 static const char *arg_kill_who = NULL;
89 static int arg_signal = SIGTERM;
90 static const char *arg_root = NULL;
91 static usec_t arg_when = 0;
112 ACTION_CANCEL_SHUTDOWN,
114 } arg_action = ACTION_SYSTEMCTL;
120 static enum transport {
124 } arg_transport = TRANSPORT_NORMAL;
125 static const char *arg_host = NULL;
126 static bool arg_follow = false;
127 static unsigned arg_lines = 10;
128 static OutputMode arg_output = OUTPUT_SHORT;
130 static bool private_bus = false;
132 static int daemon_reload(DBusConnection *bus, char **args);
133 static void halt_now(enum action a);
135 static bool on_tty(void) {
138 /* Note that this is invoked relatively early, before we start
139 * the pager. That means the value we return reflects whether
140 * we originally were started on a tty, not if we currently
141 * are. But this is intended, since we want colour and so on
142 * when run in our own pager. */
144 if (_unlikely_(t < 0))
145 t = isatty(STDOUT_FILENO) > 0;
150 static void pager_open_if_enabled(void) {
152 /* Cache result before we open the pager */
161 static void ask_password_agent_open_if_enabled(void) {
163 /* Open the password agent as a child process if necessary */
165 if (!arg_ask_password)
168 if (arg_scope != UNIT_FILE_SYSTEM)
171 ask_password_agent_open();
175 static void polkit_agent_open_if_enabled(void) {
177 /* Open the polkit agent as a child process if necessary */
179 if (!arg_ask_password)
182 if (arg_scope != UNIT_FILE_SYSTEM)
189 static const char *ansi_highlight_red(bool b) {
194 return b ? ANSI_HIGHLIGHT_RED_ON : ANSI_HIGHLIGHT_OFF;
197 static const char *ansi_highlight_green(bool b) {
202 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
205 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
208 if (!dbus_error_is_set(error))
211 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
212 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
213 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
214 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
215 return EXIT_NOPERMISSION;
217 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
218 return EXIT_NOTINSTALLED;
220 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
221 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
222 return EXIT_NOTIMPLEMENTED;
224 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
225 return EXIT_NOTCONFIGURED;
233 static void warn_wall(enum action a) {
234 static const char *table[_ACTION_MAX] = {
235 [ACTION_HALT] = "The system is going down for system halt NOW!",
236 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
237 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
238 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
239 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
240 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!",
241 [ACTION_CANCEL_SHUTDOWN] = "The system shutdown has been cancelled NOW!"
250 p = strv_join(arg_wall, " ");
252 log_error("Failed to join strings.");
268 utmp_wall(table[a], NULL);
271 static bool avoid_bus(void) {
273 if (running_in_chroot() > 0)
276 if (sd_booted() <= 0)
279 if (!isempty(arg_root))
282 if (arg_scope == UNIT_FILE_GLOBAL)
290 const char *description;
291 const char *load_state;
292 const char *active_state;
293 const char *sub_state;
294 const char *following;
295 const char *unit_path;
297 const char *job_type;
298 const char *job_path;
301 static int compare_unit_info(const void *a, const void *b) {
303 const struct unit_info *u = a, *v = b;
305 d1 = strrchr(u->id, '.');
306 d2 = strrchr(v->id, '.');
311 if ((r = strcasecmp(d1, d2)) != 0)
315 return strcasecmp(u->id, v->id);
318 static bool output_show_unit(const struct unit_info *u) {
322 return streq(u->active_state, "failed");
324 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
325 streq(dot+1, arg_type))) &&
326 (!arg_load_state || streq(u->load_state, arg_load_state)) &&
327 (arg_all || !(streq(u->active_state, "inactive")
328 || u->following[0]) || u->job_id > 0);
331 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
332 unsigned id_len, max_id_len, active_len, sub_len, job_len, desc_len, n_shown = 0;
333 const struct unit_info *u;
335 max_id_len = sizeof("UNIT")-1;
336 active_len = sizeof("ACTIVE")-1;
337 sub_len = sizeof("SUB")-1;
338 job_len = sizeof("JOB")-1;
341 for (u = unit_infos; u < unit_infos + c; u++) {
342 if (!output_show_unit(u))
345 max_id_len = MAX(max_id_len, strlen(u->id));
346 active_len = MAX(active_len, strlen(u->active_state));
347 sub_len = MAX(sub_len, strlen(u->sub_state));
349 job_len = MAX(job_len, strlen(u->job_type));
354 id_len = MIN(max_id_len, 25);
355 basic_len = 5 + id_len + 6 + active_len + sub_len + job_len;
356 if (basic_len < (unsigned) columns()) {
357 unsigned extra_len, incr;
358 extra_len = columns() - basic_len;
359 /* Either UNIT already got 25, or is fully satisfied.
360 * Grant up to 25 to DESC now. */
361 incr = MIN(extra_len, 25);
364 /* split the remaining space between UNIT and DESC,
365 * but do not give UNIT more than it needs. */
367 incr = MIN(extra_len / 2, max_id_len - id_len);
369 desc_len += extra_len - incr;
375 if (!arg_no_legend) {
376 printf("%-*s %-6s %-*s %-*s %-*s ", id_len, "UNIT", "LOAD",
377 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
378 if (!arg_full && arg_no_pager)
379 printf("%.*s\n", desc_len, "DESCRIPTION");
381 printf("%s\n", "DESCRIPTION");
384 for (u = unit_infos; u < unit_infos + c; u++) {
386 const char *on_loaded, *off_loaded;
387 const char *on_active, *off_active;
389 if (!output_show_unit(u))
394 if (streq(u->load_state, "error")) {
395 on_loaded = ansi_highlight_red(true);
396 off_loaded = ansi_highlight_red(false);
398 on_loaded = off_loaded = "";
400 if (streq(u->active_state, "failed")) {
401 on_active = ansi_highlight_red(true);
402 off_active = ansi_highlight_red(false);
404 on_active = off_active = "";
406 e = arg_full ? NULL : ellipsize(u->id, id_len, 33);
408 printf("%-*s %s%-6s%s %s%-*s %-*s%s %-*s ",
409 id_len, e ? e : u->id,
410 on_loaded, u->load_state, off_loaded,
411 on_active, active_len, u->active_state,
412 sub_len, u->sub_state, off_active,
413 job_len, u->job_id ? u->job_type : "");
414 if (!arg_full && arg_no_pager)
415 printf("%.*s\n", desc_len, u->description);
417 printf("%s\n", u->description);
422 if (!arg_no_legend) {
423 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
424 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
425 "SUB = The low-level unit activation state, values depend on unit type.\n"
426 "JOB = Pending job for the unit.\n");
429 printf("\n%u units listed.\n", n_shown);
431 printf("\n%u units listed. Pass --all to see inactive units, too.\n", n_shown);
435 static int list_units(DBusConnection *bus, char **args) {
436 DBusMessage *reply = NULL;
438 DBusMessageIter iter, sub, sub2;
439 unsigned c = 0, n_units = 0;
440 struct unit_info *unit_infos = NULL;
442 pager_open_if_enabled();
444 r = bus_method_call_with_reply (
446 "org.freedesktop.systemd1",
447 "/org/freedesktop/systemd1",
448 "org.freedesktop.systemd1.Manager",
456 if (!dbus_message_iter_init(reply, &iter) ||
457 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
458 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
459 log_error("Failed to parse reply.");
464 dbus_message_iter_recurse(&iter, &sub);
466 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
469 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
470 log_error("Failed to parse reply.");
478 n_units = MAX(2*c, 16);
479 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
482 log_error("Failed to allocate unit array.");
492 dbus_message_iter_recurse(&sub, &sub2);
494 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
495 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
496 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
497 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
498 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
499 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
500 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
501 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
502 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
503 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
504 log_error("Failed to parse reply.");
509 dbus_message_iter_next(&sub);
514 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
515 output_units_list(unit_infos, c);
520 dbus_message_unref(reply);
527 static int compare_unit_file_list(const void *a, const void *b) {
529 const UnitFileList *u = a, *v = b;
531 d1 = strrchr(u->path, '.');
532 d2 = strrchr(v->path, '.');
537 r = strcasecmp(d1, d2);
542 return strcasecmp(path_get_file_name(u->path), path_get_file_name(v->path));
545 static bool output_show_unit_file(const UnitFileList *u) {
548 return !arg_type || ((dot = strrchr(u->path, '.')) && streq(dot+1, arg_type));
551 static void output_unit_file_list(const UnitFileList *units, unsigned c) {
552 unsigned max_id_len, id_cols, state_cols, n_shown = 0;
553 const UnitFileList *u;
555 max_id_len = sizeof("UNIT FILE")-1;
556 state_cols = sizeof("STATE")-1;
557 for (u = units; u < units + c; u++) {
558 if (!output_show_unit_file(u))
561 max_id_len = MAX(max_id_len, strlen(path_get_file_name(u->path)));
562 state_cols = MAX(state_cols, strlen(unit_file_state_to_string(u->state)));
567 id_cols = MIN(max_id_len, 25);
568 basic_cols = 1 + id_cols + state_cols;
569 if (basic_cols < (unsigned) columns())
570 id_cols += MIN(columns() - basic_cols, max_id_len - id_cols);
572 id_cols = max_id_len;
575 printf("%-*s %-*s\n", id_cols, "UNIT FILE", state_cols, "STATE");
577 for (u = units; u < units + c; u++) {
579 const char *on, *off;
582 if (!output_show_unit_file(u))
587 if (u->state == UNIT_FILE_MASKED ||
588 u->state == UNIT_FILE_MASKED_RUNTIME ||
589 u->state == UNIT_FILE_DISABLED) {
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_lines * 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, 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 " -n --no-sync Don't sync before halt/power-off/reboot\n"
3953 " --no-wall Don't send wall message before halt/power-off/reboot\n",
3954 program_invocation_short_name,
3955 arg_action == ACTION_REBOOT ? "Reboot" :
3956 arg_action == ACTION_POWEROFF ? "Power off" :
3962 static int shutdown_help(void) {
3964 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3965 "Shut down the system.\n\n"
3966 " --help Show this help\n"
3967 " -H --halt Halt the machine\n"
3968 " -P --poweroff Power-off the machine\n"
3969 " -r --reboot Reboot the machine\n"
3970 " -h Equivalent to --poweroff, overridden by --halt\n"
3971 " -k Don't halt/power-off/reboot, just send warnings\n"
3972 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3973 " -c Cancel a pending shutdown\n",
3974 program_invocation_short_name);
3979 static int telinit_help(void) {
3981 printf("%s [OPTIONS...] {COMMAND}\n\n"
3982 "Send control commands to the init daemon.\n\n"
3983 " --help Show this help\n"
3984 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
3986 " 0 Power-off the machine\n"
3987 " 6 Reboot the machine\n"
3988 " 2, 3, 4, 5 Start runlevelX.target unit\n"
3989 " 1, s, S Enter rescue mode\n"
3990 " q, Q Reload init daemon configuration\n"
3991 " u, U Reexecute init daemon\n",
3992 program_invocation_short_name);
3997 static int runlevel_help(void) {
3999 printf("%s [OPTIONS...]\n\n"
4000 "Prints the previous and current runlevel of the init system.\n\n"
4001 " --help Show this help\n",
4002 program_invocation_short_name);
4007 static int systemctl_parse_argv(int argc, char *argv[]) {
4011 ARG_IGNORE_DEPENDENCIES,
4026 ARG_NO_ASK_PASSWORD,
4033 static const struct option options[] = {
4034 { "help", no_argument, NULL, 'h' },
4035 { "version", no_argument, NULL, ARG_VERSION },
4036 { "type", required_argument, NULL, 't' },
4037 { "property", required_argument, NULL, 'p' },
4038 { "all", no_argument, NULL, 'a' },
4039 { "failed", no_argument, NULL, ARG_FAILED },
4040 { "full", no_argument, NULL, ARG_FULL },
4041 { "fail", no_argument, NULL, ARG_FAIL },
4042 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4043 { "user", no_argument, NULL, ARG_USER },
4044 { "system", no_argument, NULL, ARG_SYSTEM },
4045 { "global", no_argument, NULL, ARG_GLOBAL },
4046 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4047 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
4048 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4049 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4050 { "quiet", no_argument, NULL, 'q' },
4051 { "order", no_argument, NULL, ARG_ORDER },
4052 { "require", no_argument, NULL, ARG_REQUIRE },
4053 { "root", required_argument, NULL, ARG_ROOT },
4054 { "force", no_argument, NULL, ARG_FORCE },
4055 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4056 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4057 { "signal", required_argument, NULL, 's' },
4058 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4059 { "host", required_argument, NULL, 'H' },
4060 { "privileged",no_argument, NULL, 'P' },
4061 { "runtime", no_argument, NULL, ARG_RUNTIME },
4062 { "lines", required_argument, NULL, 'n' },
4063 { "follow", no_argument, NULL, ARG_FOLLOW },
4064 { "output", required_argument, NULL, 'o' },
4065 { NULL, 0, NULL, 0 }
4073 while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:Pn:o:", options, NULL)) >= 0) {
4082 puts(PACKAGE_STRING);
4084 puts(SYSTEMD_FEATURES);
4088 if (unit_type_from_string(optarg) >= 0) {
4092 if (unit_load_state_from_string(optarg) >= 0) {
4093 arg_load_state = optarg;
4096 log_error("Unkown unit type or load state '%s'.",
4102 if (!(l = strv_append(arg_property, optarg)))
4105 strv_free(arg_property);
4108 /* If the user asked for a particular
4109 * property, show it to him, even if it is
4120 arg_job_mode = "fail";
4123 case ARG_IGNORE_DEPENDENCIES:
4124 arg_job_mode = "ignore-dependencies";
4128 arg_scope = UNIT_FILE_USER;
4132 arg_scope = UNIT_FILE_SYSTEM;
4136 arg_scope = UNIT_FILE_GLOBAL;
4140 arg_no_block = true;
4144 arg_no_legend = true;
4148 arg_no_pager = true;
4156 arg_dot = DOT_ORDER;
4160 arg_dot = DOT_REQUIRE;
4188 /* -f is short for both --follow and --force! */
4194 arg_no_reload = true;
4198 arg_kill_who = optarg;
4202 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4203 log_error("Failed to parse signal string %s.", optarg);
4208 case ARG_NO_ASK_PASSWORD:
4209 arg_ask_password = false;
4213 arg_transport = TRANSPORT_POLKIT;
4217 arg_transport = TRANSPORT_SSH;
4226 if (safe_atou(optarg, &arg_lines) < 0) {
4227 log_error("Failed to parse lines '%s'", optarg);
4233 arg_output = output_mode_from_string(optarg);
4234 if (arg_output < 0) {
4235 log_error("Unknown output '%s'.", optarg);
4244 log_error("Unknown option code '%c'.", c);
4249 if (arg_transport != TRANSPORT_NORMAL && arg_scope != UNIT_FILE_SYSTEM) {
4250 log_error("Cannot access user instance remotely.");
4257 static int halt_parse_argv(int argc, char *argv[]) {
4266 static const struct option options[] = {
4267 { "help", no_argument, NULL, ARG_HELP },
4268 { "halt", no_argument, NULL, ARG_HALT },
4269 { "poweroff", no_argument, NULL, 'p' },
4270 { "reboot", no_argument, NULL, ARG_REBOOT },
4271 { "force", no_argument, NULL, 'f' },
4272 { "wtmp-only", no_argument, NULL, 'w' },
4273 { "no-wtmp", no_argument, NULL, 'd' },
4274 { "no-sync", no_argument, NULL, 'n' },
4275 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4276 { NULL, 0, NULL, 0 }
4284 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4285 if (runlevel == '0' || runlevel == '6')
4288 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4296 arg_action = ACTION_HALT;
4300 if (arg_action != ACTION_REBOOT)
4301 arg_action = ACTION_POWEROFF;
4305 arg_action = ACTION_REBOOT;
4330 /* Compatibility nops */
4337 log_error("Unknown option code '%c'.", c);
4342 if (optind < argc) {
4343 log_error("Too many arguments.");
4350 static int parse_time_spec(const char *t, usec_t *_u) {
4354 if (streq(t, "now"))
4356 else if (!strchr(t, ':')) {
4359 if (safe_atou64(t, &u) < 0)
4362 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4371 hour = strtol(t, &e, 10);
4372 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4375 minute = strtol(e+1, &e, 10);
4376 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4379 n = now(CLOCK_REALTIME);
4380 s = (time_t) (n / USEC_PER_SEC);
4383 assert_se(localtime_r(&s, &tm));
4385 tm.tm_hour = (int) hour;
4386 tm.tm_min = (int) minute;
4389 assert_se(s = mktime(&tm));
4391 *_u = (usec_t) s * USEC_PER_SEC;
4394 *_u += USEC_PER_DAY;
4400 static int shutdown_parse_argv(int argc, char *argv[]) {
4407 static const struct option options[] = {
4408 { "help", no_argument, NULL, ARG_HELP },
4409 { "halt", no_argument, NULL, 'H' },
4410 { "poweroff", no_argument, NULL, 'P' },
4411 { "reboot", no_argument, NULL, 'r' },
4412 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
4413 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4414 { NULL, 0, NULL, 0 }
4422 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4430 arg_action = ACTION_HALT;
4434 arg_action = ACTION_POWEROFF;
4439 arg_action = ACTION_KEXEC;
4441 arg_action = ACTION_REBOOT;
4445 arg_action = ACTION_KEXEC;
4449 if (arg_action != ACTION_HALT)
4450 arg_action = ACTION_POWEROFF;
4463 /* Compatibility nops */
4467 arg_action = ACTION_CANCEL_SHUTDOWN;
4474 log_error("Unknown option code '%c'.", c);
4479 if (argc > optind && arg_action != ACTION_CANCEL_SHUTDOWN) {
4480 r = parse_time_spec(argv[optind], &arg_when);
4482 log_error("Failed to parse time specification: %s", argv[optind]);
4486 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4488 if (argc > optind && arg_action == ACTION_CANCEL_SHUTDOWN)
4489 /* No time argument for shutdown cancel */
4490 arg_wall = argv + optind;
4491 else if (argc > optind + 1)
4492 /* We skip the time argument */
4493 arg_wall = argv + optind + 1;
4500 static int telinit_parse_argv(int argc, char *argv[]) {
4507 static const struct option options[] = {
4508 { "help", no_argument, NULL, ARG_HELP },
4509 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4510 { NULL, 0, NULL, 0 }
4513 static const struct {
4517 { '0', ACTION_POWEROFF },
4518 { '6', ACTION_REBOOT },
4519 { '1', ACTION_RESCUE },
4520 { '2', ACTION_RUNLEVEL2 },
4521 { '3', ACTION_RUNLEVEL3 },
4522 { '4', ACTION_RUNLEVEL4 },
4523 { '5', ACTION_RUNLEVEL5 },
4524 { 's', ACTION_RESCUE },
4525 { 'S', ACTION_RESCUE },
4526 { 'q', ACTION_RELOAD },
4527 { 'Q', ACTION_RELOAD },
4528 { 'u', ACTION_REEXEC },
4529 { 'U', ACTION_REEXEC }
4538 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4553 log_error("Unknown option code '%c'.", c);
4558 if (optind >= argc) {
4563 if (optind + 1 < argc) {
4564 log_error("Too many arguments.");
4568 if (strlen(argv[optind]) != 1) {
4569 log_error("Expected single character argument.");
4573 for (i = 0; i < ELEMENTSOF(table); i++)
4574 if (table[i].from == argv[optind][0])
4577 if (i >= ELEMENTSOF(table)) {
4578 log_error("Unknown command '%s'.", argv[optind]);
4582 arg_action = table[i].to;
4589 static int runlevel_parse_argv(int argc, char *argv[]) {
4595 static const struct option options[] = {
4596 { "help", no_argument, NULL, ARG_HELP },
4597 { NULL, 0, NULL, 0 }
4605 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4616 log_error("Unknown option code '%c'.", c);
4621 if (optind < argc) {
4622 log_error("Too many arguments.");
4629 static int parse_argv(int argc, char *argv[]) {
4633 if (program_invocation_short_name) {
4635 if (strstr(program_invocation_short_name, "halt")) {
4636 arg_action = ACTION_HALT;
4637 return halt_parse_argv(argc, argv);
4638 } else if (strstr(program_invocation_short_name, "poweroff")) {
4639 arg_action = ACTION_POWEROFF;
4640 return halt_parse_argv(argc, argv);
4641 } else if (strstr(program_invocation_short_name, "reboot")) {
4643 arg_action = ACTION_KEXEC;
4645 arg_action = ACTION_REBOOT;
4646 return halt_parse_argv(argc, argv);
4647 } else if (strstr(program_invocation_short_name, "shutdown")) {
4648 arg_action = ACTION_POWEROFF;
4649 return shutdown_parse_argv(argc, argv);
4650 } else if (strstr(program_invocation_short_name, "init")) {
4652 if (sd_booted() > 0) {
4653 arg_action = ACTION_INVALID;
4654 return telinit_parse_argv(argc, argv);
4656 /* Hmm, so some other init system is
4657 * running, we need to forward this
4658 * request to it. For now we simply
4659 * guess that it is Upstart. */
4661 execv("/lib/upstart/telinit", argv);
4663 log_error("Couldn't find an alternative telinit implementation to spawn.");
4667 } else if (strstr(program_invocation_short_name, "runlevel")) {
4668 arg_action = ACTION_RUNLEVEL;
4669 return runlevel_parse_argv(argc, argv);
4673 arg_action = ACTION_SYSTEMCTL;
4674 return systemctl_parse_argv(argc, argv);
4677 static int action_to_runlevel(void) {
4679 static const char table[_ACTION_MAX] = {
4680 [ACTION_HALT] = '0',
4681 [ACTION_POWEROFF] = '0',
4682 [ACTION_REBOOT] = '6',
4683 [ACTION_RUNLEVEL2] = '2',
4684 [ACTION_RUNLEVEL3] = '3',
4685 [ACTION_RUNLEVEL4] = '4',
4686 [ACTION_RUNLEVEL5] = '5',
4687 [ACTION_RESCUE] = '1'
4690 assert(arg_action < _ACTION_MAX);
4692 return table[arg_action];
4695 static int talk_upstart(void) {
4696 DBusMessage *m = NULL, *reply = NULL;
4698 int previous, rl, r;
4700 env1_buf[] = "RUNLEVEL=X",
4701 env2_buf[] = "PREVLEVEL=X";
4702 char *env1 = env1_buf, *env2 = env2_buf;
4703 const char *emit = "runlevel";
4704 dbus_bool_t b_false = FALSE;
4705 DBusMessageIter iter, sub;
4706 DBusConnection *bus;
4708 dbus_error_init(&error);
4710 if (!(rl = action_to_runlevel()))
4713 if (utmp_get_runlevel(&previous, NULL) < 0)
4716 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4717 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4722 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4727 if ((r = bus_check_peercred(bus)) < 0) {
4728 log_error("Failed to verify owner of bus.");
4732 if (!(m = dbus_message_new_method_call(
4733 "com.ubuntu.Upstart",
4734 "/com/ubuntu/Upstart",
4735 "com.ubuntu.Upstart0_6",
4738 log_error("Could not allocate message.");
4743 dbus_message_iter_init_append(m, &iter);
4745 env1_buf[sizeof(env1_buf)-2] = rl;
4746 env2_buf[sizeof(env2_buf)-2] = previous;
4748 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4749 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4750 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4751 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4752 !dbus_message_iter_close_container(&iter, &sub) ||
4753 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4754 log_error("Could not append arguments to message.");
4759 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4761 if (bus_error_is_no_service(&error)) {
4766 log_error("Failed to issue method call: %s", bus_error_message(&error));
4775 dbus_message_unref(m);
4778 dbus_message_unref(reply);
4781 dbus_connection_flush(bus);
4782 dbus_connection_close(bus);
4783 dbus_connection_unref(bus);
4786 dbus_error_free(&error);
4791 static int talk_initctl(void) {
4792 struct init_request request;
4796 if (!(rl = action_to_runlevel()))
4800 request.magic = INIT_MAGIC;
4801 request.sleeptime = 0;
4802 request.cmd = INIT_CMD_RUNLVL;
4803 request.runlevel = rl;
4805 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4807 if (errno == ENOENT)
4810 log_error("Failed to open "INIT_FIFO": %m");
4815 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4816 close_nointr_nofail(fd);
4819 log_error("Failed to write to "INIT_FIFO": %m");
4820 return errno ? -errno : -EIO;
4826 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4828 static const struct {
4836 int (* const dispatch)(DBusConnection *bus, char **args);
4838 { "list-units", LESS, 1, list_units },
4839 { "list-unit-files", EQUAL, 1, list_unit_files },
4840 { "list-jobs", EQUAL, 1, list_jobs },
4841 { "clear-jobs", EQUAL, 1, daemon_reload },
4842 { "load", MORE, 2, load_unit },
4843 { "cancel", MORE, 2, cancel_job },
4844 { "start", MORE, 2, start_unit },
4845 { "stop", MORE, 2, start_unit },
4846 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
4847 { "reload", MORE, 2, start_unit },
4848 { "restart", MORE, 2, start_unit },
4849 { "try-restart", MORE, 2, start_unit },
4850 { "reload-or-restart", MORE, 2, start_unit },
4851 { "reload-or-try-restart", MORE, 2, start_unit },
4852 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4853 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
4854 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4855 { "isolate", EQUAL, 2, start_unit },
4856 { "kill", MORE, 2, kill_unit },
4857 { "is-active", MORE, 2, check_unit },
4858 { "check", MORE, 2, check_unit },
4859 { "show", MORE, 1, show },
4860 { "status", MORE, 2, show },
4861 { "help", MORE, 2, show },
4862 { "dump", EQUAL, 1, dump },
4863 { "dot", EQUAL, 1, dot },
4864 { "snapshot", LESS, 2, snapshot },
4865 { "delete", MORE, 2, delete_snapshot },
4866 { "daemon-reload", EQUAL, 1, daemon_reload },
4867 { "daemon-reexec", EQUAL, 1, daemon_reload },
4868 { "show-environment", EQUAL, 1, show_enviroment },
4869 { "set-environment", MORE, 2, set_environment },
4870 { "unset-environment", MORE, 2, set_environment },
4871 { "halt", EQUAL, 1, start_special },
4872 { "poweroff", EQUAL, 1, start_special },
4873 { "reboot", EQUAL, 1, start_special },
4874 { "kexec", EQUAL, 1, start_special },
4875 { "suspend", EQUAL, 1, start_special },
4876 { "hibernate", EQUAL, 1, start_special },
4877 { "default", EQUAL, 1, start_special },
4878 { "rescue", EQUAL, 1, start_special },
4879 { "emergency", EQUAL, 1, start_special },
4880 { "exit", EQUAL, 1, start_special },
4881 { "reset-failed", MORE, 1, reset_failed },
4882 { "enable", MORE, 2, enable_unit },
4883 { "disable", MORE, 2, enable_unit },
4884 { "is-enabled", MORE, 2, unit_is_enabled },
4885 { "reenable", MORE, 2, enable_unit },
4886 { "preset", MORE, 2, enable_unit },
4887 { "mask", MORE, 2, enable_unit },
4888 { "unmask", MORE, 2, enable_unit },
4889 { "link", MORE, 2, enable_unit },
4890 { "switch-root", MORE, 2, switch_root },
4900 left = argc - optind;
4903 /* Special rule: no arguments means "list-units" */
4906 if (streq(argv[optind], "help") && !argv[optind+1]) {
4907 log_error("This command expects one or more "
4908 "unit names. Did you mean --help?");
4912 for (i = 0; i < ELEMENTSOF(verbs); i++)
4913 if (streq(argv[optind], verbs[i].verb))
4916 if (i >= ELEMENTSOF(verbs)) {
4917 log_error("Unknown operation '%s'.", argv[optind]);
4922 switch (verbs[i].argc_cmp) {
4925 if (left != verbs[i].argc) {
4926 log_error("Invalid number of arguments.");
4933 if (left < verbs[i].argc) {
4934 log_error("Too few arguments.");
4941 if (left > verbs[i].argc) {
4942 log_error("Too many arguments.");
4949 assert_not_reached("Unknown comparison operator.");
4952 /* Require a bus connection for all operations but
4954 if (!streq(verbs[i].verb, "enable") &&
4955 !streq(verbs[i].verb, "disable") &&
4956 !streq(verbs[i].verb, "is-enabled") &&
4957 !streq(verbs[i].verb, "list-unit-files") &&
4958 !streq(verbs[i].verb, "reenable") &&
4959 !streq(verbs[i].verb, "preset") &&
4960 !streq(verbs[i].verb, "mask") &&
4961 !streq(verbs[i].verb, "unmask") &&
4962 !streq(verbs[i].verb, "link")) {
4964 if (running_in_chroot() > 0) {
4965 log_info("Running in chroot, ignoring request.");
4969 if (((!streq(verbs[i].verb, "reboot") &&
4970 !streq(verbs[i].verb, "halt") &&
4971 !streq(verbs[i].verb, "poweroff")) || arg_force <= 0) && !bus) {
4972 log_error("Failed to get D-Bus connection: %s",
4973 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
4979 if (!bus && !avoid_bus()) {
4980 log_error("Failed to get D-Bus connection: %s",
4981 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
4986 return verbs[i].dispatch(bus, argv + optind);
4989 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
4991 struct msghdr msghdr;
4992 struct iovec iovec[2];
4993 union sockaddr_union sockaddr;
4994 struct sd_shutdown_command c;
4996 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
5003 c.dry_run = dry_run;
5007 sockaddr.sa.sa_family = AF_UNIX;
5008 strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5011 msghdr.msg_name = &sockaddr;
5012 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5015 iovec[0].iov_base = (char*) &c;
5016 iovec[0].iov_len = offsetof(struct sd_shutdown_command, wall_message);
5018 if (isempty(message))
5019 msghdr.msg_iovlen = 1;
5021 iovec[1].iov_base = (char*) message;
5022 iovec[1].iov_len = strlen(message);
5023 msghdr.msg_iovlen = 2;
5025 msghdr.msg_iov = iovec;
5027 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5028 close_nointr_nofail(fd);
5032 close_nointr_nofail(fd);
5036 static int reload_with_fallback(DBusConnection *bus) {
5039 /* First, try systemd via D-Bus. */
5040 if (daemon_reload(bus, NULL) >= 0)
5044 /* Nothing else worked, so let's try signals */
5045 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5047 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5048 log_error("kill() failed: %m");
5055 static int start_with_fallback(DBusConnection *bus) {
5058 /* First, try systemd via D-Bus. */
5059 if (start_unit(bus, NULL) >= 0)
5063 /* Hmm, talking to systemd via D-Bus didn't work. Then
5064 * let's try to talk to Upstart via D-Bus. */
5065 if (talk_upstart() > 0)
5068 /* Nothing else worked, so let's try
5070 if (talk_initctl() > 0)
5073 log_error("Failed to talk to init daemon.");
5077 warn_wall(arg_action);
5081 static _noreturn_ void halt_now(enum action a) {
5083 /* Make sure C-A-D is handled by the kernel from this
5085 reboot(RB_ENABLE_CAD);
5090 log_info("Halting.");
5091 reboot(RB_HALT_SYSTEM);
5094 case ACTION_POWEROFF:
5095 log_info("Powering off.");
5096 reboot(RB_POWER_OFF);
5100 log_info("Rebooting.");
5101 reboot(RB_AUTOBOOT);
5105 assert_not_reached("Unknown halt action.");
5108 assert_not_reached("Uh? This shouldn't happen.");
5111 static int halt_main(DBusConnection *bus) {
5114 if (geteuid() != 0) {
5115 /* Try logind if we are a normal user and no special
5116 * mode applies. Maybe PolicyKit allows us to shutdown
5119 if (arg_when <= 0 &&
5122 (arg_action == ACTION_POWEROFF ||
5123 arg_action == ACTION_REBOOT)) {
5124 r = reboot_with_logind(bus, arg_action);
5129 log_error("Must be root.");
5136 m = strv_join(arg_wall, " ");
5137 r = send_shutdownd(arg_when,
5138 arg_action == ACTION_HALT ? 'H' :
5139 arg_action == ACTION_POWEROFF ? 'P' :
5140 arg_action == ACTION_KEXEC ? 'K' :
5148 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5150 char date[FORMAT_TIMESTAMP_MAX];
5152 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5153 format_timestamp(date, sizeof(date), arg_when));
5158 if (!arg_dry && !arg_force)
5159 return start_with_fallback(bus);
5162 if (sd_booted() > 0)
5163 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5165 r = utmp_put_shutdown();
5167 log_warning("Failed to write utmp record: %s", strerror(-r));
5177 halt_now(arg_action);
5178 /* We should never reach this. */
5182 static int runlevel_main(void) {
5183 int r, runlevel, previous;
5185 r = utmp_get_runlevel(&runlevel, &previous);
5192 previous <= 0 ? 'N' : previous,
5193 runlevel <= 0 ? 'N' : runlevel);
5198 int main(int argc, char*argv[]) {
5199 int r, retval = EXIT_FAILURE;
5200 DBusConnection *bus = NULL;
5203 dbus_error_init(&error);
5205 log_parse_environment();
5208 r = parse_argv(argc, argv);
5212 retval = EXIT_SUCCESS;
5216 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5217 * let's shortcut this */
5218 if (arg_action == ACTION_RUNLEVEL) {
5219 r = runlevel_main();
5220 retval = r < 0 ? EXIT_FAILURE : r;
5224 if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5225 log_info("Running in chroot, ignoring request.");
5231 if (arg_transport == TRANSPORT_NORMAL)
5232 bus_connect(arg_scope == UNIT_FILE_SYSTEM ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, &bus, &private_bus, &error);
5233 else if (arg_transport == TRANSPORT_POLKIT) {
5234 bus_connect_system_polkit(&bus, &error);
5235 private_bus = false;
5236 } else if (arg_transport == TRANSPORT_SSH) {
5237 bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5238 private_bus = false;
5240 assert_not_reached("Uh, invalid transport...");
5243 switch (arg_action) {
5245 case ACTION_SYSTEMCTL:
5246 r = systemctl_main(bus, argc, argv, &error);
5250 case ACTION_POWEROFF:
5256 case ACTION_RUNLEVEL2:
5257 case ACTION_RUNLEVEL3:
5258 case ACTION_RUNLEVEL4:
5259 case ACTION_RUNLEVEL5:
5261 case ACTION_EMERGENCY:
5262 case ACTION_DEFAULT:
5263 r = start_with_fallback(bus);
5268 r = reload_with_fallback(bus);
5271 case ACTION_CANCEL_SHUTDOWN: {
5275 m = strv_join(arg_wall, " ");
5277 retval = EXIT_FAILURE;
5281 r = send_shutdownd(arg_when, SD_SHUTDOWN_NONE, false, !arg_no_wall, m);
5283 log_warning("Failed to talk to shutdownd, shutdown hasn't been cancelled: %s", strerror(-r));
5288 case ACTION_INVALID:
5289 case ACTION_RUNLEVEL:
5291 assert_not_reached("Unknown action");
5294 retval = r < 0 ? EXIT_FAILURE : r;
5298 dbus_connection_flush(bus);
5299 dbus_connection_close(bus);
5300 dbus_connection_unref(bus);
5303 dbus_error_free(&error);
5307 strv_free(arg_property);
5310 ask_password_agent_close();
5311 polkit_agent_close();