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"
49 #include "dbus-common.h"
50 #include "cgroup-show.h"
51 #include "cgroup-util.h"
53 #include "path-lookup.h"
54 #include "conf-parser.h"
55 #include "exit-status.h"
56 #include "bus-errors.h"
58 #include "unit-name.h"
60 #include "spawn-ask-password-agent.h"
61 #include "spawn-polkit-agent.h"
63 #include "logs-show.h"
65 static const char *arg_type = NULL;
66 static char **arg_property = NULL;
67 static bool arg_all = false;
68 static const char *arg_job_mode = "replace";
69 static UnitFileScope arg_scope = UNIT_FILE_SYSTEM;
70 static bool arg_no_block = false;
71 static bool arg_no_legend = false;
72 static bool arg_no_pager = false;
73 static bool arg_no_wtmp = false;
74 static bool arg_no_sync = false;
75 static bool arg_no_wall = false;
76 static bool arg_no_reload = false;
77 static bool arg_dry = false;
78 static bool arg_quiet = false;
79 static bool arg_full = false;
80 static int arg_force = 0;
81 static bool arg_ask_password = true;
82 static bool arg_failed = false;
83 static bool arg_runtime = false;
84 static char **arg_wall = NULL;
85 static const char *arg_kill_who = NULL;
86 static const char *arg_kill_mode = NULL;
87 static int arg_signal = SIGTERM;
88 static const char *arg_root = NULL;
89 static usec_t arg_when = 0;
108 ACTION_CANCEL_SHUTDOWN,
110 } arg_action = ACTION_SYSTEMCTL;
116 static enum transport {
120 } arg_transport = TRANSPORT_NORMAL;
121 static const char *arg_host = NULL;
122 static bool arg_follow = false;
123 static unsigned arg_lines = 10;
124 static OutputMode arg_output = OUTPUT_SHORT;
126 static bool private_bus = false;
128 static int daemon_reload(DBusConnection *bus, char **args);
129 static void halt_now(enum action a);
131 static bool on_tty(void) {
134 /* Note that this is invoked relatively early, before we start
135 * the pager. That means the value we return reflects whether
136 * we originally were started on a tty, not if we currently
137 * are. But this is intended, since we want colour and so on
138 * when run in our own pager. */
140 if (_unlikely_(t < 0))
141 t = isatty(STDOUT_FILENO) > 0;
146 static void pager_open_if_enabled(void) {
148 /* Cache result before we open the pager */
157 static void ask_password_agent_open_if_enabled(void) {
159 /* Open the password agent as a child process if necessary */
161 if (!arg_ask_password)
164 if (arg_scope != UNIT_FILE_SYSTEM)
167 ask_password_agent_open();
170 static void polkit_agent_open_if_enabled(void) {
172 /* Open the polkit agent as a child process if necessary */
174 if (!arg_ask_password)
177 if (arg_scope != UNIT_FILE_SYSTEM)
183 static const char *ansi_highlight_red(bool b) {
188 return b ? ANSI_HIGHLIGHT_RED_ON : ANSI_HIGHLIGHT_OFF;
191 static const char *ansi_highlight_green(bool b) {
196 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
199 static bool error_is_no_service(const DBusError *error) {
202 if (!dbus_error_is_set(error))
205 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
208 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
211 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
214 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
217 if (!dbus_error_is_set(error))
220 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
221 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
222 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
223 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
224 return EXIT_NOPERMISSION;
226 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
227 return EXIT_NOTINSTALLED;
229 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
230 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
231 return EXIT_NOTIMPLEMENTED;
233 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
234 return EXIT_NOTCONFIGURED;
242 static void warn_wall(enum action a) {
243 static const char *table[_ACTION_MAX] = {
244 [ACTION_HALT] = "The system is going down for system halt NOW!",
245 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
246 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
247 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
248 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
249 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
258 p = strv_join(arg_wall, " ");
260 log_error("Failed to join strings.");
276 utmp_wall(table[a], NULL);
279 static bool avoid_bus(void) {
281 if (running_in_chroot() > 0)
284 if (sd_booted() <= 0)
287 if (!isempty(arg_root))
290 if (arg_scope == UNIT_FILE_GLOBAL)
298 const char *description;
299 const char *load_state;
300 const char *active_state;
301 const char *sub_state;
302 const char *following;
303 const char *unit_path;
305 const char *job_type;
306 const char *job_path;
309 static int compare_unit_info(const void *a, const void *b) {
311 const struct unit_info *u = a, *v = b;
313 d1 = strrchr(u->id, '.');
314 d2 = strrchr(v->id, '.');
319 if ((r = strcasecmp(d1, d2)) != 0)
323 return strcasecmp(u->id, v->id);
326 static bool output_show_unit(const struct unit_info *u) {
330 return streq(u->active_state, "failed");
332 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
333 streq(dot+1, arg_type))) &&
334 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0);
337 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
338 unsigned id_len, max_id_len, active_len, sub_len, job_len, desc_len, n_shown = 0;
339 const struct unit_info *u;
341 max_id_len = sizeof("UNIT")-1;
342 active_len = sizeof("ACTIVE")-1;
343 sub_len = sizeof("SUB")-1;
344 job_len = sizeof("JOB")-1;
347 for (u = unit_infos; u < unit_infos + c; u++) {
348 if (!output_show_unit(u))
351 max_id_len = MAX(max_id_len, strlen(u->id));
352 active_len = MAX(active_len, strlen(u->active_state));
353 sub_len = MAX(sub_len, strlen(u->sub_state));
355 job_len = MAX(job_len, strlen(u->job_type));
360 id_len = MIN(max_id_len, 25);
361 basic_len = 5 + id_len + 6 + active_len + sub_len + job_len;
362 if (basic_len < (unsigned) columns()) {
363 unsigned extra_len, incr;
364 extra_len = columns() - basic_len;
365 /* Either UNIT already got 25, or is fully satisfied.
366 * Grant up to 25 to DESC now. */
367 incr = MIN(extra_len, 25);
370 /* split the remaining space between UNIT and DESC,
371 * but do not give UNIT more than it needs. */
373 incr = MIN(extra_len / 2, max_id_len - id_len);
375 desc_len += extra_len - incr;
381 if (!arg_no_legend) {
382 printf("%-*s %-6s %-*s %-*s %-*s ", id_len, "UNIT", "LOAD",
383 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
384 if (!arg_full && arg_no_pager)
385 printf("%.*s\n", desc_len, "DESCRIPTION");
387 printf("%s\n", "DESCRIPTION");
390 for (u = unit_infos; u < unit_infos + c; u++) {
392 const char *on_loaded, *off_loaded;
393 const char *on_active, *off_active;
395 if (!output_show_unit(u))
400 if (streq(u->load_state, "error")) {
401 on_loaded = ansi_highlight_red(true);
402 off_loaded = ansi_highlight_red(false);
404 on_loaded = off_loaded = "";
406 if (streq(u->active_state, "failed")) {
407 on_active = ansi_highlight_red(true);
408 off_active = ansi_highlight_red(false);
410 on_active = off_active = "";
412 e = arg_full ? NULL : ellipsize(u->id, id_len, 33);
414 printf("%-*s %s%-6s%s %s%-*s %-*s%s %-*s ",
415 id_len, e ? e : u->id,
416 on_loaded, u->load_state, off_loaded,
417 on_active, active_len, u->active_state,
418 sub_len, u->sub_state, off_active,
419 job_len, u->job_id ? u->job_type : "");
420 if (!arg_full && arg_no_pager)
421 printf("%.*s\n", desc_len, u->description);
423 printf("%s\n", u->description);
428 if (!arg_no_legend) {
429 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
430 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
431 "SUB = The low-level unit activation state, values depend on unit type.\n"
432 "JOB = Pending job for the unit.\n");
435 printf("\n%u units listed.\n", n_shown);
437 printf("\n%u units listed. Pass --all to see inactive units, too.\n", n_shown);
441 static int list_units(DBusConnection *bus, char **args) {
442 DBusMessage *m = NULL, *reply = NULL;
445 DBusMessageIter iter, sub, sub2;
446 unsigned c = 0, n_units = 0;
447 struct unit_info *unit_infos = NULL;
449 dbus_error_init(&error);
453 pager_open_if_enabled();
455 if (!(m = dbus_message_new_method_call(
456 "org.freedesktop.systemd1",
457 "/org/freedesktop/systemd1",
458 "org.freedesktop.systemd1.Manager",
460 log_error("Could not allocate message.");
464 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
465 log_error("Failed to issue method call: %s", bus_error_message(&error));
470 if (!dbus_message_iter_init(reply, &iter) ||
471 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
472 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
473 log_error("Failed to parse reply.");
478 dbus_message_iter_recurse(&iter, &sub);
480 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
483 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
484 log_error("Failed to parse reply.");
492 n_units = MAX(2*c, 16);
493 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
496 log_error("Failed to allocate unit array.");
506 dbus_message_iter_recurse(&sub, &sub2);
508 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
509 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
510 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
511 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
512 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
513 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
514 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
515 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
516 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
517 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
518 log_error("Failed to parse reply.");
523 dbus_message_iter_next(&sub);
528 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
529 output_units_list(unit_infos, c);
536 dbus_message_unref(m);
539 dbus_message_unref(reply);
543 dbus_error_free(&error);
548 static int compare_unit_file_list(const void *a, const void *b) {
550 const UnitFileList *u = a, *v = b;
552 d1 = strrchr(u->path, '.');
553 d2 = strrchr(v->path, '.');
558 r = strcasecmp(d1, d2);
563 return strcasecmp(file_name_from_path(u->path), file_name_from_path(v->path));
566 static bool output_show_unit_file(const UnitFileList *u) {
569 return !arg_type || ((dot = strrchr(u->path, '.')) && streq(dot+1, arg_type));
572 static void output_unit_file_list(const UnitFileList *units, unsigned c) {
573 unsigned max_id_len, id_cols, state_cols, n_shown = 0;
574 const UnitFileList *u;
576 max_id_len = sizeof("UNIT FILE")-1;
577 state_cols = sizeof("STATE")-1;
578 for (u = units; u < units + c; u++) {
579 if (!output_show_unit_file(u))
582 max_id_len = MAX(max_id_len, strlen(file_name_from_path(u->path)));
583 state_cols = MAX(state_cols, strlen(unit_file_state_to_string(u->state)));
588 id_cols = MIN(max_id_len, 25);
589 basic_cols = 1 + id_cols + state_cols;
590 if (basic_cols < (unsigned) columns())
591 id_cols += MIN(columns() - basic_cols, max_id_len - id_cols);
593 id_cols = max_id_len;
596 printf("%-*s %-*s\n", id_cols, "UNIT FILE", state_cols, "STATE");
598 for (u = units; u < units + c; u++) {
600 const char *on, *off;
603 if (!output_show_unit_file(u))
608 if (u->state == UNIT_FILE_MASKED ||
609 u->state == UNIT_FILE_MASKED_RUNTIME ||
610 u->state == UNIT_FILE_DISABLED) {
611 on = ansi_highlight_red(true);
612 off = ansi_highlight_red(false);
613 } else if (u->state == UNIT_FILE_ENABLED) {
614 on = ansi_highlight_green(true);
615 off = ansi_highlight_green(false);
619 id = file_name_from_path(u->path);
621 e = arg_full ? NULL : ellipsize(id, id_cols, 33);
623 printf("%-*s %s%-*s%s\n",
625 on, state_cols, unit_file_state_to_string(u->state), off);
631 printf("\n%u unit files listed.\n", n_shown);
634 static int list_unit_files(DBusConnection *bus, char **args) {
635 DBusMessage *m = NULL, *reply = NULL;
638 DBusMessageIter iter, sub, sub2;
639 unsigned c = 0, n_units = 0;
640 UnitFileList *units = NULL;
642 dbus_error_init(&error);
644 pager_open_if_enabled();
651 h = hashmap_new(string_hash_func, string_compare_func);
653 log_error("Out of memory");
657 r = unit_file_get_list(arg_scope, arg_root, h);
659 unit_file_list_free(h);
660 log_error("Failed to get unit file list: %s", strerror(-r));
664 n_units = hashmap_size(h);
665 units = new(UnitFileList, n_units);
667 unit_file_list_free(h);
668 log_error("Out of memory");
672 HASHMAP_FOREACH(u, h, i) {
673 memcpy(units + c++, u, sizeof(UnitFileList));
681 m = dbus_message_new_method_call(
682 "org.freedesktop.systemd1",
683 "/org/freedesktop/systemd1",
684 "org.freedesktop.systemd1.Manager",
687 log_error("Could not allocate message.");
691 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
693 log_error("Failed to issue method call: %s", bus_error_message(&error));
698 if (!dbus_message_iter_init(reply, &iter) ||
699 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
700 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
701 log_error("Failed to parse reply.");
706 dbus_message_iter_recurse(&iter, &sub);
708 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
712 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
713 log_error("Failed to parse reply.");
721 n_units = MAX(2*c, 16);
722 w = realloc(units, sizeof(struct UnitFileList) * n_units);
725 log_error("Failed to allocate unit array.");
735 dbus_message_iter_recurse(&sub, &sub2);
737 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->path, true) < 0 ||
738 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, false) < 0) {
739 log_error("Failed to parse reply.");
744 u->state = unit_file_state_from_string(state);
746 dbus_message_iter_next(&sub);
752 qsort(units, c, sizeof(UnitFileList), compare_unit_file_list);
753 output_unit_file_list(units, c);
760 dbus_message_unref(m);
763 dbus_message_unref(reply);
767 dbus_error_free(&error);
772 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
773 static const char * const colors[] = {
774 "Requires", "[color=\"black\"]",
775 "RequiresOverridable", "[color=\"black\"]",
776 "Requisite", "[color=\"darkblue\"]",
777 "RequisiteOverridable", "[color=\"darkblue\"]",
778 "Wants", "[color=\"darkgrey\"]",
779 "Conflicts", "[color=\"red\"]",
780 "ConflictedBy", "[color=\"red\"]",
781 "After", "[color=\"green\"]"
784 const char *c = NULL;
791 for (i = 0; i < ELEMENTSOF(colors); i += 2)
792 if (streq(colors[i], prop)) {
800 if (arg_dot != DOT_ALL)
801 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
804 switch (dbus_message_iter_get_arg_type(iter)) {
806 case DBUS_TYPE_ARRAY:
808 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
811 dbus_message_iter_recurse(iter, &sub);
813 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
816 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
817 dbus_message_iter_get_basic(&sub, &s);
818 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
820 dbus_message_iter_next(&sub);
830 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
831 DBusMessage *m = NULL, *reply = NULL;
832 const char *interface = "org.freedesktop.systemd1.Unit";
835 DBusMessageIter iter, sub, sub2, sub3;
840 dbus_error_init(&error);
842 if (!(m = dbus_message_new_method_call(
843 "org.freedesktop.systemd1",
845 "org.freedesktop.DBus.Properties",
847 log_error("Could not allocate message.");
852 if (!dbus_message_append_args(m,
853 DBUS_TYPE_STRING, &interface,
854 DBUS_TYPE_INVALID)) {
855 log_error("Could not append arguments to message.");
860 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
861 log_error("Failed to issue method call: %s", bus_error_message(&error));
866 if (!dbus_message_iter_init(reply, &iter) ||
867 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
868 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
869 log_error("Failed to parse reply.");
874 dbus_message_iter_recurse(&iter, &sub);
876 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
879 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
880 log_error("Failed to parse reply.");
885 dbus_message_iter_recurse(&sub, &sub2);
887 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
888 log_error("Failed to parse reply.");
893 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
894 log_error("Failed to parse reply.");
899 dbus_message_iter_recurse(&sub2, &sub3);
901 if (dot_one_property(name, prop, &sub3)) {
902 log_error("Failed to parse reply.");
907 dbus_message_iter_next(&sub);
914 dbus_message_unref(m);
917 dbus_message_unref(reply);
919 dbus_error_free(&error);
924 static int dot(DBusConnection *bus, char **args) {
925 DBusMessage *m = NULL, *reply = NULL;
928 DBusMessageIter iter, sub, sub2;
930 dbus_error_init(&error);
934 if (!(m = dbus_message_new_method_call(
935 "org.freedesktop.systemd1",
936 "/org/freedesktop/systemd1",
937 "org.freedesktop.systemd1.Manager",
939 log_error("Could not allocate message.");
943 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
944 log_error("Failed to issue method call: %s", bus_error_message(&error));
949 if (!dbus_message_iter_init(reply, &iter) ||
950 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
951 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
952 log_error("Failed to parse reply.");
957 printf("digraph systemd {\n");
959 dbus_message_iter_recurse(&iter, &sub);
960 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
961 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
963 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
964 log_error("Failed to parse reply.");
969 dbus_message_iter_recurse(&sub, &sub2);
971 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
972 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
973 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
974 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
975 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
976 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
977 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
978 log_error("Failed to parse reply.");
983 if ((r = dot_one(bus, id, unit_path)) < 0)
986 /* printf("\t\"%s\";\n", id); */
987 dbus_message_iter_next(&sub);
992 log_info(" Color legend: black = Requires\n"
993 " dark blue = Requisite\n"
994 " dark grey = Wants\n"
999 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
1000 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
1006 dbus_message_unref(m);
1009 dbus_message_unref(reply);
1011 dbus_error_free(&error);
1016 static int list_jobs(DBusConnection *bus, char **args) {
1017 DBusMessage *m = NULL, *reply = NULL;
1020 DBusMessageIter iter, sub, sub2;
1023 dbus_error_init(&error);
1027 pager_open_if_enabled();
1029 if (!(m = dbus_message_new_method_call(
1030 "org.freedesktop.systemd1",
1031 "/org/freedesktop/systemd1",
1032 "org.freedesktop.systemd1.Manager",
1034 log_error("Could not allocate message.");
1038 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1039 log_error("Failed to issue method call: %s", bus_error_message(&error));
1044 if (!dbus_message_iter_init(reply, &iter) ||
1045 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1046 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
1047 log_error("Failed to parse reply.");
1052 dbus_message_iter_recurse(&iter, &sub);
1055 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
1057 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1058 const char *name, *type, *state, *job_path, *unit_path;
1062 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
1063 log_error("Failed to parse reply.");
1068 dbus_message_iter_recurse(&sub, &sub2);
1070 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
1071 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
1072 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
1073 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
1074 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
1075 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
1076 log_error("Failed to parse reply.");
1081 e = arg_full ? NULL : ellipsize(name, 25, 33);
1082 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
1087 dbus_message_iter_next(&sub);
1091 printf("\n%u jobs listed.\n", k);
1097 dbus_message_unref(m);
1100 dbus_message_unref(reply);
1102 dbus_error_free(&error);
1107 static int load_unit(DBusConnection *bus, char **args) {
1108 DBusMessage *m = NULL;
1113 dbus_error_init(&error);
1118 STRV_FOREACH(name, args+1) {
1121 if (!(m = dbus_message_new_method_call(
1122 "org.freedesktop.systemd1",
1123 "/org/freedesktop/systemd1",
1124 "org.freedesktop.systemd1.Manager",
1126 log_error("Could not allocate message.");
1131 if (!dbus_message_append_args(m,
1132 DBUS_TYPE_STRING, name,
1133 DBUS_TYPE_INVALID)) {
1134 log_error("Could not append arguments to message.");
1139 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1140 log_error("Failed to issue method call: %s", bus_error_message(&error));
1145 dbus_message_unref(m);
1146 dbus_message_unref(reply);
1155 dbus_message_unref(m);
1157 dbus_error_free(&error);
1162 static int cancel_job(DBusConnection *bus, char **args) {
1163 DBusMessage *m = NULL, *reply = NULL;
1168 dbus_error_init(&error);
1173 if (strv_length(args) <= 1)
1174 return daemon_reload(bus, args);
1176 STRV_FOREACH(name, args+1) {
1180 if (!(m = dbus_message_new_method_call(
1181 "org.freedesktop.systemd1",
1182 "/org/freedesktop/systemd1",
1183 "org.freedesktop.systemd1.Manager",
1185 log_error("Could not allocate message.");
1190 if ((r = safe_atou(*name, &id)) < 0) {
1191 log_error("Failed to parse job id: %s", strerror(-r));
1195 assert_cc(sizeof(uint32_t) == sizeof(id));
1196 if (!dbus_message_append_args(m,
1197 DBUS_TYPE_UINT32, &id,
1198 DBUS_TYPE_INVALID)) {
1199 log_error("Could not append arguments to message.");
1204 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1205 log_error("Failed to issue method call: %s", bus_error_message(&error));
1210 if (!dbus_message_get_args(reply, &error,
1211 DBUS_TYPE_OBJECT_PATH, &path,
1212 DBUS_TYPE_INVALID)) {
1213 log_error("Failed to parse reply: %s", bus_error_message(&error));
1218 dbus_message_unref(m);
1219 if (!(m = dbus_message_new_method_call(
1220 "org.freedesktop.systemd1",
1222 "org.freedesktop.systemd1.Job",
1224 log_error("Could not allocate message.");
1229 dbus_message_unref(reply);
1230 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1231 log_error("Failed to issue method call: %s", bus_error_message(&error));
1236 dbus_message_unref(m);
1237 dbus_message_unref(reply);
1245 dbus_message_unref(m);
1248 dbus_message_unref(reply);
1250 dbus_error_free(&error);
1255 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1256 DBusMessage *m = NULL, *reply = NULL;
1257 dbus_bool_t b = FALSE;
1258 DBusMessageIter iter, sub;
1260 *interface = "org.freedesktop.systemd1.Unit",
1261 *property = "NeedDaemonReload",
1264 /* We ignore all errors here, since this is used to show a warning only */
1266 if (!(m = dbus_message_new_method_call(
1267 "org.freedesktop.systemd1",
1268 "/org/freedesktop/systemd1",
1269 "org.freedesktop.systemd1.Manager",
1273 if (!dbus_message_append_args(m,
1274 DBUS_TYPE_STRING, &unit,
1278 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1281 if (!dbus_message_get_args(reply, NULL,
1282 DBUS_TYPE_OBJECT_PATH, &path,
1286 dbus_message_unref(m);
1287 if (!(m = dbus_message_new_method_call(
1288 "org.freedesktop.systemd1",
1290 "org.freedesktop.DBus.Properties",
1294 if (!dbus_message_append_args(m,
1295 DBUS_TYPE_STRING, &interface,
1296 DBUS_TYPE_STRING, &property,
1297 DBUS_TYPE_INVALID)) {
1301 dbus_message_unref(reply);
1302 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1305 if (!dbus_message_iter_init(reply, &iter) ||
1306 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1309 dbus_message_iter_recurse(&iter, &sub);
1311 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1314 dbus_message_iter_get_basic(&sub, &b);
1318 dbus_message_unref(m);
1321 dbus_message_unref(reply);
1326 typedef struct WaitData {
1331 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1339 dbus_error_init(&error);
1341 log_debug("Got D-Bus request: %s.%s() on %s",
1342 dbus_message_get_interface(message),
1343 dbus_message_get_member(message),
1344 dbus_message_get_path(message));
1346 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1347 log_error("Warning! D-Bus connection terminated.");
1348 dbus_connection_close(connection);
1350 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1352 const char *path, *result, *unit;
1353 dbus_bool_t success = true;
1355 if (dbus_message_get_args(message, &error,
1356 DBUS_TYPE_UINT32, &id,
1357 DBUS_TYPE_OBJECT_PATH, &path,
1358 DBUS_TYPE_STRING, &unit,
1359 DBUS_TYPE_STRING, &result,
1360 DBUS_TYPE_INVALID)) {
1363 p = set_remove(d->set, (char*) path);
1367 d->result = strdup(result);
1372 dbus_error_free(&error);
1373 if (dbus_message_get_args(message, &error,
1374 DBUS_TYPE_UINT32, &id,
1375 DBUS_TYPE_OBJECT_PATH, &path,
1376 DBUS_TYPE_STRING, &result,
1377 DBUS_TYPE_INVALID)) {
1380 /* Compatibility with older systemd versions <
1381 * 183 during upgrades. This should be dropped
1383 p = set_remove(d->set, (char*) path);
1387 d->result = strdup(result);
1392 dbus_error_free(&error);
1393 if (dbus_message_get_args(message, &error,
1394 DBUS_TYPE_UINT32, &id,
1395 DBUS_TYPE_OBJECT_PATH, &path,
1396 DBUS_TYPE_BOOLEAN, &success,
1397 DBUS_TYPE_INVALID)) {
1400 /* Compatibility with older systemd versions <
1401 * 19 during upgrades. This should be dropped
1404 p = set_remove(d->set, (char*) path);
1408 d->result = strdup("failed");
1414 log_error("Failed to parse message: %s", bus_error_message(&error));
1418 dbus_error_free(&error);
1419 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1422 static int enable_wait_for_jobs(DBusConnection *bus) {
1430 dbus_error_init(&error);
1431 dbus_bus_add_match(bus,
1433 "sender='org.freedesktop.systemd1',"
1434 "interface='org.freedesktop.systemd1.Manager',"
1435 "member='JobRemoved',"
1436 "path='/org/freedesktop/systemd1'",
1439 if (dbus_error_is_set(&error)) {
1440 log_error("Failed to add match: %s", bus_error_message(&error));
1441 dbus_error_free(&error);
1445 /* This is slightly dirty, since we don't undo the match registrations. */
1449 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1459 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1460 log_error("Failed to add filter.");
1465 while (!set_isempty(s) &&
1466 dbus_connection_read_write_dispatch(bus, -1))
1469 if (!arg_quiet && d.result) {
1470 if (streq(d.result, "timeout"))
1471 log_error("Job timed out.");
1472 else if (streq(d.result, "canceled"))
1473 log_error("Job canceled.");
1474 else if (streq(d.result, "dependency"))
1475 log_error("A dependency job failed. See system journal for details.");
1476 else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
1477 log_error("Job failed. See system journal and 'systemctl status' for details.");
1480 if (streq_ptr(d.result, "timeout"))
1482 else if (streq_ptr(d.result, "canceled"))
1484 else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
1492 /* This is slightly dirty, since we don't undo the filter registration. */
1497 static int start_unit_one(
1498 DBusConnection *bus,
1505 DBusMessage *m = NULL, *reply = NULL;
1514 assert(arg_no_block || s);
1516 if (!(m = dbus_message_new_method_call(
1517 "org.freedesktop.systemd1",
1518 "/org/freedesktop/systemd1",
1519 "org.freedesktop.systemd1.Manager",
1521 log_error("Could not allocate message.");
1526 if (!dbus_message_append_args(m,
1527 DBUS_TYPE_STRING, &name,
1528 DBUS_TYPE_STRING, &mode,
1529 DBUS_TYPE_INVALID)) {
1530 log_error("Could not append arguments to message.");
1535 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1537 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1538 /* There's always a fallback possible for
1539 * legacy actions. */
1544 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.");
1581 dbus_message_unref(m);
1584 dbus_message_unref(reply);
1589 static enum action verb_to_action(const char *verb) {
1590 if (streq(verb, "halt"))
1592 else if (streq(verb, "poweroff"))
1593 return ACTION_POWEROFF;
1594 else if (streq(verb, "reboot"))
1595 return ACTION_REBOOT;
1596 else if (streq(verb, "kexec"))
1597 return ACTION_KEXEC;
1598 else if (streq(verb, "rescue"))
1599 return ACTION_RESCUE;
1600 else if (streq(verb, "emergency"))
1601 return ACTION_EMERGENCY;
1602 else if (streq(verb, "default"))
1603 return ACTION_DEFAULT;
1604 else if (streq(verb, "exit"))
1607 return ACTION_INVALID;
1610 static int start_unit(DBusConnection *bus, char **args) {
1612 static const char * const table[_ACTION_MAX] = {
1613 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1614 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1615 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1616 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1617 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1618 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1619 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1620 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1621 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1622 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1623 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1624 [ACTION_EXIT] = SPECIAL_EXIT_TARGET
1628 const char *method, *mode, *one_name;
1633 dbus_error_init(&error);
1637 ask_password_agent_open_if_enabled();
1639 if (arg_action == ACTION_SYSTEMCTL) {
1641 streq(args[0], "stop") ||
1642 streq(args[0], "condstop") ? "StopUnit" :
1643 streq(args[0], "reload") ? "ReloadUnit" :
1644 streq(args[0], "restart") ? "RestartUnit" :
1646 streq(args[0], "try-restart") ||
1647 streq(args[0], "condrestart") ? "TryRestartUnit" :
1649 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1651 streq(args[0], "reload-or-try-restart") ||
1652 streq(args[0], "condreload") ||
1654 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1658 (streq(args[0], "isolate") ||
1659 streq(args[0], "rescue") ||
1660 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1662 one_name = table[verb_to_action(args[0])];
1665 assert(arg_action < ELEMENTSOF(table));
1666 assert(table[arg_action]);
1668 method = "StartUnit";
1670 mode = (arg_action == ACTION_EMERGENCY ||
1671 arg_action == ACTION_RESCUE ||
1672 arg_action == ACTION_RUNLEVEL2 ||
1673 arg_action == ACTION_RUNLEVEL3 ||
1674 arg_action == ACTION_RUNLEVEL4 ||
1675 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1677 one_name = table[arg_action];
1680 if (!arg_no_block) {
1681 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1682 log_error("Could not watch jobs: %s", strerror(-ret));
1686 if (!(s = set_new(string_hash_func, string_compare_func))) {
1687 log_error("Failed to allocate set.");
1694 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1697 STRV_FOREACH(name, args+1)
1698 if ((r = start_unit_one(bus, method, *name, mode, &error, s)) != 0) {
1699 ret = translate_bus_error_to_exit_status(r, &error);
1700 dbus_error_free(&error);
1705 if ((r = wait_for_jobs(bus, s)) < 0) {
1714 dbus_error_free(&error);
1719 /* Ask systemd-logind, which might grant access to unprivileged users
1720 * through PolicyKit */
1721 static int reboot_with_logind(DBusConnection *bus, enum action a) {
1724 DBusMessage *m = NULL, *reply = NULL;
1726 dbus_bool_t interactive = true;
1729 dbus_error_init(&error);
1731 polkit_agent_open_if_enabled();
1739 case ACTION_POWEROFF:
1740 method = "PowerOff";
1747 m = dbus_message_new_method_call(
1748 "org.freedesktop.login1",
1749 "/org/freedesktop/login1",
1750 "org.freedesktop.login1.Manager",
1753 log_error("Could not allocate message.");
1758 if (!dbus_message_append_args(m,
1759 DBUS_TYPE_BOOLEAN, &interactive,
1760 DBUS_TYPE_INVALID)) {
1761 log_error("Could not append arguments to message.");
1766 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
1768 if (error_is_no_service(&error)) {
1769 log_debug("Failed to issue method call: %s", bus_error_message(&error));
1774 if (dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
1775 log_debug("Failed to issue method call: %s", bus_error_message(&error));
1780 log_info("Failed to issue method call: %s", bus_error_message(&error));
1789 dbus_message_unref(m);
1792 dbus_message_unref(reply);
1794 dbus_error_free(&error);
1802 static int start_special(DBusConnection *bus, char **args) {
1808 a = verb_to_action(args[0]);
1810 if (arg_force >= 2 && geteuid() != 0) {
1811 log_error("Must be root.");
1815 if (arg_force >= 2 &&
1816 (a == ACTION_HALT ||
1817 a == ACTION_POWEROFF ||
1818 a == ACTION_REBOOT))
1821 if (arg_force >= 1 &&
1822 (a == ACTION_HALT ||
1823 a == ACTION_POWEROFF ||
1824 a == ACTION_REBOOT ||
1825 a == ACTION_KEXEC ||
1827 return daemon_reload(bus, args);
1829 /* first try logind, to allow authentication with polkit */
1830 if (geteuid() != 0 &&
1831 (a == ACTION_POWEROFF ||
1832 a == ACTION_REBOOT)) {
1833 r = reboot_with_logind(bus, a);
1838 r = start_unit(bus, args);
1845 static int check_unit(DBusConnection *bus, char **args) {
1846 DBusMessage *m = NULL, *reply = NULL;
1848 *interface = "org.freedesktop.systemd1.Unit",
1849 *property = "ActiveState";
1850 int r = 3; /* According to LSB: "program is not running" */
1857 dbus_error_init(&error);
1859 STRV_FOREACH(name, args+1) {
1860 const char *path = NULL;
1862 DBusMessageIter iter, sub;
1864 if (!(m = dbus_message_new_method_call(
1865 "org.freedesktop.systemd1",
1866 "/org/freedesktop/systemd1",
1867 "org.freedesktop.systemd1.Manager",
1869 log_error("Could not allocate message.");
1874 if (!dbus_message_append_args(m,
1875 DBUS_TYPE_STRING, name,
1876 DBUS_TYPE_INVALID)) {
1877 log_error("Could not append arguments to message.");
1882 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1884 /* Hmm, cannot figure out anything about this unit... */
1888 dbus_error_free(&error);
1889 dbus_message_unref(m);
1894 if (!dbus_message_get_args(reply, &error,
1895 DBUS_TYPE_OBJECT_PATH, &path,
1896 DBUS_TYPE_INVALID)) {
1897 log_error("Failed to parse reply: %s", bus_error_message(&error));
1902 dbus_message_unref(m);
1903 if (!(m = dbus_message_new_method_call(
1904 "org.freedesktop.systemd1",
1906 "org.freedesktop.DBus.Properties",
1908 log_error("Could not allocate message.");
1913 if (!dbus_message_append_args(m,
1914 DBUS_TYPE_STRING, &interface,
1915 DBUS_TYPE_STRING, &property,
1916 DBUS_TYPE_INVALID)) {
1917 log_error("Could not append arguments to message.");
1922 dbus_message_unref(reply);
1923 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1924 log_error("Failed to issue method call: %s", bus_error_message(&error));
1929 if (!dbus_message_iter_init(reply, &iter) ||
1930 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1931 log_error("Failed to parse reply.");
1936 dbus_message_iter_recurse(&iter, &sub);
1938 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1939 log_error("Failed to parse reply.");
1944 dbus_message_iter_get_basic(&sub, &state);
1949 if (streq(state, "active") || streq(state, "reloading"))
1952 dbus_message_unref(m);
1953 dbus_message_unref(reply);
1959 dbus_message_unref(m);
1962 dbus_message_unref(reply);
1964 dbus_error_free(&error);
1969 static int kill_unit(DBusConnection *bus, char **args) {
1970 DBusMessage *m = NULL;
1978 dbus_error_init(&error);
1981 arg_kill_who = "all";
1984 arg_kill_mode = streq(arg_kill_who, "all") ? "control-group" : "process";
1986 STRV_FOREACH(name, args+1) {
1989 if (!(m = dbus_message_new_method_call(
1990 "org.freedesktop.systemd1",
1991 "/org/freedesktop/systemd1",
1992 "org.freedesktop.systemd1.Manager",
1994 log_error("Could not allocate message.");
1999 if (!dbus_message_append_args(m,
2000 DBUS_TYPE_STRING, name,
2001 DBUS_TYPE_STRING, &arg_kill_who,
2002 DBUS_TYPE_STRING, &arg_kill_mode,
2003 DBUS_TYPE_INT32, &arg_signal,
2004 DBUS_TYPE_INVALID)) {
2005 log_error("Could not append arguments to message.");
2010 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2011 log_error("Failed to issue method call: %s", bus_error_message(&error));
2012 dbus_error_free(&error);
2016 dbus_message_unref(m);
2019 dbus_message_unref(reply);
2025 dbus_message_unref(m);
2027 dbus_error_free(&error);
2032 typedef struct ExecStatusInfo {
2040 usec_t start_timestamp;
2041 usec_t exit_timestamp;
2046 LIST_FIELDS(struct ExecStatusInfo, exec);
2049 static void exec_status_info_free(ExecStatusInfo *i) {
2058 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
2059 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
2060 DBusMessageIter sub2, sub3;
2064 int32_t code, status;
2070 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
2073 dbus_message_iter_recurse(sub, &sub2);
2075 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
2078 if (!(i->path = strdup(path)))
2081 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
2082 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
2086 dbus_message_iter_recurse(&sub2, &sub3);
2087 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
2088 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
2089 dbus_message_iter_next(&sub3);
2094 if (!(i->argv = new0(char*, n+1)))
2098 dbus_message_iter_recurse(&sub2, &sub3);
2099 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
2102 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
2103 dbus_message_iter_get_basic(&sub3, &s);
2104 dbus_message_iter_next(&sub3);
2106 if (!(i->argv[n++] = strdup(s)))
2110 if (!dbus_message_iter_next(&sub2) ||
2111 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
2112 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
2113 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
2114 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
2115 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
2116 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
2117 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
2118 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
2122 i->start_timestamp = (usec_t) start_timestamp;
2123 i->exit_timestamp = (usec_t) exit_timestamp;
2124 i->pid = (pid_t) pid;
2131 typedef struct UnitStatusInfo {
2133 const char *load_state;
2134 const char *active_state;
2135 const char *sub_state;
2136 const char *unit_file_state;
2138 const char *description;
2139 const char *following;
2142 const char *default_control_group;
2144 const char *load_error;
2147 usec_t inactive_exit_timestamp;
2148 usec_t inactive_exit_timestamp_monotonic;
2149 usec_t active_enter_timestamp;
2150 usec_t active_exit_timestamp;
2151 usec_t inactive_enter_timestamp;
2153 bool need_daemon_reload;
2158 const char *status_text;
2160 #ifdef HAVE_SYSV_COMPAT
2164 usec_t start_timestamp;
2165 usec_t exit_timestamp;
2167 int exit_code, exit_status;
2169 usec_t condition_timestamp;
2170 bool condition_result;
2173 unsigned n_accepted;
2174 unsigned n_connections;
2178 const char *sysfs_path;
2180 /* Mount, Automount */
2186 LIST_HEAD(ExecStatusInfo, exec);
2189 static void print_status_info(UnitStatusInfo *i) {
2191 const char *on, *off, *ss;
2193 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
2194 char since2[FORMAT_TIMESTAMP_MAX], *s2;
2198 /* This shows pretty information about a unit. See
2199 * print_property() for a low-level property printer */
2201 printf("%s", strna(i->id));
2203 if (i->description && !streq_ptr(i->id, i->description))
2204 printf(" - %s", i->description);
2209 printf("\t Follow: unit currently follows state of %s\n", i->following);
2211 if (streq_ptr(i->load_state, "error")) {
2212 on = ansi_highlight_red(true);
2213 off = ansi_highlight_red(false);
2218 printf("\t Loaded: %s%s%s (Reason: %s)\n", on, strna(i->load_state), off, i->load_error);
2219 else if (i->path && i->unit_file_state)
2220 printf("\t Loaded: %s%s%s (%s; %s)\n", on, strna(i->load_state), off, i->path, i->unit_file_state);
2222 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
2224 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
2226 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
2228 if (streq_ptr(i->active_state, "failed")) {
2229 on = ansi_highlight_red(true);
2230 off = ansi_highlight_red(false);
2231 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
2232 on = ansi_highlight_green(true);
2233 off = ansi_highlight_green(false);
2238 printf("\t Active: %s%s (%s)%s",
2240 strna(i->active_state),
2244 printf("\t Active: %s%s%s",
2246 strna(i->active_state),
2249 if (!isempty(i->result) && !streq(i->result, "success"))
2250 printf(" (Result: %s)", i->result);
2252 timestamp = (streq_ptr(i->active_state, "active") ||
2253 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
2254 (streq_ptr(i->active_state, "inactive") ||
2255 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
2256 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
2257 i->active_exit_timestamp;
2259 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
2260 s2 = format_timestamp(since2, sizeof(since2), timestamp);
2263 printf(" since %s; %s\n", s2, s1);
2265 printf(" since %s\n", s2);
2269 if (!i->condition_result && i->condition_timestamp > 0) {
2270 s1 = format_timestamp_pretty(since1, sizeof(since1), i->condition_timestamp);
2271 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
2274 printf("\t start condition failed at %s; %s\n", s2, s1);
2276 printf("\t start condition failed at %s\n", s2);
2280 printf("\t Device: %s\n", i->sysfs_path);
2282 printf("\t Where: %s\n", i->where);
2284 printf("\t What: %s\n", i->what);
2287 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
2289 LIST_FOREACH(exec, p, i->exec) {
2293 /* Only show exited processes here */
2297 t = strv_join(p->argv, " ");
2298 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
2301 #ifdef HAVE_SYSV_COMPAT
2303 good = is_clean_exit_lsb(p->code, p->status);
2306 good = is_clean_exit(p->code, p->status);
2309 on = ansi_highlight_red(true);
2310 off = ansi_highlight_red(false);
2314 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
2316 if (p->code == CLD_EXITED) {
2319 printf("status=%i", p->status);
2321 #ifdef HAVE_SYSV_COMPAT
2322 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
2324 if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
2329 printf("signal=%s", signal_to_string(p->status));
2331 printf(")%s\n", off);
2333 if (i->main_pid == p->pid &&
2334 i->start_timestamp == p->start_timestamp &&
2335 i->exit_timestamp == p->start_timestamp)
2336 /* Let's not show this twice */
2339 if (p->pid == i->control_pid)
2343 if (i->main_pid > 0 || i->control_pid > 0) {
2346 if (i->main_pid > 0) {
2347 printf("Main PID: %u", (unsigned) i->main_pid);
2351 get_process_comm(i->main_pid, &t);
2356 } else if (i->exit_code > 0) {
2357 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2359 if (i->exit_code == CLD_EXITED) {
2362 printf("status=%i", i->exit_status);
2364 #ifdef HAVE_SYSV_COMPAT
2365 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
2367 if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
2372 printf("signal=%s", signal_to_string(i->exit_status));
2377 if (i->main_pid > 0 && i->control_pid > 0)
2380 if (i->control_pid > 0) {
2383 printf(" Control: %u", (unsigned) i->control_pid);
2385 get_process_comm(i->control_pid, &t);
2396 printf("\t Status: \"%s\"\n", i->status_text);
2398 if (i->default_control_group) {
2401 printf("\t CGroup: %s\n", i->default_control_group);
2403 if (arg_transport != TRANSPORT_SSH) {
2413 if (i->main_pid > 0)
2414 extra[k++] = i->main_pid;
2416 if (i->control_pid > 0)
2417 extra[k++] = i->control_pid;
2419 show_cgroup_and_extra_by_spec(i->default_control_group, "\t\t ", c, false, arg_all, extra, k);
2423 if (i->id && arg_transport != TRANSPORT_SSH) {
2425 show_journal_by_unit(i->id, arg_output, 0, i->inactive_exit_timestamp_monotonic, arg_lines, arg_all, arg_follow);
2428 if (i->need_daemon_reload)
2429 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2430 ansi_highlight_red(true),
2431 ansi_highlight_red(false),
2432 arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
2435 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2441 switch (dbus_message_iter_get_arg_type(iter)) {
2443 case DBUS_TYPE_STRING: {
2446 dbus_message_iter_get_basic(iter, &s);
2449 if (streq(name, "Id"))
2451 else if (streq(name, "LoadState"))
2453 else if (streq(name, "ActiveState"))
2454 i->active_state = s;
2455 else if (streq(name, "SubState"))
2457 else if (streq(name, "Description"))
2459 else if (streq(name, "FragmentPath"))
2461 #ifdef HAVE_SYSV_COMPAT
2462 else if (streq(name, "SysVPath")) {
2467 else if (streq(name, "DefaultControlGroup"))
2468 i->default_control_group = s;
2469 else if (streq(name, "StatusText"))
2471 else if (streq(name, "SysFSPath"))
2473 else if (streq(name, "Where"))
2475 else if (streq(name, "What"))
2477 else if (streq(name, "Following"))
2479 else if (streq(name, "UnitFileState"))
2480 i->unit_file_state = s;
2481 else if (streq(name, "Result"))
2488 case DBUS_TYPE_BOOLEAN: {
2491 dbus_message_iter_get_basic(iter, &b);
2493 if (streq(name, "Accept"))
2495 else if (streq(name, "NeedDaemonReload"))
2496 i->need_daemon_reload = b;
2497 else if (streq(name, "ConditionResult"))
2498 i->condition_result = b;
2503 case DBUS_TYPE_UINT32: {
2506 dbus_message_iter_get_basic(iter, &u);
2508 if (streq(name, "MainPID")) {
2510 i->main_pid = (pid_t) u;
2513 } else if (streq(name, "ControlPID"))
2514 i->control_pid = (pid_t) u;
2515 else if (streq(name, "ExecMainPID")) {
2517 i->main_pid = (pid_t) u;
2518 } else if (streq(name, "NAccepted"))
2520 else if (streq(name, "NConnections"))
2521 i->n_connections = u;
2526 case DBUS_TYPE_INT32: {
2529 dbus_message_iter_get_basic(iter, &j);
2531 if (streq(name, "ExecMainCode"))
2532 i->exit_code = (int) j;
2533 else if (streq(name, "ExecMainStatus"))
2534 i->exit_status = (int) j;
2539 case DBUS_TYPE_UINT64: {
2542 dbus_message_iter_get_basic(iter, &u);
2544 if (streq(name, "ExecMainStartTimestamp"))
2545 i->start_timestamp = (usec_t) u;
2546 else if (streq(name, "ExecMainExitTimestamp"))
2547 i->exit_timestamp = (usec_t) u;
2548 else if (streq(name, "ActiveEnterTimestamp"))
2549 i->active_enter_timestamp = (usec_t) u;
2550 else if (streq(name, "InactiveEnterTimestamp"))
2551 i->inactive_enter_timestamp = (usec_t) u;
2552 else if (streq(name, "InactiveExitTimestamp"))
2553 i->inactive_exit_timestamp = (usec_t) u;
2554 else if (streq(name, "InactiveExitTimestampMonotonic"))
2555 i->inactive_exit_timestamp_monotonic = (usec_t) u;
2556 else if (streq(name, "ActiveExitTimestamp"))
2557 i->active_exit_timestamp = (usec_t) u;
2558 else if (streq(name, "ConditionTimestamp"))
2559 i->condition_timestamp = (usec_t) u;
2564 case DBUS_TYPE_ARRAY: {
2566 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2567 startswith(name, "Exec")) {
2568 DBusMessageIter sub;
2570 dbus_message_iter_recurse(iter, &sub);
2571 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2572 ExecStatusInfo *info;
2575 if (!(info = new0(ExecStatusInfo, 1)))
2578 if (!(info->name = strdup(name))) {
2583 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2588 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2590 dbus_message_iter_next(&sub);
2597 case DBUS_TYPE_STRUCT: {
2599 if (streq(name, "LoadError")) {
2600 DBusMessageIter sub;
2601 const char *n, *message;
2604 dbus_message_iter_recurse(iter, &sub);
2606 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &n, true);
2610 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &message, false);
2614 if (!isempty(message))
2615 i->load_error = message;
2625 static int print_property(const char *name, DBusMessageIter *iter) {
2629 /* This is a low-level property printer, see
2630 * print_status_info() for the nicer output */
2632 if (arg_property && !strv_find(arg_property, name))
2635 switch (dbus_message_iter_get_arg_type(iter)) {
2637 case DBUS_TYPE_STRUCT: {
2638 DBusMessageIter sub;
2639 dbus_message_iter_recurse(iter, &sub);
2641 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2644 dbus_message_iter_get_basic(&sub, &u);
2647 printf("%s=%u\n", name, (unsigned) u);
2649 printf("%s=\n", name);
2652 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2655 dbus_message_iter_get_basic(&sub, &s);
2657 if (arg_all || s[0])
2658 printf("%s=%s\n", name, s);
2661 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "LoadError")) {
2662 const char *a = NULL, *b = NULL;
2664 if (bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &a, true) >= 0)
2665 bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &b, false);
2667 if (arg_all || !isempty(a) || !isempty(b))
2668 printf("%s=%s \"%s\"\n", name, strempty(a), strempty(b));
2676 case DBUS_TYPE_ARRAY:
2678 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
2679 DBusMessageIter sub, sub2;
2681 dbus_message_iter_recurse(iter, &sub);
2682 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2686 dbus_message_iter_recurse(&sub, &sub2);
2688 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
2689 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
2690 printf("EnvironmentFile=%s (ignore_errors=%s)\n", path, yes_no(ignore));
2692 dbus_message_iter_next(&sub);
2697 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2698 DBusMessageIter sub, sub2;
2700 dbus_message_iter_recurse(iter, &sub);
2701 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2702 const char *type, *path;
2704 dbus_message_iter_recurse(&sub, &sub2);
2706 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2707 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2708 printf("%s=%s\n", type, path);
2710 dbus_message_iter_next(&sub);
2715 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2716 DBusMessageIter sub, sub2;
2718 dbus_message_iter_recurse(iter, &sub);
2719 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2721 uint64_t value, next_elapse;
2723 dbus_message_iter_recurse(&sub, &sub2);
2725 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2726 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2727 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2728 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2730 printf("%s={ value=%s ; next_elapse=%s }\n",
2732 format_timespan(timespan1, sizeof(timespan1), value),
2733 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2736 dbus_message_iter_next(&sub);
2741 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "ControlGroupAttributes")) {
2742 DBusMessageIter sub, sub2;
2744 dbus_message_iter_recurse(iter, &sub);
2745 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2746 const char *controller, *attr, *value;
2748 dbus_message_iter_recurse(&sub, &sub2);
2750 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &controller, true) >= 0 &&
2751 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &attr, true) >= 0 &&
2752 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &value, false) >= 0) {
2754 printf("ControlGroupAttribute={ controller=%s ; attribute=%s ; value=\"%s\" }\n",
2760 dbus_message_iter_next(&sub);
2765 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2766 DBusMessageIter sub;
2768 dbus_message_iter_recurse(iter, &sub);
2769 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2770 ExecStatusInfo info;
2773 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2774 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2777 t = strv_join(info.argv, " ");
2779 printf("%s={ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2783 yes_no(info.ignore),
2784 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2785 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2786 (unsigned) info. pid,
2787 sigchld_code_to_string(info.code),
2789 info.code == CLD_EXITED ? "" : "/",
2790 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2796 strv_free(info.argv);
2798 dbus_message_iter_next(&sub);
2807 if (generic_print_property(name, iter, arg_all) > 0)
2811 printf("%s=[unprintable]\n", name);
2816 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2817 DBusMessage *m = NULL, *reply = NULL;
2818 const char *interface = "";
2821 DBusMessageIter iter, sub, sub2, sub3;
2822 UnitStatusInfo info;
2830 dbus_error_init(&error);
2832 if (!(m = dbus_message_new_method_call(
2833 "org.freedesktop.systemd1",
2835 "org.freedesktop.DBus.Properties",
2837 log_error("Could not allocate message.");
2842 if (!dbus_message_append_args(m,
2843 DBUS_TYPE_STRING, &interface,
2844 DBUS_TYPE_INVALID)) {
2845 log_error("Could not append arguments to message.");
2850 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2851 log_error("Failed to issue method call: %s", bus_error_message(&error));
2856 if (!dbus_message_iter_init(reply, &iter) ||
2857 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2858 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2859 log_error("Failed to parse reply.");
2864 dbus_message_iter_recurse(&iter, &sub);
2871 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2874 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2875 log_error("Failed to parse reply.");
2880 dbus_message_iter_recurse(&sub, &sub2);
2882 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2883 log_error("Failed to parse reply.");
2888 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2889 log_error("Failed to parse reply.");
2894 dbus_message_iter_recurse(&sub2, &sub3);
2896 if (show_properties)
2897 r = print_property(name, &sub3);
2899 r = status_property(name, &sub3, &info);
2902 log_error("Failed to parse reply.");
2907 dbus_message_iter_next(&sub);
2912 if (!show_properties)
2913 print_status_info(&info);
2915 if (!streq_ptr(info.active_state, "active") &&
2916 !streq_ptr(info.active_state, "reloading") &&
2917 streq(verb, "status"))
2918 /* According to LSB: "program not running" */
2921 while ((p = info.exec)) {
2922 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2923 exec_status_info_free(p);
2928 dbus_message_unref(m);
2931 dbus_message_unref(reply);
2933 dbus_error_free(&error);
2938 static int show(DBusConnection *bus, char **args) {
2939 DBusMessage *m = NULL, *reply = NULL;
2942 bool show_properties, new_line = false;
2948 dbus_error_init(&error);
2950 show_properties = !streq(args[0], "status");
2952 if (show_properties)
2953 pager_open_if_enabled();
2955 if (show_properties && strv_length(args) <= 1) {
2956 /* If not argument is specified inspect the manager
2959 ret = show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2963 STRV_FOREACH(name, args+1) {
2964 const char *path = NULL;
2967 if (safe_atou32(*name, &id) < 0) {
2969 /* Interpret as unit name */
2971 if (!(m = dbus_message_new_method_call(
2972 "org.freedesktop.systemd1",
2973 "/org/freedesktop/systemd1",
2974 "org.freedesktop.systemd1.Manager",
2976 log_error("Could not allocate message.");
2981 if (!dbus_message_append_args(m,
2982 DBUS_TYPE_STRING, name,
2983 DBUS_TYPE_INVALID)) {
2984 log_error("Could not append arguments to message.");
2989 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2991 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2992 log_error("Failed to issue method call: %s", bus_error_message(&error));
2997 dbus_error_free(&error);
2999 dbus_message_unref(m);
3000 if (!(m = dbus_message_new_method_call(
3001 "org.freedesktop.systemd1",
3002 "/org/freedesktop/systemd1",
3003 "org.freedesktop.systemd1.Manager",
3005 log_error("Could not allocate message.");
3010 if (!dbus_message_append_args(m,
3011 DBUS_TYPE_STRING, name,
3012 DBUS_TYPE_INVALID)) {
3013 log_error("Could not append arguments to message.");
3018 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3019 log_error("Failed to issue method call: %s", bus_error_message(&error));
3021 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
3022 ret = 4; /* According to LSB: "program or service status is unknown" */
3029 } else if (show_properties) {
3031 /* Interpret as job id */
3033 if (!(m = dbus_message_new_method_call(
3034 "org.freedesktop.systemd1",
3035 "/org/freedesktop/systemd1",
3036 "org.freedesktop.systemd1.Manager",
3038 log_error("Could not allocate message.");
3043 if (!dbus_message_append_args(m,
3044 DBUS_TYPE_UINT32, &id,
3045 DBUS_TYPE_INVALID)) {
3046 log_error("Could not append arguments to message.");
3051 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3052 log_error("Failed to issue method call: %s", bus_error_message(&error));
3058 /* Interpret as PID */
3060 if (!(m = dbus_message_new_method_call(
3061 "org.freedesktop.systemd1",
3062 "/org/freedesktop/systemd1",
3063 "org.freedesktop.systemd1.Manager",
3065 log_error("Could not allocate message.");
3070 if (!dbus_message_append_args(m,
3071 DBUS_TYPE_UINT32, &id,
3072 DBUS_TYPE_INVALID)) {
3073 log_error("Could not append arguments to message.");
3078 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3079 log_error("Failed to issue method call: %s", bus_error_message(&error));
3085 if (!dbus_message_get_args(reply, &error,
3086 DBUS_TYPE_OBJECT_PATH, &path,
3087 DBUS_TYPE_INVALID)) {
3088 log_error("Failed to parse reply: %s", bus_error_message(&error));
3093 if ((r = show_one(args[0], bus, path, show_properties, &new_line)) != 0)
3096 dbus_message_unref(m);
3097 dbus_message_unref(reply);
3103 dbus_message_unref(m);
3106 dbus_message_unref(reply);
3108 dbus_error_free(&error);
3113 static int dump(DBusConnection *bus, char **args) {
3114 DBusMessage *m = NULL, *reply = NULL;
3119 dbus_error_init(&error);
3121 pager_open_if_enabled();
3123 if (!(m = dbus_message_new_method_call(
3124 "org.freedesktop.systemd1",
3125 "/org/freedesktop/systemd1",
3126 "org.freedesktop.systemd1.Manager",
3128 log_error("Could not allocate message.");
3132 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3133 log_error("Failed to issue method call: %s", bus_error_message(&error));
3138 if (!dbus_message_get_args(reply, &error,
3139 DBUS_TYPE_STRING, &text,
3140 DBUS_TYPE_INVALID)) {
3141 log_error("Failed to parse reply: %s", bus_error_message(&error));
3146 fputs(text, stdout);
3152 dbus_message_unref(m);
3155 dbus_message_unref(reply);
3157 dbus_error_free(&error);
3162 static int snapshot(DBusConnection *bus, char **args) {
3163 DBusMessage *m = NULL, *reply = NULL;
3166 const char *name = "", *path, *id;
3167 dbus_bool_t cleanup = FALSE;
3168 DBusMessageIter iter, sub;
3170 *interface = "org.freedesktop.systemd1.Unit",
3173 dbus_error_init(&error);
3175 if (!(m = dbus_message_new_method_call(
3176 "org.freedesktop.systemd1",
3177 "/org/freedesktop/systemd1",
3178 "org.freedesktop.systemd1.Manager",
3179 "CreateSnapshot"))) {
3180 log_error("Could not allocate message.");
3184 if (strv_length(args) > 1)
3187 if (!dbus_message_append_args(m,
3188 DBUS_TYPE_STRING, &name,
3189 DBUS_TYPE_BOOLEAN, &cleanup,
3190 DBUS_TYPE_INVALID)) {
3191 log_error("Could not append arguments to message.");
3196 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3197 log_error("Failed to issue method call: %s", bus_error_message(&error));
3202 if (!dbus_message_get_args(reply, &error,
3203 DBUS_TYPE_OBJECT_PATH, &path,
3204 DBUS_TYPE_INVALID)) {
3205 log_error("Failed to parse reply: %s", bus_error_message(&error));
3210 dbus_message_unref(m);
3211 if (!(m = dbus_message_new_method_call(
3212 "org.freedesktop.systemd1",
3214 "org.freedesktop.DBus.Properties",
3216 log_error("Could not allocate message.");
3220 if (!dbus_message_append_args(m,
3221 DBUS_TYPE_STRING, &interface,
3222 DBUS_TYPE_STRING, &property,
3223 DBUS_TYPE_INVALID)) {
3224 log_error("Could not append arguments to message.");
3229 dbus_message_unref(reply);
3230 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3231 log_error("Failed to issue method call: %s", bus_error_message(&error));
3236 if (!dbus_message_iter_init(reply, &iter) ||
3237 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3238 log_error("Failed to parse reply.");
3243 dbus_message_iter_recurse(&iter, &sub);
3245 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3246 log_error("Failed to parse reply.");
3251 dbus_message_iter_get_basic(&sub, &id);
3259 dbus_message_unref(m);
3262 dbus_message_unref(reply);
3264 dbus_error_free(&error);
3269 static int delete_snapshot(DBusConnection *bus, char **args) {
3270 DBusMessage *m = NULL, *reply = NULL;
3278 dbus_error_init(&error);
3280 STRV_FOREACH(name, args+1) {
3281 const char *path = NULL;
3283 if (!(m = dbus_message_new_method_call(
3284 "org.freedesktop.systemd1",
3285 "/org/freedesktop/systemd1",
3286 "org.freedesktop.systemd1.Manager",
3288 log_error("Could not allocate message.");
3293 if (!dbus_message_append_args(m,
3294 DBUS_TYPE_STRING, name,
3295 DBUS_TYPE_INVALID)) {
3296 log_error("Could not append arguments to message.");
3301 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3302 log_error("Failed to issue method call: %s", bus_error_message(&error));
3307 if (!dbus_message_get_args(reply, &error,
3308 DBUS_TYPE_OBJECT_PATH, &path,
3309 DBUS_TYPE_INVALID)) {
3310 log_error("Failed to parse reply: %s", bus_error_message(&error));
3315 dbus_message_unref(m);
3316 if (!(m = dbus_message_new_method_call(
3317 "org.freedesktop.systemd1",
3319 "org.freedesktop.systemd1.Snapshot",
3321 log_error("Could not allocate message.");
3326 dbus_message_unref(reply);
3327 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3328 log_error("Failed to issue method call: %s", bus_error_message(&error));
3333 dbus_message_unref(m);
3334 dbus_message_unref(reply);
3342 dbus_message_unref(m);
3345 dbus_message_unref(reply);
3347 dbus_error_free(&error);
3352 static int daemon_reload(DBusConnection *bus, char **args) {
3353 DBusMessage *m = NULL, *reply = NULL;
3358 dbus_error_init(&error);
3360 if (arg_action == ACTION_RELOAD)
3362 else if (arg_action == ACTION_REEXEC)
3363 method = "Reexecute";
3365 assert(arg_action == ACTION_SYSTEMCTL);
3368 streq(args[0], "clear-jobs") ||
3369 streq(args[0], "cancel") ? "ClearJobs" :
3370 streq(args[0], "daemon-reexec") ? "Reexecute" :
3371 streq(args[0], "reset-failed") ? "ResetFailed" :
3372 streq(args[0], "halt") ? "Halt" :
3373 streq(args[0], "poweroff") ? "PowerOff" :
3374 streq(args[0], "reboot") ? "Reboot" :
3375 streq(args[0], "kexec") ? "KExec" :
3376 streq(args[0], "exit") ? "Exit" :
3377 /* "daemon-reload" */ "Reload";
3380 if (!(m = dbus_message_new_method_call(
3381 "org.freedesktop.systemd1",
3382 "/org/freedesktop/systemd1",
3383 "org.freedesktop.systemd1.Manager",
3385 log_error("Could not allocate message.");
3389 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3391 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3392 /* There's always a fallback possible for
3393 * legacy actions. */
3398 if (streq(method, "Reexecute") && dbus_error_has_name(&error, DBUS_ERROR_NO_REPLY)) {
3399 /* On reexecution, we expect a disconnect, not
3405 log_error("Failed to issue method call: %s", bus_error_message(&error));
3414 dbus_message_unref(m);
3417 dbus_message_unref(reply);
3419 dbus_error_free(&error);
3424 static int reset_failed(DBusConnection *bus, char **args) {
3425 DBusMessage *m = NULL;
3431 dbus_error_init(&error);
3433 if (strv_length(args) <= 1)
3434 return daemon_reload(bus, args);
3436 STRV_FOREACH(name, args+1) {
3439 if (!(m = dbus_message_new_method_call(
3440 "org.freedesktop.systemd1",
3441 "/org/freedesktop/systemd1",
3442 "org.freedesktop.systemd1.Manager",
3443 "ResetFailedUnit"))) {
3444 log_error("Could not allocate message.");
3449 if (!dbus_message_append_args(m,
3450 DBUS_TYPE_STRING, name,
3451 DBUS_TYPE_INVALID)) {
3452 log_error("Could not append arguments to message.");
3457 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3458 log_error("Failed to issue method call: %s", bus_error_message(&error));
3463 dbus_message_unref(m);
3464 dbus_message_unref(reply);
3472 dbus_message_unref(m);
3474 dbus_error_free(&error);
3479 static int show_enviroment(DBusConnection *bus, char **args) {
3480 DBusMessage *m = NULL, *reply = NULL;
3482 DBusMessageIter iter, sub, sub2;
3485 *interface = "org.freedesktop.systemd1.Manager",
3486 *property = "Environment";
3488 dbus_error_init(&error);
3490 pager_open_if_enabled();
3492 if (!(m = dbus_message_new_method_call(
3493 "org.freedesktop.systemd1",
3494 "/org/freedesktop/systemd1",
3495 "org.freedesktop.DBus.Properties",
3497 log_error("Could not allocate message.");
3501 if (!dbus_message_append_args(m,
3502 DBUS_TYPE_STRING, &interface,
3503 DBUS_TYPE_STRING, &property,
3504 DBUS_TYPE_INVALID)) {
3505 log_error("Could not append arguments to message.");
3510 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3511 log_error("Failed to issue method call: %s", bus_error_message(&error));
3516 if (!dbus_message_iter_init(reply, &iter) ||
3517 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3518 log_error("Failed to parse reply.");
3523 dbus_message_iter_recurse(&iter, &sub);
3525 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3526 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3527 log_error("Failed to parse reply.");
3532 dbus_message_iter_recurse(&sub, &sub2);
3534 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3537 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3538 log_error("Failed to parse reply.");
3543 dbus_message_iter_get_basic(&sub2, &text);
3544 printf("%s\n", text);
3546 dbus_message_iter_next(&sub2);
3553 dbus_message_unref(m);
3556 dbus_message_unref(reply);
3558 dbus_error_free(&error);
3563 static int set_environment(DBusConnection *bus, char **args) {
3564 DBusMessage *m = NULL, *reply = NULL;
3568 DBusMessageIter iter, sub;
3571 dbus_error_init(&error);
3573 method = streq(args[0], "set-environment")
3575 : "UnsetEnvironment";
3577 if (!(m = dbus_message_new_method_call(
3578 "org.freedesktop.systemd1",
3579 "/org/freedesktop/systemd1",
3580 "org.freedesktop.systemd1.Manager",
3583 log_error("Could not allocate message.");
3587 dbus_message_iter_init_append(m, &iter);
3589 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3590 log_error("Could not append arguments to message.");
3595 STRV_FOREACH(name, args+1)
3596 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, name)) {
3597 log_error("Could not append arguments to message.");
3602 if (!dbus_message_iter_close_container(&iter, &sub)) {
3603 log_error("Could not append arguments to message.");
3608 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3609 log_error("Failed to issue method call: %s", bus_error_message(&error));
3618 dbus_message_unref(m);
3621 dbus_message_unref(reply);
3623 dbus_error_free(&error);
3628 static int enable_sysv_units(char **args) {
3631 #if defined (HAVE_SYSV_COMPAT) && (defined(TARGET_FEDORA) || defined(TARGET_MANDRIVA) || defined(TARGET_SUSE) || defined(TARGET_MEEGO) || defined(TARGET_ALTLINUX) || defined(TARGET_MAGEIA))
3632 const char *verb = args[0];
3633 unsigned f = 1, t = 1;
3636 if (arg_scope != UNIT_FILE_SYSTEM)
3639 if (!streq(verb, "enable") &&
3640 !streq(verb, "disable") &&
3641 !streq(verb, "is-enabled"))
3644 /* Processes all SysV units, and reshuffles the array so that
3645 * afterwards only the native units remain */
3648 r = lookup_paths_init(&paths, MANAGER_SYSTEM, false);
3654 for (f = 1; args[f]; f++) {
3657 bool found_native = false, found_sysv;
3659 const char *argv[6] = { "/sbin/chkconfig", NULL, NULL, NULL, NULL };
3660 char **k, *l, *q = NULL;
3667 if (!endswith(name, ".service"))
3670 if (path_is_absolute(name))
3673 STRV_FOREACH(k, paths.unit_path) {
3676 if (!isempty(arg_root))
3677 asprintf(&p, "%s/%s/%s", arg_root, *k, name);
3679 asprintf(&p, "%s/%s", *k, name);
3682 log_error("No memory");
3687 found_native = access(p, F_OK) >= 0;
3698 if (!isempty(arg_root))
3699 asprintf(&p, "%s/" SYSTEM_SYSVINIT_PATH "/%s", arg_root, name);
3701 asprintf(&p, SYSTEM_SYSVINIT_PATH "/%s", name);
3703 log_error("No memory");
3708 p[strlen(p) - sizeof(".service") + 1] = 0;
3709 found_sysv = access(p, F_OK) >= 0;
3716 /* Mark this entry, so that we don't try enabling it as native unit */
3717 args[f] = (char*) "";
3719 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", name);
3721 if (!isempty(arg_root))
3722 argv[c++] = q = strappend("--root=", arg_root);
3724 argv[c++] = file_name_from_path(p);
3726 streq(verb, "enable") ? "on" :
3727 streq(verb, "disable") ? "off" : "--level=5";
3730 l = strv_join((char**)argv, " ");
3732 log_error("No memory.");
3739 log_info("Executing %s", l);
3744 log_error("Failed to fork: %m");
3749 } else if (pid == 0) {
3752 execv(argv[0], (char**) argv);
3753 _exit(EXIT_FAILURE);
3759 j = wait_for_terminate(pid, &status);
3761 log_error("Failed to wait for child: %s", strerror(-r));
3766 if (status.si_code == CLD_EXITED) {
3767 if (streq(verb, "is-enabled")) {
3768 if (status.si_status == 0) {
3777 } else if (status.si_status != 0) {
3788 lookup_paths_free(&paths);
3790 /* Drop all SysV units */
3791 for (f = 1, t = 1; args[f]; f++) {
3793 if (isempty(args[f]))
3796 args[t++] = args[f];
3805 static int enable_unit(DBusConnection *bus, char **args) {
3806 const char *verb = args[0];
3807 UnitFileChange *changes = NULL;
3808 unsigned n_changes = 0, i;
3809 int carries_install_info = -1;
3810 DBusMessage *m = NULL, *reply = NULL;
3814 r = enable_sysv_units(args);
3821 dbus_error_init(&error);
3823 if (!bus || avoid_bus()) {
3824 if (streq(verb, "enable")) {
3825 r = unit_file_enable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3826 carries_install_info = r;
3827 } else if (streq(verb, "disable"))
3828 r = unit_file_disable(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
3829 else if (streq(verb, "reenable")) {
3830 r = unit_file_reenable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3831 carries_install_info = r;
3832 } else if (streq(verb, "link"))
3833 r = unit_file_link(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3834 else if (streq(verb, "preset")) {
3835 r = unit_file_preset(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3836 carries_install_info = r;
3837 } else if (streq(verb, "mask"))
3838 r = unit_file_mask(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3839 else if (streq(verb, "unmask"))
3840 r = unit_file_unmask(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
3842 assert_not_reached("Unknown verb");
3845 log_error("Operation failed: %s", strerror(-r));
3850 for (i = 0; i < n_changes; i++) {
3851 if (changes[i].type == UNIT_FILE_SYMLINK)
3852 log_info("ln -s '%s' '%s'", changes[i].source, changes[i].path);
3854 log_info("rm '%s'", changes[i].path);
3860 bool send_force = true, expect_carries_install_info = false;
3862 DBusMessageIter iter, sub, sub2;
3864 if (streq(verb, "enable")) {
3865 method = "EnableUnitFiles";
3866 expect_carries_install_info = true;
3867 } else if (streq(verb, "disable")) {
3868 method = "DisableUnitFiles";
3870 } else if (streq(verb, "reenable")) {
3871 method = "ReenableUnitFiles";
3872 expect_carries_install_info = true;
3873 } else if (streq(verb, "link"))
3874 method = "LinkUnitFiles";
3875 else if (streq(verb, "preset")) {
3876 method = "PresetUnitFiles";
3877 expect_carries_install_info = true;
3878 } else if (streq(verb, "mask"))
3879 method = "MaskUnitFiles";
3880 else if (streq(verb, "unmask")) {
3881 method = "UnmaskUnitFiles";
3884 assert_not_reached("Unknown verb");
3886 m = dbus_message_new_method_call(
3887 "org.freedesktop.systemd1",
3888 "/org/freedesktop/systemd1",
3889 "org.freedesktop.systemd1.Manager",
3892 log_error("Out of memory");
3897 dbus_message_iter_init_append(m, &iter);
3899 r = bus_append_strv_iter(&iter, args+1);
3901 log_error("Failed to append unit files.");
3906 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &a)) {
3907 log_error("Failed to append runtime boolean.");
3915 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b)) {
3916 log_error("Failed to append force boolean.");
3922 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3924 log_error("Failed to issue method call: %s", bus_error_message(&error));
3929 if (!dbus_message_iter_init(reply, &iter)) {
3930 log_error("Failed to initialize iterator.");
3934 if (expect_carries_install_info) {
3935 r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_BOOLEAN, &b, true);
3937 log_error("Failed to parse reply.");
3941 carries_install_info = b;
3944 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
3945 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
3946 log_error("Failed to parse reply.");
3951 dbus_message_iter_recurse(&iter, &sub);
3952 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
3953 const char *type, *path, *source;
3955 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
3956 log_error("Failed to parse reply.");
3961 dbus_message_iter_recurse(&sub, &sub2);
3963 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
3964 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0 ||
3965 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &source, false) < 0) {
3966 log_error("Failed to parse reply.");
3972 if (streq(type, "symlink"))
3973 log_info("ln -s '%s' '%s'", source, path);
3975 log_info("rm '%s'", path);
3978 dbus_message_iter_next(&sub);
3981 /* Try to reload if enabeld */
3983 r = daemon_reload(bus, args);
3986 if (carries_install_info == 0)
3987 log_warning("Warning: unit files do not carry install information. No operation executed.");
3991 dbus_message_unref(m);
3994 dbus_message_unref(reply);
3996 unit_file_changes_free(changes, n_changes);
3998 dbus_error_free(&error);
4002 static int unit_is_enabled(DBusConnection *bus, char **args) {
4005 DBusMessage *m = NULL, *reply = NULL;
4009 dbus_error_init(&error);
4011 r = enable_sysv_units(args);
4017 if (!bus || avoid_bus()) {
4019 STRV_FOREACH(name, args+1) {
4020 UnitFileState state;
4022 state = unit_file_get_state(arg_scope, arg_root, *name);
4028 if (state == UNIT_FILE_ENABLED ||
4029 state == UNIT_FILE_ENABLED_RUNTIME ||
4030 state == UNIT_FILE_STATIC)
4034 puts(unit_file_state_to_string(state));
4038 STRV_FOREACH(name, args+1) {
4041 m = dbus_message_new_method_call(
4042 "org.freedesktop.systemd1",
4043 "/org/freedesktop/systemd1",
4044 "org.freedesktop.systemd1.Manager",
4045 "GetUnitFileState");
4047 log_error("Out of memory");
4052 if (!dbus_message_append_args(m,
4053 DBUS_TYPE_STRING, name,
4054 DBUS_TYPE_INVALID)) {
4055 log_error("Could not append arguments to message.");
4060 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
4062 log_error("Failed to issue method call: %s", bus_error_message(&error));
4067 if (!dbus_message_get_args(reply, &error,
4068 DBUS_TYPE_STRING, &s,
4069 DBUS_TYPE_INVALID)) {
4070 log_error("Failed to parse reply: %s", bus_error_message(&error));
4075 dbus_message_unref(m);
4076 dbus_message_unref(reply);
4079 if (streq(s, "enabled") ||
4080 streq(s, "enabled-runtime") ||
4089 r = enabled ? 0 : 1;
4093 dbus_message_unref(m);
4096 dbus_message_unref(reply);
4098 dbus_error_free(&error);
4102 static int systemctl_help(void) {
4104 pager_open_if_enabled();
4106 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4107 "Query or send control commands to the systemd manager.\n\n"
4108 " -h --help Show this help\n"
4109 " --version Show package version\n"
4110 " -t --type=TYPE List only units of a particular type\n"
4111 " -p --property=NAME Show only properties by this name\n"
4112 " -a --all Show all units/properties, including dead/empty ones\n"
4113 " --failed Show only failed units\n"
4114 " --full Don't ellipsize unit names on output\n"
4115 " --fail When queueing a new job, fail if conflicting jobs are\n"
4117 " --ignore-dependencies\n"
4118 " When queueing a new job, ignore all its dependencies\n"
4119 " --kill-who=WHO Who to send signal to\n"
4120 " -s --signal=SIGNAL Which signal to send\n"
4121 " -H --host=[USER@]HOST\n"
4122 " Show information for remote host\n"
4123 " -P --privileged Acquire privileges before execution\n"
4124 " -q --quiet Suppress output\n"
4125 " --no-block Do not wait until operation finished\n"
4126 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4127 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4129 " --no-legend Do not print a legend (column headers and hints)\n"
4130 " --no-pager Do not pipe output into a pager\n"
4131 " --no-ask-password\n"
4132 " Do not ask for system passwords\n"
4133 " --order When generating graph for dot, show only order\n"
4134 " --require When generating graph for dot, show only requirement\n"
4135 " --system Connect to system manager\n"
4136 " --user Connect to user service manager\n"
4137 " --global Enable/disable unit files globally\n"
4138 " -f --force When enabling unit files, override existing symlinks\n"
4139 " When shutting down, execute action immediately\n"
4140 " --root=PATH Enable unit files in the specified root directory\n"
4141 " --runtime Enable unit files only temporarily until next reboot\n"
4142 " -n --lines=INTEGER Journal entries to show\n"
4143 " --follow Follow journal\n"
4144 " -o --output=STRING Change journal output mode (short, short-monotonic,\n"
4145 " verbose, export, json, cat)\n\n"
4147 " list-units List loaded units\n"
4148 " start [NAME...] Start (activate) one or more units\n"
4149 " stop [NAME...] Stop (deactivate) one or more units\n"
4150 " reload [NAME...] Reload one or more units\n"
4151 " restart [NAME...] Start or restart one or more units\n"
4152 " try-restart [NAME...] Restart one or more units if active\n"
4153 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4154 " otherwise start or restart\n"
4155 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4156 " otherwise restart if active\n"
4157 " isolate [NAME] Start one unit and stop all others\n"
4158 " kill [NAME...] Send signal to processes of a unit\n"
4159 " is-active [NAME...] Check whether units are active\n"
4160 " status [NAME...|PID...] Show runtime status of one or more units\n"
4161 " show [NAME...|JOB...] Show properties of one or more\n"
4162 " units/jobs or the manager\n"
4163 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4165 " load [NAME...] Load one or more units\n\n"
4166 "Unit File Commands:\n"
4167 " list-unit-files List installed unit files\n"
4168 " enable [NAME...] Enable one or more unit files\n"
4169 " disable [NAME...] Disable one or more unit files\n"
4170 " reenable [NAME...] Reenable one or more unit files\n"
4171 " preset [NAME...] Enable/disable one or more unit files\n"
4172 " based on preset configuration\n"
4173 " mask [NAME...] Mask one or more units\n"
4174 " unmask [NAME...] Unmask one or more units\n"
4175 " link [PATH...] Link one or more units files into\n"
4176 " the search path\n"
4177 " is-enabled [NAME...] Check whether unit files are enabled\n\n"
4179 " list-jobs List jobs\n"
4180 " cancel [JOB...] Cancel all, one, or more jobs\n\n"
4181 "Status Commands:\n"
4182 " dump Dump server status\n"
4183 " dot Dump dependency graph for dot(1)\n\n"
4184 "Snapshot Commands:\n"
4185 " snapshot [NAME] Create a snapshot\n"
4186 " delete [NAME...] Remove one or more snapshots\n\n"
4187 "Environment Commands:\n"
4188 " show-environment Dump environment\n"
4189 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4190 " unset-environment [NAME...] Unset one or more environment variables\n\n"
4191 "Manager Lifecycle Commands:\n"
4192 " daemon-reload Reload systemd manager configuration\n"
4193 " daemon-reexec Reexecute systemd manager\n\n"
4194 "System Commands:\n"
4195 " default Enter system default mode\n"
4196 " rescue Enter system rescue mode\n"
4197 " emergency Enter system emergency mode\n"
4198 " halt Shut down and halt the system\n"
4199 " poweroff Shut down and power-off the system\n"
4200 " reboot Shut down and reboot the system\n"
4201 " kexec Shut down and reboot the system with kexec\n"
4202 " exit Ask for user instance termination\n",
4203 program_invocation_short_name);
4208 static int halt_help(void) {
4210 printf("%s [OPTIONS...]\n\n"
4211 "%s the system.\n\n"
4212 " --help Show this help\n"
4213 " --halt Halt the machine\n"
4214 " -p --poweroff Switch off the machine\n"
4215 " --reboot Reboot the machine\n"
4216 " -f --force Force immediate halt/power-off/reboot\n"
4217 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4218 " -d --no-wtmp Don't write wtmp record\n"
4219 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4220 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4221 program_invocation_short_name,
4222 arg_action == ACTION_REBOOT ? "Reboot" :
4223 arg_action == ACTION_POWEROFF ? "Power off" :
4229 static int shutdown_help(void) {
4231 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4232 "Shut down the system.\n\n"
4233 " --help Show this help\n"
4234 " -H --halt Halt the machine\n"
4235 " -P --poweroff Power-off the machine\n"
4236 " -r --reboot Reboot the machine\n"
4237 " -h Equivalent to --poweroff, overriden by --halt\n"
4238 " -k Don't halt/power-off/reboot, just send warnings\n"
4239 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4240 " -c Cancel a pending shutdown\n",
4241 program_invocation_short_name);
4246 static int telinit_help(void) {
4248 printf("%s [OPTIONS...] {COMMAND}\n\n"
4249 "Send control commands to the init daemon.\n\n"
4250 " --help Show this help\n"
4251 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4253 " 0 Power-off the machine\n"
4254 " 6 Reboot the machine\n"
4255 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4256 " 1, s, S Enter rescue mode\n"
4257 " q, Q Reload init daemon configuration\n"
4258 " u, U Reexecute init daemon\n",
4259 program_invocation_short_name);
4264 static int runlevel_help(void) {
4266 printf("%s [OPTIONS...]\n\n"
4267 "Prints the previous and current runlevel of the init system.\n\n"
4268 " --help Show this help\n",
4269 program_invocation_short_name);
4274 static int systemctl_parse_argv(int argc, char *argv[]) {
4278 ARG_IGNORE_DEPENDENCIES,
4294 ARG_NO_ASK_PASSWORD,
4301 static const struct option options[] = {
4302 { "help", no_argument, NULL, 'h' },
4303 { "version", no_argument, NULL, ARG_VERSION },
4304 { "type", required_argument, NULL, 't' },
4305 { "property", required_argument, NULL, 'p' },
4306 { "all", no_argument, NULL, 'a' },
4307 { "failed", no_argument, NULL, ARG_FAILED },
4308 { "full", no_argument, NULL, ARG_FULL },
4309 { "fail", no_argument, NULL, ARG_FAIL },
4310 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4311 { "user", no_argument, NULL, ARG_USER },
4312 { "system", no_argument, NULL, ARG_SYSTEM },
4313 { "global", no_argument, NULL, ARG_GLOBAL },
4314 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4315 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
4316 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4317 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4318 { "quiet", no_argument, NULL, 'q' },
4319 { "order", no_argument, NULL, ARG_ORDER },
4320 { "require", no_argument, NULL, ARG_REQUIRE },
4321 { "root", required_argument, NULL, ARG_ROOT },
4322 { "force", no_argument, NULL, ARG_FORCE },
4323 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4324 { "kill-mode", required_argument, NULL, ARG_KILL_MODE }, /* undocumented on purpose */
4325 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4326 { "signal", required_argument, NULL, 's' },
4327 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4328 { "host", required_argument, NULL, 'H' },
4329 { "privileged",no_argument, NULL, 'P' },
4330 { "runtime", no_argument, NULL, ARG_RUNTIME },
4331 { "lines", required_argument, NULL, 'n' },
4332 { "follow", no_argument, NULL, ARG_FOLLOW },
4333 { "output", required_argument, NULL, 'o' },
4334 { NULL, 0, NULL, 0 }
4342 while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:Pn:o:", options, NULL)) >= 0) {
4351 puts(PACKAGE_STRING);
4353 puts(SYSTEMD_FEATURES);
4363 if (!(l = strv_append(arg_property, optarg)))
4366 strv_free(arg_property);
4369 /* If the user asked for a particular
4370 * property, show it to him, even if it is
4381 arg_job_mode = "fail";
4384 case ARG_IGNORE_DEPENDENCIES:
4385 arg_job_mode = "ignore-dependencies";
4389 arg_scope = UNIT_FILE_USER;
4393 arg_scope = UNIT_FILE_SYSTEM;
4397 arg_scope = UNIT_FILE_GLOBAL;
4401 arg_no_block = true;
4405 arg_no_legend = true;
4409 arg_no_pager = true;
4417 arg_dot = DOT_ORDER;
4421 arg_dot = DOT_REQUIRE;
4449 /* -f is short for both --follow and --force! */
4455 arg_no_reload = true;
4459 arg_kill_who = optarg;
4463 arg_kill_mode = optarg;
4467 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4468 log_error("Failed to parse signal string %s.", optarg);
4473 case ARG_NO_ASK_PASSWORD:
4474 arg_ask_password = false;
4478 arg_transport = TRANSPORT_POLKIT;
4482 arg_transport = TRANSPORT_SSH;
4491 if (safe_atou(optarg, &arg_lines) < 0) {
4492 log_error("Failed to parse lines '%s'", optarg);
4498 arg_output = output_mode_from_string(optarg);
4499 if (arg_output < 0) {
4500 log_error("Unknown output '%s'.", optarg);
4509 log_error("Unknown option code %c", c);
4514 if (arg_transport != TRANSPORT_NORMAL && arg_scope != UNIT_FILE_SYSTEM) {
4515 log_error("Cannot access user instance remotely.");
4522 static int halt_parse_argv(int argc, char *argv[]) {
4531 static const struct option options[] = {
4532 { "help", no_argument, NULL, ARG_HELP },
4533 { "halt", no_argument, NULL, ARG_HALT },
4534 { "poweroff", no_argument, NULL, 'p' },
4535 { "reboot", no_argument, NULL, ARG_REBOOT },
4536 { "force", no_argument, NULL, 'f' },
4537 { "wtmp-only", no_argument, NULL, 'w' },
4538 { "no-wtmp", no_argument, NULL, 'd' },
4539 { "no-sync", no_argument, NULL, 'n' },
4540 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4541 { NULL, 0, NULL, 0 }
4549 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4550 if (runlevel == '0' || runlevel == '6')
4553 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4561 arg_action = ACTION_HALT;
4565 if (arg_action != ACTION_REBOOT)
4566 arg_action = ACTION_POWEROFF;
4570 arg_action = ACTION_REBOOT;
4595 /* Compatibility nops */
4602 log_error("Unknown option code %c", c);
4607 if (optind < argc) {
4608 log_error("Too many arguments.");
4615 static int parse_time_spec(const char *t, usec_t *_u) {
4619 if (streq(t, "now"))
4621 else if (!strchr(t, ':')) {
4624 if (safe_atou64(t, &u) < 0)
4627 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4636 hour = strtol(t, &e, 10);
4637 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4640 minute = strtol(e+1, &e, 10);
4641 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4644 n = now(CLOCK_REALTIME);
4645 s = (time_t) (n / USEC_PER_SEC);
4648 assert_se(localtime_r(&s, &tm));
4650 tm.tm_hour = (int) hour;
4651 tm.tm_min = (int) minute;
4654 assert_se(s = mktime(&tm));
4656 *_u = (usec_t) s * USEC_PER_SEC;
4659 *_u += USEC_PER_DAY;
4665 static int shutdown_parse_argv(int argc, char *argv[]) {
4672 static const struct option options[] = {
4673 { "help", no_argument, NULL, ARG_HELP },
4674 { "halt", no_argument, NULL, 'H' },
4675 { "poweroff", no_argument, NULL, 'P' },
4676 { "reboot", no_argument, NULL, 'r' },
4677 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
4678 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4679 { NULL, 0, NULL, 0 }
4687 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4695 arg_action = ACTION_HALT;
4699 arg_action = ACTION_POWEROFF;
4704 arg_action = ACTION_KEXEC;
4706 arg_action = ACTION_REBOOT;
4710 arg_action = ACTION_KEXEC;
4714 if (arg_action != ACTION_HALT)
4715 arg_action = ACTION_POWEROFF;
4728 /* Compatibility nops */
4732 arg_action = ACTION_CANCEL_SHUTDOWN;
4739 log_error("Unknown option code %c", c);
4744 if (argc > optind) {
4745 r = parse_time_spec(argv[optind], &arg_when);
4747 log_error("Failed to parse time specification: %s", argv[optind]);
4751 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4753 /* We skip the time argument */
4754 if (argc > optind + 1)
4755 arg_wall = argv + optind + 1;
4762 static int telinit_parse_argv(int argc, char *argv[]) {
4769 static const struct option options[] = {
4770 { "help", no_argument, NULL, ARG_HELP },
4771 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4772 { NULL, 0, NULL, 0 }
4775 static const struct {
4779 { '0', ACTION_POWEROFF },
4780 { '6', ACTION_REBOOT },
4781 { '1', ACTION_RESCUE },
4782 { '2', ACTION_RUNLEVEL2 },
4783 { '3', ACTION_RUNLEVEL3 },
4784 { '4', ACTION_RUNLEVEL4 },
4785 { '5', ACTION_RUNLEVEL5 },
4786 { 's', ACTION_RESCUE },
4787 { 'S', ACTION_RESCUE },
4788 { 'q', ACTION_RELOAD },
4789 { 'Q', ACTION_RELOAD },
4790 { 'u', ACTION_REEXEC },
4791 { 'U', ACTION_REEXEC }
4800 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4815 log_error("Unknown option code %c", c);
4820 if (optind >= argc) {
4825 if (optind + 1 < argc) {
4826 log_error("Too many arguments.");
4830 if (strlen(argv[optind]) != 1) {
4831 log_error("Expected single character argument.");
4835 for (i = 0; i < ELEMENTSOF(table); i++)
4836 if (table[i].from == argv[optind][0])
4839 if (i >= ELEMENTSOF(table)) {
4840 log_error("Unknown command %s.", argv[optind]);
4844 arg_action = table[i].to;
4851 static int runlevel_parse_argv(int argc, char *argv[]) {
4857 static const struct option options[] = {
4858 { "help", no_argument, NULL, ARG_HELP },
4859 { NULL, 0, NULL, 0 }
4867 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4878 log_error("Unknown option code %c", c);
4883 if (optind < argc) {
4884 log_error("Too many arguments.");
4891 static int parse_argv(int argc, char *argv[]) {
4895 if (program_invocation_short_name) {
4897 if (strstr(program_invocation_short_name, "halt")) {
4898 arg_action = ACTION_HALT;
4899 return halt_parse_argv(argc, argv);
4900 } else if (strstr(program_invocation_short_name, "poweroff")) {
4901 arg_action = ACTION_POWEROFF;
4902 return halt_parse_argv(argc, argv);
4903 } else if (strstr(program_invocation_short_name, "reboot")) {
4905 arg_action = ACTION_KEXEC;
4907 arg_action = ACTION_REBOOT;
4908 return halt_parse_argv(argc, argv);
4909 } else if (strstr(program_invocation_short_name, "shutdown")) {
4910 arg_action = ACTION_POWEROFF;
4911 return shutdown_parse_argv(argc, argv);
4912 } else if (strstr(program_invocation_short_name, "init")) {
4914 if (sd_booted() > 0) {
4915 arg_action = ACTION_INVALID;
4916 return telinit_parse_argv(argc, argv);
4918 /* Hmm, so some other init system is
4919 * running, we need to forward this
4920 * request to it. For now we simply
4921 * guess that it is Upstart. */
4923 execv("/lib/upstart/telinit", argv);
4925 log_error("Couldn't find an alternative telinit implementation to spawn.");
4929 } else if (strstr(program_invocation_short_name, "runlevel")) {
4930 arg_action = ACTION_RUNLEVEL;
4931 return runlevel_parse_argv(argc, argv);
4935 arg_action = ACTION_SYSTEMCTL;
4936 return systemctl_parse_argv(argc, argv);
4939 static int action_to_runlevel(void) {
4941 static const char table[_ACTION_MAX] = {
4942 [ACTION_HALT] = '0',
4943 [ACTION_POWEROFF] = '0',
4944 [ACTION_REBOOT] = '6',
4945 [ACTION_RUNLEVEL2] = '2',
4946 [ACTION_RUNLEVEL3] = '3',
4947 [ACTION_RUNLEVEL4] = '4',
4948 [ACTION_RUNLEVEL5] = '5',
4949 [ACTION_RESCUE] = '1'
4952 assert(arg_action < _ACTION_MAX);
4954 return table[arg_action];
4957 static int talk_upstart(void) {
4958 DBusMessage *m = NULL, *reply = NULL;
4960 int previous, rl, r;
4962 env1_buf[] = "RUNLEVEL=X",
4963 env2_buf[] = "PREVLEVEL=X";
4964 char *env1 = env1_buf, *env2 = env2_buf;
4965 const char *emit = "runlevel";
4966 dbus_bool_t b_false = FALSE;
4967 DBusMessageIter iter, sub;
4968 DBusConnection *bus;
4970 dbus_error_init(&error);
4972 if (!(rl = action_to_runlevel()))
4975 if (utmp_get_runlevel(&previous, NULL) < 0)
4978 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4979 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4984 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4989 if ((r = bus_check_peercred(bus)) < 0) {
4990 log_error("Failed to verify owner of bus.");
4994 if (!(m = dbus_message_new_method_call(
4995 "com.ubuntu.Upstart",
4996 "/com/ubuntu/Upstart",
4997 "com.ubuntu.Upstart0_6",
5000 log_error("Could not allocate message.");
5005 dbus_message_iter_init_append(m, &iter);
5007 env1_buf[sizeof(env1_buf)-2] = rl;
5008 env2_buf[sizeof(env2_buf)-2] = previous;
5010 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5011 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5012 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5013 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5014 !dbus_message_iter_close_container(&iter, &sub) ||
5015 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5016 log_error("Could not append arguments to message.");
5021 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5023 if (error_is_no_service(&error)) {
5028 log_error("Failed to issue method call: %s", bus_error_message(&error));
5037 dbus_message_unref(m);
5040 dbus_message_unref(reply);
5043 dbus_connection_flush(bus);
5044 dbus_connection_close(bus);
5045 dbus_connection_unref(bus);
5048 dbus_error_free(&error);
5053 static int talk_initctl(void) {
5054 struct init_request request;
5058 if (!(rl = action_to_runlevel()))
5062 request.magic = INIT_MAGIC;
5063 request.sleeptime = 0;
5064 request.cmd = INIT_CMD_RUNLVL;
5065 request.runlevel = rl;
5067 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5069 if (errno == ENOENT)
5072 log_error("Failed to open "INIT_FIFO": %m");
5077 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5078 close_nointr_nofail(fd);
5081 log_error("Failed to write to "INIT_FIFO": %m");
5082 return errno ? -errno : -EIO;
5088 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5090 static const struct {
5098 int (* const dispatch)(DBusConnection *bus, char **args);
5100 { "list-units", LESS, 1, list_units },
5101 { "list-unit-files", EQUAL, 1, list_unit_files },
5102 { "list-jobs", EQUAL, 1, list_jobs },
5103 { "clear-jobs", EQUAL, 1, daemon_reload },
5104 { "load", MORE, 2, load_unit },
5105 { "cancel", MORE, 2, cancel_job },
5106 { "start", MORE, 2, start_unit },
5107 { "stop", MORE, 2, start_unit },
5108 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5109 { "reload", MORE, 2, start_unit },
5110 { "restart", MORE, 2, start_unit },
5111 { "try-restart", MORE, 2, start_unit },
5112 { "reload-or-restart", MORE, 2, start_unit },
5113 { "reload-or-try-restart", MORE, 2, start_unit },
5114 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5115 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5116 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5117 { "isolate", EQUAL, 2, start_unit },
5118 { "kill", MORE, 2, kill_unit },
5119 { "is-active", MORE, 2, check_unit },
5120 { "check", MORE, 2, check_unit },
5121 { "show", MORE, 1, show },
5122 { "status", MORE, 2, show },
5123 { "dump", EQUAL, 1, dump },
5124 { "dot", EQUAL, 1, dot },
5125 { "snapshot", LESS, 2, snapshot },
5126 { "delete", MORE, 2, delete_snapshot },
5127 { "daemon-reload", EQUAL, 1, daemon_reload },
5128 { "daemon-reexec", EQUAL, 1, daemon_reload },
5129 { "show-environment", EQUAL, 1, show_enviroment },
5130 { "set-environment", MORE, 2, set_environment },
5131 { "unset-environment", MORE, 2, set_environment },
5132 { "halt", EQUAL, 1, start_special },
5133 { "poweroff", EQUAL, 1, start_special },
5134 { "reboot", EQUAL, 1, start_special },
5135 { "kexec", EQUAL, 1, start_special },
5136 { "default", EQUAL, 1, start_special },
5137 { "rescue", EQUAL, 1, start_special },
5138 { "emergency", EQUAL, 1, start_special },
5139 { "exit", EQUAL, 1, start_special },
5140 { "reset-failed", MORE, 1, reset_failed },
5141 { "enable", MORE, 2, enable_unit },
5142 { "disable", MORE, 2, enable_unit },
5143 { "is-enabled", MORE, 2, unit_is_enabled },
5144 { "reenable", MORE, 2, enable_unit },
5145 { "preset", MORE, 2, enable_unit },
5146 { "mask", MORE, 2, enable_unit },
5147 { "unmask", MORE, 2, enable_unit },
5148 { "link", MORE, 2, enable_unit }
5158 left = argc - optind;
5161 /* Special rule: no arguments means "list-units" */
5164 if (streq(argv[optind], "help")) {
5169 for (i = 0; i < ELEMENTSOF(verbs); i++)
5170 if (streq(argv[optind], verbs[i].verb))
5173 if (i >= ELEMENTSOF(verbs)) {
5174 log_error("Unknown operation %s", argv[optind]);
5179 switch (verbs[i].argc_cmp) {
5182 if (left != verbs[i].argc) {
5183 log_error("Invalid number of arguments.");
5190 if (left < verbs[i].argc) {
5191 log_error("Too few arguments.");
5198 if (left > verbs[i].argc) {
5199 log_error("Too many arguments.");
5206 assert_not_reached("Unknown comparison operator.");
5209 /* Require a bus connection for all operations but
5211 if (!streq(verbs[i].verb, "enable") &&
5212 !streq(verbs[i].verb, "disable") &&
5213 !streq(verbs[i].verb, "is-enabled") &&
5214 !streq(verbs[i].verb, "list-unit-files") &&
5215 !streq(verbs[i].verb, "reenable") &&
5216 !streq(verbs[i].verb, "preset") &&
5217 !streq(verbs[i].verb, "mask") &&
5218 !streq(verbs[i].verb, "unmask") &&
5219 !streq(verbs[i].verb, "link")) {
5221 if (running_in_chroot() > 0) {
5222 log_info("Running in chroot, ignoring request.");
5226 if (((!streq(verbs[i].verb, "reboot") &&
5227 !streq(verbs[i].verb, "halt") &&
5228 !streq(verbs[i].verb, "reboot")) || arg_force <= 0) && !bus) {
5229 log_error("Failed to get D-Bus connection: %s",
5230 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5236 if (!bus && !avoid_bus()) {
5237 log_error("Failed to get D-Bus connection: %s",
5238 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5243 return verbs[i].dispatch(bus, argv + optind);
5246 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
5248 struct msghdr msghdr;
5249 struct iovec iovec[2];
5250 union sockaddr_union sockaddr;
5251 struct sd_shutdown_command c;
5253 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
5260 c.dry_run = dry_run;
5264 sockaddr.sa.sa_family = AF_UNIX;
5265 strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5268 msghdr.msg_name = &sockaddr;
5269 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5272 iovec[0].iov_base = (char*) &c;
5273 iovec[0].iov_len = offsetof(struct sd_shutdown_command, wall_message);
5275 if (isempty(message))
5276 msghdr.msg_iovlen = 1;
5278 iovec[1].iov_base = (char*) message;
5279 iovec[1].iov_len = strlen(message);
5280 msghdr.msg_iovlen = 2;
5282 msghdr.msg_iov = iovec;
5284 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5285 close_nointr_nofail(fd);
5289 close_nointr_nofail(fd);
5293 static int reload_with_fallback(DBusConnection *bus) {
5296 /* First, try systemd via D-Bus. */
5297 if (daemon_reload(bus, NULL) >= 0)
5301 /* Nothing else worked, so let's try signals */
5302 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5304 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5305 log_error("kill() failed: %m");
5312 static int start_with_fallback(DBusConnection *bus) {
5315 /* First, try systemd via D-Bus. */
5316 if (start_unit(bus, NULL) >= 0)
5320 /* Hmm, talking to systemd via D-Bus didn't work. Then
5321 * let's try to talk to Upstart via D-Bus. */
5322 if (talk_upstart() > 0)
5325 /* Nothing else worked, so let's try
5327 if (talk_initctl() > 0)
5330 log_error("Failed to talk to init daemon.");
5334 warn_wall(arg_action);
5338 static void halt_now(enum action a) {
5340 /* Make sure C-A-D is handled by the kernel from this
5342 reboot(RB_ENABLE_CAD);
5347 log_info("Halting.");
5348 reboot(RB_HALT_SYSTEM);
5351 case ACTION_POWEROFF:
5352 log_info("Powering off.");
5353 reboot(RB_POWER_OFF);
5357 log_info("Rebooting.");
5358 reboot(RB_AUTOBOOT);
5362 assert_not_reached("Unknown halt action.");
5365 assert_not_reached("Uh? This shouldn't happen.");
5368 static int halt_main(DBusConnection *bus) {
5371 if (geteuid() != 0) {
5372 /* Try logind if we are a normal user and no special
5373 * mode applies. Maybe PolicyKit allows us to shutdown
5376 if (arg_when <= 0 &&
5379 (arg_action == ACTION_POWEROFF ||
5380 arg_action == ACTION_REBOOT)) {
5381 r = reboot_with_logind(bus, arg_action);
5386 log_error("Must be root.");
5393 m = strv_join(arg_wall, " ");
5394 r = send_shutdownd(arg_when,
5395 arg_action == ACTION_HALT ? 'H' :
5396 arg_action == ACTION_POWEROFF ? 'P' :
5397 arg_action == ACTION_KEXEC ? 'K' :
5405 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5407 char date[FORMAT_TIMESTAMP_MAX];
5409 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5410 format_timestamp(date, sizeof(date), arg_when));
5415 if (!arg_dry && !arg_force)
5416 return start_with_fallback(bus);
5419 if (sd_booted() > 0)
5420 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5422 r = utmp_put_shutdown();
5424 log_warning("Failed to write utmp record: %s", strerror(-r));
5434 halt_now(arg_action);
5435 /* We should never reach this. */
5439 static int runlevel_main(void) {
5440 int r, runlevel, previous;
5442 r = utmp_get_runlevel(&runlevel, &previous);
5449 previous <= 0 ? 'N' : previous,
5450 runlevel <= 0 ? 'N' : runlevel);
5455 int main(int argc, char*argv[]) {
5456 int r, retval = EXIT_FAILURE;
5457 DBusConnection *bus = NULL;
5460 dbus_error_init(&error);
5462 log_parse_environment();
5465 r = parse_argv(argc, argv);
5469 retval = EXIT_SUCCESS;
5473 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5474 * let's shortcut this */
5475 if (arg_action == ACTION_RUNLEVEL) {
5476 r = runlevel_main();
5477 retval = r < 0 ? EXIT_FAILURE : r;
5481 if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5482 log_info("Running in chroot, ignoring request.");
5488 if (arg_transport == TRANSPORT_NORMAL)
5489 bus_connect(arg_scope == UNIT_FILE_SYSTEM ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, &bus, &private_bus, &error);
5490 else if (arg_transport == TRANSPORT_POLKIT) {
5491 bus_connect_system_polkit(&bus, &error);
5492 private_bus = false;
5493 } else if (arg_transport == TRANSPORT_SSH) {
5494 bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5495 private_bus = false;
5497 assert_not_reached("Uh, invalid transport...");
5500 switch (arg_action) {
5502 case ACTION_SYSTEMCTL:
5503 r = systemctl_main(bus, argc, argv, &error);
5507 case ACTION_POWEROFF:
5513 case ACTION_RUNLEVEL2:
5514 case ACTION_RUNLEVEL3:
5515 case ACTION_RUNLEVEL4:
5516 case ACTION_RUNLEVEL5:
5518 case ACTION_EMERGENCY:
5519 case ACTION_DEFAULT:
5520 r = start_with_fallback(bus);
5525 r = reload_with_fallback(bus);
5528 case ACTION_CANCEL_SHUTDOWN:
5529 r = send_shutdownd(0, 0, false, false, NULL);
5532 case ACTION_INVALID:
5533 case ACTION_RUNLEVEL:
5535 assert_not_reached("Unknown action");
5538 retval = r < 0 ? EXIT_FAILURE : r;
5542 dbus_connection_flush(bus);
5543 dbus_connection_close(bus);
5544 dbus_connection_unref(bus);
5547 dbus_error_free(&error);
5551 strv_free(arg_property);
5554 ask_password_agent_close();
5555 polkit_agent_close();