1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <sys/reboot.h>
28 #include <sys/ioctl.h>
32 #include <sys/socket.h>
35 #include <sys/prctl.h>
36 #include <dbus/dbus.h>
38 #include <systemd/sd-daemon.h>
39 #include <systemd/sd-shutdown.h>
45 #include "utmp-wtmp.h"
48 #include "path-util.h"
50 #include "dbus-common.h"
51 #include "cgroup-show.h"
52 #include "cgroup-util.h"
54 #include "path-lookup.h"
55 #include "conf-parser.h"
56 #include "exit-status.h"
57 #include "bus-errors.h"
59 #include "unit-name.h"
61 #include "spawn-ask-password-agent.h"
62 #include "spawn-polkit-agent.h"
64 #include "logs-show.h"
65 #include "path-util.h"
67 static const char *arg_type = NULL;
68 static const char *arg_load_state = NULL;
69 static char **arg_property = NULL;
70 static bool arg_all = false;
71 static const char *arg_job_mode = "replace";
72 static UnitFileScope arg_scope = UNIT_FILE_SYSTEM;
73 static bool arg_no_block = false;
74 static bool arg_no_legend = false;
75 static bool arg_no_pager = false;
76 static bool arg_no_wtmp = false;
77 static bool arg_no_sync = false;
78 static bool arg_no_wall = false;
79 static bool arg_no_reload = false;
80 static bool arg_dry = false;
81 static bool arg_quiet = false;
82 static bool arg_full = false;
83 static int arg_force = 0;
84 static bool arg_ask_password = true;
85 static bool arg_failed = false;
86 static bool arg_runtime = false;
87 static char **arg_wall = NULL;
88 static const char *arg_kill_who = NULL;
89 static int arg_signal = SIGTERM;
90 static const char *arg_root = NULL;
91 static usec_t arg_when = 0;
112 ACTION_CANCEL_SHUTDOWN,
114 } arg_action = ACTION_SYSTEMCTL;
120 static enum transport {
124 } arg_transport = TRANSPORT_NORMAL;
125 static const char *arg_host = NULL;
126 static bool arg_follow = false;
127 static unsigned arg_lines = 10;
128 static OutputMode arg_output = OUTPUT_SHORT;
130 static bool private_bus = false;
132 static int daemon_reload(DBusConnection *bus, char **args);
133 static void halt_now(enum action a);
135 static bool on_tty(void) {
138 /* Note that this is invoked relatively early, before we start
139 * the pager. That means the value we return reflects whether
140 * we originally were started on a tty, not if we currently
141 * are. But this is intended, since we want colour and so on
142 * when run in our own pager. */
144 if (_unlikely_(t < 0))
145 t = isatty(STDOUT_FILENO) > 0;
150 static void pager_open_if_enabled(void) {
152 /* Cache result before we open the pager */
161 static void ask_password_agent_open_if_enabled(void) {
163 /* Open the password agent as a child process if necessary */
165 if (!arg_ask_password)
168 if (arg_scope != UNIT_FILE_SYSTEM)
171 ask_password_agent_open();
175 static void polkit_agent_open_if_enabled(void) {
177 /* Open the polkit agent as a child process if necessary */
179 if (!arg_ask_password)
182 if (arg_scope != UNIT_FILE_SYSTEM)
189 static const char *ansi_highlight_red(bool b) {
194 return b ? ANSI_HIGHLIGHT_RED_ON : ANSI_HIGHLIGHT_OFF;
197 static const char *ansi_highlight_green(bool b) {
202 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
205 static bool error_is_no_service(const DBusError *error) {
208 if (!dbus_error_is_set(error))
211 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
214 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
217 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
220 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
223 if (!dbus_error_is_set(error))
226 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
227 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
228 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
229 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
230 return EXIT_NOPERMISSION;
232 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
233 return EXIT_NOTINSTALLED;
235 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
236 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
237 return EXIT_NOTIMPLEMENTED;
239 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
240 return EXIT_NOTCONFIGURED;
248 static void warn_wall(enum action a) {
249 static const char *table[_ACTION_MAX] = {
250 [ACTION_HALT] = "The system is going down for system halt NOW!",
251 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
252 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
253 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
254 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
255 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!",
256 [ACTION_CANCEL_SHUTDOWN] = "The system shutdown has been cancelled NOW!"
265 p = strv_join(arg_wall, " ");
267 log_error("Failed to join strings.");
283 utmp_wall(table[a], NULL);
286 static bool avoid_bus(void) {
288 if (running_in_chroot() > 0)
291 if (sd_booted() <= 0)
294 if (!isempty(arg_root))
297 if (arg_scope == UNIT_FILE_GLOBAL)
305 const char *description;
306 const char *load_state;
307 const char *active_state;
308 const char *sub_state;
309 const char *following;
310 const char *unit_path;
312 const char *job_type;
313 const char *job_path;
316 static int compare_unit_info(const void *a, const void *b) {
318 const struct unit_info *u = a, *v = b;
320 d1 = strrchr(u->id, '.');
321 d2 = strrchr(v->id, '.');
326 if ((r = strcasecmp(d1, d2)) != 0)
330 return strcasecmp(u->id, v->id);
333 static bool output_show_unit(const struct unit_info *u) {
337 return streq(u->active_state, "failed");
339 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
340 streq(dot+1, arg_type))) &&
341 (!arg_load_state || streq(u->load_state, arg_load_state)) &&
342 (arg_all || !(streq(u->active_state, "inactive")
343 || u->following[0]) || u->job_id > 0);
346 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
347 unsigned id_len, max_id_len, active_len, sub_len, job_len, desc_len, n_shown = 0;
348 const struct unit_info *u;
350 max_id_len = sizeof("UNIT")-1;
351 active_len = sizeof("ACTIVE")-1;
352 sub_len = sizeof("SUB")-1;
353 job_len = sizeof("JOB")-1;
356 for (u = unit_infos; u < unit_infos + c; u++) {
357 if (!output_show_unit(u))
360 max_id_len = MAX(max_id_len, strlen(u->id));
361 active_len = MAX(active_len, strlen(u->active_state));
362 sub_len = MAX(sub_len, strlen(u->sub_state));
364 job_len = MAX(job_len, strlen(u->job_type));
369 id_len = MIN(max_id_len, 25);
370 basic_len = 5 + id_len + 6 + active_len + sub_len + job_len;
371 if (basic_len < (unsigned) columns()) {
372 unsigned extra_len, incr;
373 extra_len = columns() - basic_len;
374 /* Either UNIT already got 25, or is fully satisfied.
375 * Grant up to 25 to DESC now. */
376 incr = MIN(extra_len, 25);
379 /* split the remaining space between UNIT and DESC,
380 * but do not give UNIT more than it needs. */
382 incr = MIN(extra_len / 2, max_id_len - id_len);
384 desc_len += extra_len - incr;
390 if (!arg_no_legend) {
391 printf("%-*s %-6s %-*s %-*s %-*s ", id_len, "UNIT", "LOAD",
392 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
393 if (!arg_full && arg_no_pager)
394 printf("%.*s\n", desc_len, "DESCRIPTION");
396 printf("%s\n", "DESCRIPTION");
399 for (u = unit_infos; u < unit_infos + c; u++) {
401 const char *on_loaded, *off_loaded;
402 const char *on_active, *off_active;
404 if (!output_show_unit(u))
409 if (streq(u->load_state, "error")) {
410 on_loaded = ansi_highlight_red(true);
411 off_loaded = ansi_highlight_red(false);
413 on_loaded = off_loaded = "";
415 if (streq(u->active_state, "failed")) {
416 on_active = ansi_highlight_red(true);
417 off_active = ansi_highlight_red(false);
419 on_active = off_active = "";
421 e = arg_full ? NULL : ellipsize(u->id, id_len, 33);
423 printf("%-*s %s%-6s%s %s%-*s %-*s%s %-*s ",
424 id_len, e ? e : u->id,
425 on_loaded, u->load_state, off_loaded,
426 on_active, active_len, u->active_state,
427 sub_len, u->sub_state, off_active,
428 job_len, u->job_id ? u->job_type : "");
429 if (!arg_full && arg_no_pager)
430 printf("%.*s\n", desc_len, u->description);
432 printf("%s\n", u->description);
437 if (!arg_no_legend) {
438 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
439 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
440 "SUB = The low-level unit activation state, values depend on unit type.\n"
441 "JOB = Pending job for the unit.\n");
444 printf("\n%u units listed.\n", n_shown);
446 printf("\n%u units listed. Pass --all to see inactive units, too.\n", n_shown);
450 static int list_units(DBusConnection *bus, char **args) {
451 DBusMessage *m = NULL, *reply = NULL;
454 DBusMessageIter iter, sub, sub2;
455 unsigned c = 0, n_units = 0;
456 struct unit_info *unit_infos = NULL;
458 dbus_error_init(&error);
462 pager_open_if_enabled();
464 if (!(m = dbus_message_new_method_call(
465 "org.freedesktop.systemd1",
466 "/org/freedesktop/systemd1",
467 "org.freedesktop.systemd1.Manager",
469 log_error("Could not allocate message.");
473 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
474 log_error("Failed to issue method call: %s", bus_error_message(&error));
479 if (!dbus_message_iter_init(reply, &iter) ||
480 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
481 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
482 log_error("Failed to parse reply.");
487 dbus_message_iter_recurse(&iter, &sub);
489 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
492 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
493 log_error("Failed to parse reply.");
501 n_units = MAX(2*c, 16);
502 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
505 log_error("Failed to allocate unit array.");
515 dbus_message_iter_recurse(&sub, &sub2);
517 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
518 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
519 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
520 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
521 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
522 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
523 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
524 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
525 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
526 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
527 log_error("Failed to parse reply.");
532 dbus_message_iter_next(&sub);
537 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
538 output_units_list(unit_infos, c);
545 dbus_message_unref(m);
548 dbus_message_unref(reply);
552 dbus_error_free(&error);
557 static int compare_unit_file_list(const void *a, const void *b) {
559 const UnitFileList *u = a, *v = b;
561 d1 = strrchr(u->path, '.');
562 d2 = strrchr(v->path, '.');
567 r = strcasecmp(d1, d2);
572 return strcasecmp(path_get_file_name(u->path), path_get_file_name(v->path));
575 static bool output_show_unit_file(const UnitFileList *u) {
578 return !arg_type || ((dot = strrchr(u->path, '.')) && streq(dot+1, arg_type));
581 static void output_unit_file_list(const UnitFileList *units, unsigned c) {
582 unsigned max_id_len, id_cols, state_cols, n_shown = 0;
583 const UnitFileList *u;
585 max_id_len = sizeof("UNIT FILE")-1;
586 state_cols = sizeof("STATE")-1;
587 for (u = units; u < units + c; u++) {
588 if (!output_show_unit_file(u))
591 max_id_len = MAX(max_id_len, strlen(path_get_file_name(u->path)));
592 state_cols = MAX(state_cols, strlen(unit_file_state_to_string(u->state)));
597 id_cols = MIN(max_id_len, 25);
598 basic_cols = 1 + id_cols + state_cols;
599 if (basic_cols < (unsigned) columns())
600 id_cols += MIN(columns() - basic_cols, max_id_len - id_cols);
602 id_cols = max_id_len;
605 printf("%-*s %-*s\n", id_cols, "UNIT FILE", state_cols, "STATE");
607 for (u = units; u < units + c; u++) {
609 const char *on, *off;
612 if (!output_show_unit_file(u))
617 if (u->state == UNIT_FILE_MASKED ||
618 u->state == UNIT_FILE_MASKED_RUNTIME ||
619 u->state == UNIT_FILE_DISABLED) {
620 on = ansi_highlight_red(true);
621 off = ansi_highlight_red(false);
622 } else if (u->state == UNIT_FILE_ENABLED) {
623 on = ansi_highlight_green(true);
624 off = ansi_highlight_green(false);
628 id = path_get_file_name(u->path);
630 e = arg_full ? NULL : ellipsize(id, id_cols, 33);
632 printf("%-*s %s%-*s%s\n",
634 on, state_cols, unit_file_state_to_string(u->state), off);
640 printf("\n%u unit files listed.\n", n_shown);
643 static int list_unit_files(DBusConnection *bus, char **args) {
644 DBusMessage *m = NULL, *reply = NULL;
647 DBusMessageIter iter, sub, sub2;
648 unsigned c = 0, n_units = 0;
649 UnitFileList *units = NULL;
651 dbus_error_init(&error);
653 pager_open_if_enabled();
660 h = hashmap_new(string_hash_func, string_compare_func);
664 r = unit_file_get_list(arg_scope, arg_root, h);
666 unit_file_list_free(h);
667 log_error("Failed to get unit file list: %s", strerror(-r));
671 n_units = hashmap_size(h);
672 units = new(UnitFileList, n_units);
674 unit_file_list_free(h);
678 HASHMAP_FOREACH(u, h, i) {
679 memcpy(units + c++, u, sizeof(UnitFileList));
687 m = dbus_message_new_method_call(
688 "org.freedesktop.systemd1",
689 "/org/freedesktop/systemd1",
690 "org.freedesktop.systemd1.Manager",
693 log_error("Could not allocate message.");
697 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
699 log_error("Failed to issue method call: %s", bus_error_message(&error));
704 if (!dbus_message_iter_init(reply, &iter) ||
705 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
706 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
707 log_error("Failed to parse reply.");
712 dbus_message_iter_recurse(&iter, &sub);
714 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
718 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
719 log_error("Failed to parse reply.");
727 n_units = MAX(2*c, 16);
728 w = realloc(units, sizeof(struct UnitFileList) * n_units);
731 log_error("Failed to allocate unit array.");
741 dbus_message_iter_recurse(&sub, &sub2);
743 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->path, true) < 0 ||
744 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, false) < 0) {
745 log_error("Failed to parse reply.");
750 u->state = unit_file_state_from_string(state);
752 dbus_message_iter_next(&sub);
758 qsort(units, c, sizeof(UnitFileList), compare_unit_file_list);
759 output_unit_file_list(units, c);
766 dbus_message_unref(m);
769 dbus_message_unref(reply);
773 dbus_error_free(&error);
778 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
779 static const char * const colors[] = {
780 "Requires", "[color=\"black\"]",
781 "RequiresOverridable", "[color=\"black\"]",
782 "Requisite", "[color=\"darkblue\"]",
783 "RequisiteOverridable", "[color=\"darkblue\"]",
784 "Wants", "[color=\"grey66\"]",
785 "Conflicts", "[color=\"red\"]",
786 "ConflictedBy", "[color=\"red\"]",
787 "After", "[color=\"green\"]"
790 const char *c = NULL;
797 for (i = 0; i < ELEMENTSOF(colors); i += 2)
798 if (streq(colors[i], prop)) {
806 if (arg_dot != DOT_ALL)
807 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
810 switch (dbus_message_iter_get_arg_type(iter)) {
812 case DBUS_TYPE_ARRAY:
814 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
817 dbus_message_iter_recurse(iter, &sub);
819 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
822 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
823 dbus_message_iter_get_basic(&sub, &s);
824 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
826 dbus_message_iter_next(&sub);
836 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
837 DBusMessage *m = NULL, *reply = NULL;
838 const char *interface = "org.freedesktop.systemd1.Unit";
841 DBusMessageIter iter, sub, sub2, sub3;
846 dbus_error_init(&error);
848 if (!(m = dbus_message_new_method_call(
849 "org.freedesktop.systemd1",
851 "org.freedesktop.DBus.Properties",
853 log_error("Could not allocate message.");
858 if (!dbus_message_append_args(m,
859 DBUS_TYPE_STRING, &interface,
860 DBUS_TYPE_INVALID)) {
861 log_error("Could not append arguments to message.");
866 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
867 log_error("Failed to issue method call: %s", bus_error_message(&error));
872 if (!dbus_message_iter_init(reply, &iter) ||
873 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
874 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
875 log_error("Failed to parse reply.");
880 dbus_message_iter_recurse(&iter, &sub);
882 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
885 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
886 log_error("Failed to parse reply.");
891 dbus_message_iter_recurse(&sub, &sub2);
893 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
894 log_error("Failed to parse reply.");
899 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
900 log_error("Failed to parse reply.");
905 dbus_message_iter_recurse(&sub2, &sub3);
907 if (dot_one_property(name, prop, &sub3)) {
908 log_error("Failed to parse reply.");
913 dbus_message_iter_next(&sub);
920 dbus_message_unref(m);
923 dbus_message_unref(reply);
925 dbus_error_free(&error);
930 static int dot(DBusConnection *bus, char **args) {
931 DBusMessage *m = NULL, *reply = NULL;
934 DBusMessageIter iter, sub, sub2;
936 dbus_error_init(&error);
940 if (!(m = dbus_message_new_method_call(
941 "org.freedesktop.systemd1",
942 "/org/freedesktop/systemd1",
943 "org.freedesktop.systemd1.Manager",
945 log_error("Could not allocate message.");
949 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
950 log_error("Failed to issue method call: %s", bus_error_message(&error));
955 if (!dbus_message_iter_init(reply, &iter) ||
956 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
957 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
958 log_error("Failed to parse reply.");
963 printf("digraph systemd {\n");
965 dbus_message_iter_recurse(&iter, &sub);
966 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
967 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
969 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
970 log_error("Failed to parse reply.");
975 dbus_message_iter_recurse(&sub, &sub2);
977 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
978 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
979 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
980 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
981 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
982 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
983 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
984 log_error("Failed to parse reply.");
989 if ((r = dot_one(bus, id, unit_path)) < 0)
992 /* printf("\t\"%s\";\n", id); */
993 dbus_message_iter_next(&sub);
998 log_info(" Color legend: black = Requires\n"
999 " dark blue = Requisite\n"
1000 " dark grey = Wants\n"
1001 " red = Conflicts\n"
1002 " green = After\n");
1005 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
1006 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
1012 dbus_message_unref(m);
1015 dbus_message_unref(reply);
1017 dbus_error_free(&error);
1022 static int list_jobs(DBusConnection *bus, char **args) {
1023 DBusMessage *m = NULL, *reply = NULL;
1026 DBusMessageIter iter, sub, sub2;
1029 dbus_error_init(&error);
1033 pager_open_if_enabled();
1035 if (!(m = dbus_message_new_method_call(
1036 "org.freedesktop.systemd1",
1037 "/org/freedesktop/systemd1",
1038 "org.freedesktop.systemd1.Manager",
1040 log_error("Could not allocate message.");
1044 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1045 log_error("Failed to issue method call: %s", bus_error_message(&error));
1050 if (!dbus_message_iter_init(reply, &iter) ||
1051 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1052 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
1053 log_error("Failed to parse reply.");
1058 dbus_message_iter_recurse(&iter, &sub);
1061 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
1063 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1064 const char *name, *type, *state, *job_path, *unit_path;
1068 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
1069 log_error("Failed to parse reply.");
1074 dbus_message_iter_recurse(&sub, &sub2);
1076 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
1077 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
1078 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
1079 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
1080 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
1081 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
1082 log_error("Failed to parse reply.");
1087 e = arg_full ? NULL : ellipsize(name, 25, 33);
1088 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
1093 dbus_message_iter_next(&sub);
1097 printf("\n%u jobs listed.\n", k);
1103 dbus_message_unref(m);
1106 dbus_message_unref(reply);
1108 dbus_error_free(&error);
1113 static int load_unit(DBusConnection *bus, char **args) {
1114 DBusMessage *m = NULL;
1119 dbus_error_init(&error);
1124 STRV_FOREACH(name, args+1) {
1129 if (!(m = dbus_message_new_method_call(
1130 "org.freedesktop.systemd1",
1131 "/org/freedesktop/systemd1",
1132 "org.freedesktop.systemd1.Manager",
1134 log_error("Could not allocate message.");
1139 n = unit_name_mangle(*name);
1140 b = dbus_message_append_args(m,
1141 DBUS_TYPE_STRING, n ? &n : name,
1145 log_error("Could not append arguments to message.");
1150 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
1152 log_error("Failed to issue method call: %s", bus_error_message(&error));
1157 dbus_message_unref(m);
1158 dbus_message_unref(reply);
1167 dbus_message_unref(m);
1169 dbus_error_free(&error);
1174 static int cancel_job(DBusConnection *bus, char **args) {
1175 DBusMessage *m = NULL, *reply = NULL;
1180 dbus_error_init(&error);
1185 if (strv_length(args) <= 1)
1186 return daemon_reload(bus, args);
1188 STRV_FOREACH(name, args+1) {
1192 if (!(m = dbus_message_new_method_call(
1193 "org.freedesktop.systemd1",
1194 "/org/freedesktop/systemd1",
1195 "org.freedesktop.systemd1.Manager",
1197 log_error("Could not allocate message.");
1202 if ((r = safe_atou(*name, &id)) < 0) {
1203 log_error("Failed to parse job id: %s", strerror(-r));
1207 assert_cc(sizeof(uint32_t) == sizeof(id));
1208 if (!dbus_message_append_args(m,
1209 DBUS_TYPE_UINT32, &id,
1210 DBUS_TYPE_INVALID)) {
1211 log_error("Could not append arguments to message.");
1216 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1217 log_error("Failed to issue method call: %s", bus_error_message(&error));
1222 if (!dbus_message_get_args(reply, &error,
1223 DBUS_TYPE_OBJECT_PATH, &path,
1224 DBUS_TYPE_INVALID)) {
1225 log_error("Failed to parse reply: %s", bus_error_message(&error));
1230 dbus_message_unref(m);
1231 if (!(m = dbus_message_new_method_call(
1232 "org.freedesktop.systemd1",
1234 "org.freedesktop.systemd1.Job",
1236 log_error("Could not allocate message.");
1241 dbus_message_unref(reply);
1242 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1243 log_error("Failed to issue method call: %s", bus_error_message(&error));
1248 dbus_message_unref(m);
1249 dbus_message_unref(reply);
1257 dbus_message_unref(m);
1260 dbus_message_unref(reply);
1262 dbus_error_free(&error);
1267 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1268 DBusMessage *m = NULL, *reply = NULL;
1269 dbus_bool_t b = FALSE;
1270 DBusMessageIter iter, sub;
1272 *interface = "org.freedesktop.systemd1.Unit",
1273 *property = "NeedDaemonReload",
1278 /* We ignore all errors here, since this is used to show a warning only */
1280 m = dbus_message_new_method_call(
1281 "org.freedesktop.systemd1",
1282 "/org/freedesktop/systemd1",
1283 "org.freedesktop.systemd1.Manager",
1288 n = unit_name_mangle(unit);
1289 k = dbus_message_append_args(m,
1290 DBUS_TYPE_STRING, n ? (const char**) &n : &unit,
1296 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL);
1300 if (!dbus_message_get_args(reply, NULL,
1301 DBUS_TYPE_OBJECT_PATH, &path,
1305 dbus_message_unref(m);
1306 m = dbus_message_new_method_call(
1307 "org.freedesktop.systemd1",
1309 "org.freedesktop.DBus.Properties",
1314 if (!dbus_message_append_args(m,
1315 DBUS_TYPE_STRING, &interface,
1316 DBUS_TYPE_STRING, &property,
1317 DBUS_TYPE_INVALID)) {
1321 dbus_message_unref(reply);
1322 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL);
1326 if (!dbus_message_iter_init(reply, &iter) ||
1327 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1330 dbus_message_iter_recurse(&iter, &sub);
1332 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1335 dbus_message_iter_get_basic(&sub, &b);
1339 dbus_message_unref(m);
1342 dbus_message_unref(reply);
1347 typedef struct WaitData {
1352 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1360 dbus_error_init(&error);
1362 log_debug("Got D-Bus request: %s.%s() on %s",
1363 dbus_message_get_interface(message),
1364 dbus_message_get_member(message),
1365 dbus_message_get_path(message));
1367 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1368 log_error("Warning! D-Bus connection terminated.");
1369 dbus_connection_close(connection);
1371 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1373 const char *path, *result, *unit;
1374 dbus_bool_t success = true;
1376 if (dbus_message_get_args(message, &error,
1377 DBUS_TYPE_UINT32, &id,
1378 DBUS_TYPE_OBJECT_PATH, &path,
1379 DBUS_TYPE_STRING, &unit,
1380 DBUS_TYPE_STRING, &result,
1381 DBUS_TYPE_INVALID)) {
1384 p = set_remove(d->set, (char*) path);
1388 d->result = strdup(result);
1393 dbus_error_free(&error);
1394 if (dbus_message_get_args(message, &error,
1395 DBUS_TYPE_UINT32, &id,
1396 DBUS_TYPE_OBJECT_PATH, &path,
1397 DBUS_TYPE_STRING, &result,
1398 DBUS_TYPE_INVALID)) {
1401 /* Compatibility with older systemd versions <
1402 * 183 during upgrades. This should be dropped
1404 p = set_remove(d->set, (char*) path);
1408 d->result = strdup(result);
1413 dbus_error_free(&error);
1414 if (dbus_message_get_args(message, &error,
1415 DBUS_TYPE_UINT32, &id,
1416 DBUS_TYPE_OBJECT_PATH, &path,
1417 DBUS_TYPE_BOOLEAN, &success,
1418 DBUS_TYPE_INVALID)) {
1421 /* Compatibility with older systemd versions <
1422 * 19 during upgrades. This should be dropped
1425 p = set_remove(d->set, (char*) path);
1429 d->result = strdup("failed");
1435 log_error("Failed to parse message: %s", bus_error_message(&error));
1439 dbus_error_free(&error);
1440 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1443 static int enable_wait_for_jobs(DBusConnection *bus) {
1451 dbus_error_init(&error);
1452 dbus_bus_add_match(bus,
1454 "sender='org.freedesktop.systemd1',"
1455 "interface='org.freedesktop.systemd1.Manager',"
1456 "member='JobRemoved',"
1457 "path='/org/freedesktop/systemd1'",
1460 if (dbus_error_is_set(&error)) {
1461 log_error("Failed to add match: %s", bus_error_message(&error));
1462 dbus_error_free(&error);
1466 /* This is slightly dirty, since we don't undo the match registrations. */
1470 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1480 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1481 log_error("Failed to add filter.");
1486 while (!set_isempty(s) &&
1487 dbus_connection_read_write_dispatch(bus, -1))
1490 if (!arg_quiet && d.result) {
1491 if (streq(d.result, "timeout"))
1492 log_error("Job timed out.");
1493 else if (streq(d.result, "canceled"))
1494 log_error("Job canceled.");
1495 else if (streq(d.result, "dependency"))
1496 log_error("A dependency job failed. See system journal for details.");
1497 else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
1498 log_error("Job failed. See system journal and 'systemctl status' for details.");
1501 if (streq_ptr(d.result, "timeout"))
1503 else if (streq_ptr(d.result, "canceled"))
1505 else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
1513 /* This is slightly dirty, since we don't undo the filter registration. */
1518 static int check_one_unit(DBusConnection *bus, char *name, bool quiet) {
1519 DBusMessage *m = NULL, *reply = NULL;
1521 DBusMessageIter iter, sub;
1523 *interface = "org.freedesktop.systemd1.Unit",
1524 *property = "ActiveState";
1525 const char *path = NULL;
1527 int r = 3; /* According to LSB: "program is not running" */
1534 dbus_error_init(&error);
1536 m = dbus_message_new_method_call(
1537 "org.freedesktop.systemd1",
1538 "/org/freedesktop/systemd1",
1539 "org.freedesktop.systemd1.Manager",
1542 log_error("Could not allocate message.");
1547 n = unit_name_mangle(name);
1548 b = dbus_message_append_args(m,
1549 DBUS_TYPE_STRING, n ? &n : &name,
1553 log_error("Could not append arguments to message.");
1558 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
1560 /* Hmm, cannot figure out anything about this unit... */
1567 if (!dbus_message_get_args(reply, &error,
1568 DBUS_TYPE_OBJECT_PATH, &path,
1569 DBUS_TYPE_INVALID)) {
1570 log_error("Failed to parse reply: %s", bus_error_message(&error));
1575 dbus_message_unref(m);
1576 m = dbus_message_new_method_call(
1577 "org.freedesktop.systemd1",
1579 "org.freedesktop.DBus.Properties",
1582 log_error("Could not allocate message.");
1587 if (!dbus_message_append_args(m,
1588 DBUS_TYPE_STRING, &interface,
1589 DBUS_TYPE_STRING, &property,
1590 DBUS_TYPE_INVALID)) {
1591 log_error("Could not append arguments to message.");
1596 dbus_message_unref(reply);
1597 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
1599 log_error("Failed to issue method call: %s", bus_error_message(&error));
1604 if (!dbus_message_iter_init(reply, &iter) ||
1605 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1606 log_error("Failed to parse reply.");
1611 dbus_message_iter_recurse(&iter, &sub);
1613 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1614 log_error("Failed to parse reply.");
1619 dbus_message_iter_get_basic(&sub, &state);
1624 if (streq(state, "active") || streq(state, "reloading"))
1629 dbus_message_unref(m);
1632 dbus_message_unref(reply);
1634 dbus_error_free(&error);
1639 static void check_triggering_units(
1640 DBusConnection *bus,
1641 const char *unit_name) {
1644 DBusMessage *m = NULL, *reply = NULL;
1645 DBusMessageIter iter, sub;
1646 char *service_trigger = NULL;
1647 const char *interface = "org.freedesktop.systemd1.Unit",
1648 *triggered_by_property = "TriggeredBy";
1650 char *unit_path = NULL, *n = NULL;
1651 bool print_warning_label = true;
1653 dbus_error_init(&error);
1655 n = unit_name_mangle(unit_name);
1656 unit_path = unit_dbus_path_from_name(n ? n : unit_name);
1659 log_error("Could not allocate dbus path.");
1663 m = dbus_message_new_method_call("org.freedesktop.systemd1",
1665 "org.freedesktop.DBus.Properties",
1668 log_error("Could not allocate message.");
1672 if (!dbus_message_append_args(m,
1673 DBUS_TYPE_STRING, &interface,
1674 DBUS_TYPE_STRING, &triggered_by_property,
1675 DBUS_TYPE_INVALID)) {
1676 log_error("Could not append arguments to message.");
1680 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
1682 log_error("Failed to issue method call: %s", bus_error_message(&error));
1686 if (!dbus_message_iter_init(reply, &iter) ||
1687 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1688 log_error("Failed to parse reply: %s", bus_error_message(&error));
1693 dbus_message_iter_recurse(&iter, &sub);
1694 dbus_message_iter_recurse(&sub, &iter);
1697 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1700 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1701 log_error("Failed to parse reply: %s", bus_error_message(&error));
1705 dbus_message_iter_get_basic(&sub, &service_trigger);
1707 r = check_one_unit(bus, service_trigger, true);
1711 if (print_warning_label) {
1712 log_warning("Warning: Stopping %s, but it can still be activated by:", unit_name);
1713 print_warning_label = false;
1715 log_warning(" %s", service_trigger);
1718 dbus_message_iter_next(&sub);
1722 dbus_message_unref(m);
1725 dbus_message_unref(reply);
1727 dbus_error_free(&error);
1732 static int start_unit_one(
1733 DBusConnection *bus,
1740 DBusMessage *m = NULL, *reply = NULL;
1751 assert(arg_no_block || s);
1753 m = dbus_message_new_method_call(
1754 "org.freedesktop.systemd1",
1755 "/org/freedesktop/systemd1",
1756 "org.freedesktop.systemd1.Manager",
1759 log_error("Could not allocate message.");
1764 n = unit_name_mangle(name);
1765 b = dbus_message_append_args(m,
1766 DBUS_TYPE_STRING, n ? (const char **) &n : &name,
1767 DBUS_TYPE_STRING, &mode,
1771 log_error("Could not append arguments to message.");
1776 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error);
1779 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1780 /* There's always a fallback possible for
1781 * legacy actions. */
1786 log_error("Failed to issue method call: %s", bus_error_message(error));
1791 if (!dbus_message_get_args(reply, error,
1792 DBUS_TYPE_OBJECT_PATH, &path,
1793 DBUS_TYPE_INVALID)) {
1794 log_error("Failed to parse reply: %s", bus_error_message(error));
1799 if (need_daemon_reload(bus, name))
1800 log_warning("Warning: Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1801 arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
1803 if (!arg_no_block) {
1806 if (!(p = strdup(path))) {
1807 log_error("Failed to duplicate path.");
1812 if ((r = set_put(s, p)) < 0) {
1814 log_error("Failed to add path to set.");
1819 /* When stopping a unit warn if it can still be triggered by
1820 * another active unit (socket, path, timer) */
1821 if (!arg_quiet && streq(method, "StopUnit"))
1822 check_triggering_units(bus, name);
1828 dbus_message_unref(m);
1831 dbus_message_unref(reply);
1836 static enum action verb_to_action(const char *verb) {
1837 if (streq(verb, "halt"))
1839 else if (streq(verb, "poweroff"))
1840 return ACTION_POWEROFF;
1841 else if (streq(verb, "reboot"))
1842 return ACTION_REBOOT;
1843 else if (streq(verb, "kexec"))
1844 return ACTION_KEXEC;
1845 else if (streq(verb, "rescue"))
1846 return ACTION_RESCUE;
1847 else if (streq(verb, "emergency"))
1848 return ACTION_EMERGENCY;
1849 else if (streq(verb, "default"))
1850 return ACTION_DEFAULT;
1851 else if (streq(verb, "exit"))
1853 else if (streq(verb, "suspend"))
1854 return ACTION_SUSPEND;
1855 else if (streq(verb, "hibernate"))
1856 return ACTION_HIBERNATE;
1858 return ACTION_INVALID;
1861 static int start_unit(DBusConnection *bus, char **args) {
1863 static const char * const table[_ACTION_MAX] = {
1864 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1865 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1866 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1867 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1868 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1869 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1870 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1871 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1872 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1873 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1874 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1875 [ACTION_EXIT] = SPECIAL_EXIT_TARGET,
1876 [ACTION_SUSPEND] = SPECIAL_SUSPEND_TARGET,
1877 [ACTION_HIBERNATE] = SPECIAL_HIBERNATE_TARGET
1881 const char *method, *mode, *one_name;
1886 dbus_error_init(&error);
1890 ask_password_agent_open_if_enabled();
1892 if (arg_action == ACTION_SYSTEMCTL) {
1894 streq(args[0], "stop") ||
1895 streq(args[0], "condstop") ? "StopUnit" :
1896 streq(args[0], "reload") ? "ReloadUnit" :
1897 streq(args[0], "restart") ? "RestartUnit" :
1899 streq(args[0], "try-restart") ||
1900 streq(args[0], "condrestart") ? "TryRestartUnit" :
1902 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1904 streq(args[0], "reload-or-try-restart") ||
1905 streq(args[0], "condreload") ||
1907 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1911 (streq(args[0], "isolate") ||
1912 streq(args[0], "rescue") ||
1913 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1915 one_name = table[verb_to_action(args[0])];
1918 assert(arg_action < ELEMENTSOF(table));
1919 assert(table[arg_action]);
1921 method = "StartUnit";
1923 mode = (arg_action == ACTION_EMERGENCY ||
1924 arg_action == ACTION_RESCUE ||
1925 arg_action == ACTION_RUNLEVEL2 ||
1926 arg_action == ACTION_RUNLEVEL3 ||
1927 arg_action == ACTION_RUNLEVEL4 ||
1928 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1930 one_name = table[arg_action];
1933 if (!arg_no_block) {
1934 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1935 log_error("Could not watch jobs: %s", strerror(-ret));
1939 if (!(s = set_new(string_hash_func, string_compare_func))) {
1940 log_error("Failed to allocate set.");
1947 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1950 STRV_FOREACH(name, args+1)
1951 if ((r = start_unit_one(bus, method, *name, mode, &error, s)) != 0) {
1952 ret = translate_bus_error_to_exit_status(r, &error);
1953 dbus_error_free(&error);
1958 if ((r = wait_for_jobs(bus, s)) < 0) {
1967 dbus_error_free(&error);
1972 /* Ask systemd-logind, which might grant access to unprivileged users
1973 * through PolicyKit */
1974 static int reboot_with_logind(DBusConnection *bus, enum action a) {
1977 DBusMessage *m = NULL, *reply = NULL;
1979 dbus_bool_t interactive = true;
1982 dbus_error_init(&error);
1984 polkit_agent_open_if_enabled();
1992 case ACTION_POWEROFF:
1993 method = "PowerOff";
1996 case ACTION_SUSPEND:
2000 case ACTION_HIBERNATE:
2001 method = "Hibernate";
2008 m = dbus_message_new_method_call(
2009 "org.freedesktop.login1",
2010 "/org/freedesktop/login1",
2011 "org.freedesktop.login1.Manager",
2014 log_error("Could not allocate message.");
2019 if (!dbus_message_append_args(m,
2020 DBUS_TYPE_BOOLEAN, &interactive,
2021 DBUS_TYPE_INVALID)) {
2022 log_error("Could not append arguments to message.");
2027 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
2029 if (error_is_no_service(&error)) {
2030 log_debug("Failed to issue method call: %s", bus_error_message(&error));
2035 if (dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2036 log_debug("Failed to issue method call: %s", bus_error_message(&error));
2041 log_info("Failed to issue method call: %s", bus_error_message(&error));
2050 dbus_message_unref(m);
2053 dbus_message_unref(reply);
2055 dbus_error_free(&error);
2063 static int start_special(DBusConnection *bus, char **args) {
2069 a = verb_to_action(args[0]);
2071 if (arg_force >= 2 && geteuid() != 0) {
2072 log_error("Must be root.");
2076 if (arg_force >= 2 &&
2077 (a == ACTION_HALT ||
2078 a == ACTION_POWEROFF ||
2079 a == ACTION_REBOOT))
2082 if (arg_force >= 1 &&
2083 (a == ACTION_HALT ||
2084 a == ACTION_POWEROFF ||
2085 a == ACTION_REBOOT ||
2086 a == ACTION_KEXEC ||
2088 return daemon_reload(bus, args);
2090 /* first try logind, to allow authentication with polkit */
2091 if (geteuid() != 0 &&
2092 (a == ACTION_POWEROFF ||
2093 a == ACTION_REBOOT ||
2094 a == ACTION_SUSPEND ||
2095 a == ACTION_HIBERNATE)) {
2096 r = reboot_with_logind(bus, a);
2101 r = start_unit(bus, args);
2108 static int check_unit(DBusConnection *bus, char **args) {
2110 int r = 3; /* According to LSB: "program is not running" */
2115 STRV_FOREACH(name, args+1) {
2116 int state = check_one_unit(bus, *name, arg_quiet);
2126 static int kill_unit(DBusConnection *bus, char **args) {
2127 DBusMessage *m = NULL;
2135 dbus_error_init(&error);
2138 arg_kill_who = "all";
2140 STRV_FOREACH(name, args+1) {
2145 m = dbus_message_new_method_call(
2146 "org.freedesktop.systemd1",
2147 "/org/freedesktop/systemd1",
2148 "org.freedesktop.systemd1.Manager",
2151 log_error("Could not allocate message.");
2156 n = unit_name_mangle(*name);
2157 b = dbus_message_append_args(m,
2158 DBUS_TYPE_STRING, n ? &n : name,
2159 DBUS_TYPE_STRING, &arg_kill_who,
2160 DBUS_TYPE_INT32, &arg_signal,
2164 log_error("Could not append arguments to message.");
2169 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
2171 log_error("Failed to issue method call: %s", bus_error_message(&error));
2172 dbus_error_free(&error);
2176 dbus_message_unref(m);
2179 dbus_message_unref(reply);
2185 dbus_message_unref(m);
2187 dbus_error_free(&error);
2192 typedef struct ExecStatusInfo {
2200 usec_t start_timestamp;
2201 usec_t exit_timestamp;
2206 LIST_FIELDS(struct ExecStatusInfo, exec);
2209 static void exec_status_info_free(ExecStatusInfo *i) {
2218 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
2219 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
2220 DBusMessageIter sub2, sub3;
2224 int32_t code, status;
2230 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
2233 dbus_message_iter_recurse(sub, &sub2);
2235 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
2238 if (!(i->path = strdup(path)))
2241 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
2242 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
2246 dbus_message_iter_recurse(&sub2, &sub3);
2247 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
2248 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
2249 dbus_message_iter_next(&sub3);
2254 if (!(i->argv = new0(char*, n+1)))
2258 dbus_message_iter_recurse(&sub2, &sub3);
2259 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
2262 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
2263 dbus_message_iter_get_basic(&sub3, &s);
2264 dbus_message_iter_next(&sub3);
2266 if (!(i->argv[n++] = strdup(s)))
2270 if (!dbus_message_iter_next(&sub2) ||
2271 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
2272 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
2273 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
2274 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
2275 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
2276 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
2277 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
2278 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
2282 i->start_timestamp = (usec_t) start_timestamp;
2283 i->exit_timestamp = (usec_t) exit_timestamp;
2284 i->pid = (pid_t) pid;
2291 typedef struct UnitStatusInfo {
2293 const char *load_state;
2294 const char *active_state;
2295 const char *sub_state;
2296 const char *unit_file_state;
2298 const char *description;
2299 const char *following;
2301 char **documentation;
2303 const char *fragment_path;
2304 const char *source_path;
2305 const char *default_control_group;
2307 const char *load_error;
2310 usec_t inactive_exit_timestamp;
2311 usec_t inactive_exit_timestamp_monotonic;
2312 usec_t active_enter_timestamp;
2313 usec_t active_exit_timestamp;
2314 usec_t inactive_enter_timestamp;
2316 bool need_daemon_reload;
2321 const char *status_text;
2324 usec_t start_timestamp;
2325 usec_t exit_timestamp;
2327 int exit_code, exit_status;
2329 usec_t condition_timestamp;
2330 bool condition_result;
2333 unsigned n_accepted;
2334 unsigned n_connections;
2338 const char *sysfs_path;
2340 /* Mount, Automount */
2346 LIST_HEAD(ExecStatusInfo, exec);
2349 static void print_status_info(UnitStatusInfo *i) {
2351 const char *on, *off, *ss;
2353 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
2354 char since2[FORMAT_TIMESTAMP_MAX], *s2;
2359 /* This shows pretty information about a unit. See
2360 * print_property() for a low-level property printer */
2362 printf("%s", strna(i->id));
2364 if (i->description && !streq_ptr(i->id, i->description))
2365 printf(" - %s", i->description);
2370 printf("\t Follow: unit currently follows state of %s\n", i->following);
2372 if (streq_ptr(i->load_state, "error")) {
2373 on = ansi_highlight_red(true);
2374 off = ansi_highlight_red(false);
2378 path = i->source_path ? i->source_path : i->fragment_path;
2381 printf("\t Loaded: %s%s%s (Reason: %s)\n", on, strna(i->load_state), off, i->load_error);
2382 else if (path && i->unit_file_state)
2383 printf("\t Loaded: %s%s%s (%s; %s)\n", on, strna(i->load_state), off, path, i->unit_file_state);
2385 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, path);
2387 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
2389 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
2391 if (streq_ptr(i->active_state, "failed")) {
2392 on = ansi_highlight_red(true);
2393 off = ansi_highlight_red(false);
2394 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
2395 on = ansi_highlight_green(true);
2396 off = ansi_highlight_green(false);
2401 printf("\t Active: %s%s (%s)%s",
2403 strna(i->active_state),
2407 printf("\t Active: %s%s%s",
2409 strna(i->active_state),
2412 if (!isempty(i->result) && !streq(i->result, "success"))
2413 printf(" (Result: %s)", i->result);
2415 timestamp = (streq_ptr(i->active_state, "active") ||
2416 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
2417 (streq_ptr(i->active_state, "inactive") ||
2418 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
2419 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
2420 i->active_exit_timestamp;
2422 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
2423 s2 = format_timestamp(since2, sizeof(since2), timestamp);
2426 printf(" since %s; %s\n", s2, s1);
2428 printf(" since %s\n", s2);
2432 if (!i->condition_result && i->condition_timestamp > 0) {
2433 s1 = format_timestamp_pretty(since1, sizeof(since1), i->condition_timestamp);
2434 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
2437 printf("\t start condition failed at %s; %s\n", s2, s1);
2439 printf("\t start condition failed at %s\n", s2);
2443 printf("\t Device: %s\n", i->sysfs_path);
2445 printf("\t Where: %s\n", i->where);
2447 printf("\t What: %s\n", i->what);
2449 if (!strv_isempty(i->documentation)) {
2453 STRV_FOREACH(t, i->documentation) {
2455 printf("\t Docs: %s\n", *t);
2458 printf("\t %s\n", *t);
2463 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
2465 LIST_FOREACH(exec, p, i->exec) {
2469 /* Only show exited processes here */
2473 t = strv_join(p->argv, " ");
2474 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
2477 good = is_clean_exit_lsb(p->code, p->status);
2479 on = ansi_highlight_red(true);
2480 off = ansi_highlight_red(false);
2484 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
2486 if (p->code == CLD_EXITED) {
2489 printf("status=%i", p->status);
2491 c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD);
2496 printf("signal=%s", signal_to_string(p->status));
2498 printf(")%s\n", off);
2500 if (i->main_pid == p->pid &&
2501 i->start_timestamp == p->start_timestamp &&
2502 i->exit_timestamp == p->start_timestamp)
2503 /* Let's not show this twice */
2506 if (p->pid == i->control_pid)
2510 if (i->main_pid > 0 || i->control_pid > 0) {
2513 if (i->main_pid > 0) {
2514 printf("Main PID: %u", (unsigned) i->main_pid);
2518 get_process_comm(i->main_pid, &t);
2523 } else if (i->exit_code > 0) {
2524 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2526 if (i->exit_code == CLD_EXITED) {
2529 printf("status=%i", i->exit_status);
2531 c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD);
2536 printf("signal=%s", signal_to_string(i->exit_status));
2541 if (i->main_pid > 0 && i->control_pid > 0)
2544 if (i->control_pid > 0) {
2547 printf(" Control: %u", (unsigned) i->control_pid);
2549 get_process_comm(i->control_pid, &t);
2560 printf("\t Status: \"%s\"\n", i->status_text);
2562 if (i->default_control_group) {
2565 printf("\t CGroup: %s\n", i->default_control_group);
2567 if (arg_transport != TRANSPORT_SSH) {
2577 if (i->main_pid > 0)
2578 extra[k++] = i->main_pid;
2580 if (i->control_pid > 0)
2581 extra[k++] = i->control_pid;
2583 show_cgroup_and_extra_by_spec(i->default_control_group, "\t\t ", c, false, arg_all, extra, k);
2587 if (i->id && arg_transport != TRANSPORT_SSH) {
2589 arg_lines * OUTPUT_SHOW_ALL |
2590 arg_follow * OUTPUT_FOLLOW |
2591 !arg_quiet * OUTPUT_WARN_CUTOFF |
2592 on_tty() * OUTPUT_COLOR;
2595 show_journal_by_unit(i->id, arg_output, 0,
2596 i->inactive_exit_timestamp_monotonic,
2600 if (i->need_daemon_reload)
2601 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2602 ansi_highlight_red(true),
2603 ansi_highlight_red(false),
2604 arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
2607 static void show_unit_help(UnitStatusInfo *i) {
2612 if (!i->documentation) {
2613 log_info("Documentation for %s not known.", i->id);
2617 STRV_FOREACH(p, i->documentation) {
2619 if (startswith(*p, "man:")) {
2622 char *page = NULL, *section = NULL;
2623 const char *args[4] = { "man", NULL, NULL, NULL };
2628 if ((*p)[k-1] == ')')
2629 e = strrchr(*p, '(');
2632 page = strndup((*p) + 4, e - *p - 4);
2638 section = strndup(e + 1, *p + k - e - 2);
2652 log_error("Failed to fork: %m");
2660 execvp(args[0], (char**) args);
2661 log_error("Failed to execute man: %m");
2662 _exit(EXIT_FAILURE);
2668 wait_for_terminate(pid, NULL);
2670 log_info("Can't show: %s", *p);
2674 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2680 switch (dbus_message_iter_get_arg_type(iter)) {
2682 case DBUS_TYPE_STRING: {
2685 dbus_message_iter_get_basic(iter, &s);
2688 if (streq(name, "Id"))
2690 else if (streq(name, "LoadState"))
2692 else if (streq(name, "ActiveState"))
2693 i->active_state = s;
2694 else if (streq(name, "SubState"))
2696 else if (streq(name, "Description"))
2698 else if (streq(name, "FragmentPath"))
2699 i->fragment_path = s;
2700 else if (streq(name, "SourcePath"))
2702 else if (streq(name, "DefaultControlGroup"))
2703 i->default_control_group = s;
2704 else if (streq(name, "StatusText"))
2706 else if (streq(name, "SysFSPath"))
2708 else if (streq(name, "Where"))
2710 else if (streq(name, "What"))
2712 else if (streq(name, "Following"))
2714 else if (streq(name, "UnitFileState"))
2715 i->unit_file_state = s;
2716 else if (streq(name, "Result"))
2723 case DBUS_TYPE_BOOLEAN: {
2726 dbus_message_iter_get_basic(iter, &b);
2728 if (streq(name, "Accept"))
2730 else if (streq(name, "NeedDaemonReload"))
2731 i->need_daemon_reload = b;
2732 else if (streq(name, "ConditionResult"))
2733 i->condition_result = b;
2738 case DBUS_TYPE_UINT32: {
2741 dbus_message_iter_get_basic(iter, &u);
2743 if (streq(name, "MainPID")) {
2745 i->main_pid = (pid_t) u;
2748 } else if (streq(name, "ControlPID"))
2749 i->control_pid = (pid_t) u;
2750 else if (streq(name, "ExecMainPID")) {
2752 i->main_pid = (pid_t) u;
2753 } else if (streq(name, "NAccepted"))
2755 else if (streq(name, "NConnections"))
2756 i->n_connections = u;
2761 case DBUS_TYPE_INT32: {
2764 dbus_message_iter_get_basic(iter, &j);
2766 if (streq(name, "ExecMainCode"))
2767 i->exit_code = (int) j;
2768 else if (streq(name, "ExecMainStatus"))
2769 i->exit_status = (int) j;
2774 case DBUS_TYPE_UINT64: {
2777 dbus_message_iter_get_basic(iter, &u);
2779 if (streq(name, "ExecMainStartTimestamp"))
2780 i->start_timestamp = (usec_t) u;
2781 else if (streq(name, "ExecMainExitTimestamp"))
2782 i->exit_timestamp = (usec_t) u;
2783 else if (streq(name, "ActiveEnterTimestamp"))
2784 i->active_enter_timestamp = (usec_t) u;
2785 else if (streq(name, "InactiveEnterTimestamp"))
2786 i->inactive_enter_timestamp = (usec_t) u;
2787 else if (streq(name, "InactiveExitTimestamp"))
2788 i->inactive_exit_timestamp = (usec_t) u;
2789 else if (streq(name, "InactiveExitTimestampMonotonic"))
2790 i->inactive_exit_timestamp_monotonic = (usec_t) u;
2791 else if (streq(name, "ActiveExitTimestamp"))
2792 i->active_exit_timestamp = (usec_t) u;
2793 else if (streq(name, "ConditionTimestamp"))
2794 i->condition_timestamp = (usec_t) u;
2799 case DBUS_TYPE_ARRAY: {
2801 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2802 startswith(name, "Exec")) {
2803 DBusMessageIter sub;
2805 dbus_message_iter_recurse(iter, &sub);
2806 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2807 ExecStatusInfo *info;
2810 if (!(info = new0(ExecStatusInfo, 1)))
2813 if (!(info->name = strdup(name))) {
2818 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2823 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2825 dbus_message_iter_next(&sub);
2827 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING &&
2828 streq(name, "Documentation")) {
2830 DBusMessageIter sub;
2832 dbus_message_iter_recurse(iter, &sub);
2833 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING) {
2837 dbus_message_iter_get_basic(&sub, &s);
2839 l = strv_append(i->documentation, s);
2843 strv_free(i->documentation);
2844 i->documentation = l;
2846 dbus_message_iter_next(&sub);
2853 case DBUS_TYPE_STRUCT: {
2855 if (streq(name, "LoadError")) {
2856 DBusMessageIter sub;
2857 const char *n, *message;
2860 dbus_message_iter_recurse(iter, &sub);
2862 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &n, true);
2866 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &message, false);
2870 if (!isempty(message))
2871 i->load_error = message;
2881 static int print_property(const char *name, DBusMessageIter *iter) {
2885 /* This is a low-level property printer, see
2886 * print_status_info() for the nicer output */
2888 if (arg_property && !strv_find(arg_property, name))
2891 switch (dbus_message_iter_get_arg_type(iter)) {
2893 case DBUS_TYPE_STRUCT: {
2894 DBusMessageIter sub;
2895 dbus_message_iter_recurse(iter, &sub);
2897 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2900 dbus_message_iter_get_basic(&sub, &u);
2903 printf("%s=%u\n", name, (unsigned) u);
2905 printf("%s=\n", name);
2908 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2911 dbus_message_iter_get_basic(&sub, &s);
2913 if (arg_all || s[0])
2914 printf("%s=%s\n", name, s);
2917 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "LoadError")) {
2918 const char *a = NULL, *b = NULL;
2920 if (bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &a, true) >= 0)
2921 bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &b, false);
2923 if (arg_all || !isempty(a) || !isempty(b))
2924 printf("%s=%s \"%s\"\n", name, strempty(a), strempty(b));
2932 case DBUS_TYPE_ARRAY:
2934 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
2935 DBusMessageIter sub, sub2;
2937 dbus_message_iter_recurse(iter, &sub);
2938 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2942 dbus_message_iter_recurse(&sub, &sub2);
2944 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
2945 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
2946 printf("EnvironmentFile=%s (ignore_errors=%s)\n", path, yes_no(ignore));
2948 dbus_message_iter_next(&sub);
2953 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2954 DBusMessageIter sub, sub2;
2956 dbus_message_iter_recurse(iter, &sub);
2957 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2958 const char *type, *path;
2960 dbus_message_iter_recurse(&sub, &sub2);
2962 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2963 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2964 printf("%s=%s\n", type, path);
2966 dbus_message_iter_next(&sub);
2971 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2972 DBusMessageIter sub, sub2;
2974 dbus_message_iter_recurse(iter, &sub);
2975 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2977 uint64_t value, next_elapse;
2979 dbus_message_iter_recurse(&sub, &sub2);
2981 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2982 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2983 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2984 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2986 printf("%s={ value=%s ; next_elapse=%s }\n",
2988 format_timespan(timespan1, sizeof(timespan1), value),
2989 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2992 dbus_message_iter_next(&sub);
2997 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "ControlGroupAttributes")) {
2998 DBusMessageIter sub, sub2;
3000 dbus_message_iter_recurse(iter, &sub);
3001 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3002 const char *controller, *attr, *value;
3004 dbus_message_iter_recurse(&sub, &sub2);
3006 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &controller, true) >= 0 &&
3007 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &attr, true) >= 0 &&
3008 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &value, false) >= 0) {
3010 printf("ControlGroupAttribute={ controller=%s ; attribute=%s ; value=\"%s\" }\n",
3016 dbus_message_iter_next(&sub);
3021 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
3022 DBusMessageIter sub;
3024 dbus_message_iter_recurse(iter, &sub);
3025 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3026 ExecStatusInfo info;
3029 if (exec_status_info_deserialize(&sub, &info) >= 0) {
3030 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
3033 t = strv_join(info.argv, " ");
3035 printf("%s={ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
3039 yes_no(info.ignore),
3040 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
3041 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
3042 (unsigned) info. pid,
3043 sigchld_code_to_string(info.code),
3045 info.code == CLD_EXITED ? "" : "/",
3046 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
3052 strv_free(info.argv);
3054 dbus_message_iter_next(&sub);
3063 if (generic_print_property(name, iter, arg_all) > 0)
3067 printf("%s=[unprintable]\n", name);
3072 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
3073 DBusMessage *m = NULL, *reply = NULL;
3074 const char *interface = "";
3077 DBusMessageIter iter, sub, sub2, sub3;
3078 UnitStatusInfo info;
3086 dbus_error_init(&error);
3088 if (!(m = dbus_message_new_method_call(
3089 "org.freedesktop.systemd1",
3091 "org.freedesktop.DBus.Properties",
3093 log_error("Could not allocate message.");
3098 if (!dbus_message_append_args(m,
3099 DBUS_TYPE_STRING, &interface,
3100 DBUS_TYPE_INVALID)) {
3101 log_error("Could not append arguments to message.");
3106 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3107 log_error("Failed to issue method call: %s", bus_error_message(&error));
3112 if (!dbus_message_iter_init(reply, &iter) ||
3113 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
3114 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
3115 log_error("Failed to parse reply.");
3120 dbus_message_iter_recurse(&iter, &sub);
3127 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
3130 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
3131 log_error("Failed to parse reply.");
3136 dbus_message_iter_recurse(&sub, &sub2);
3138 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
3139 log_error("Failed to parse reply.");
3144 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
3145 log_error("Failed to parse reply.");
3150 dbus_message_iter_recurse(&sub2, &sub3);
3152 if (show_properties)
3153 r = print_property(name, &sub3);
3155 r = status_property(name, &sub3, &info);
3158 log_error("Failed to parse reply.");
3163 dbus_message_iter_next(&sub);
3168 if (!show_properties) {
3169 if (streq(verb, "help"))
3170 show_unit_help(&info);
3172 print_status_info(&info);
3175 strv_free(info.documentation);
3177 if (!streq_ptr(info.active_state, "active") &&
3178 !streq_ptr(info.active_state, "reloading") &&
3179 streq(verb, "status"))
3180 /* According to LSB: "program not running" */
3183 while ((p = info.exec)) {
3184 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
3185 exec_status_info_free(p);
3190 dbus_message_unref(m);
3193 dbus_message_unref(reply);
3195 dbus_error_free(&error);
3200 static int show_one_by_pid(const char *verb, DBusConnection *bus, uint32_t pid, bool *new_line) {
3201 DBusMessage *m = NULL, *reply = NULL;
3202 const char *path = NULL;
3206 dbus_error_init(&error);
3208 m = dbus_message_new_method_call(
3209 "org.freedesktop.systemd1",
3210 "/org/freedesktop/systemd1",
3211 "org.freedesktop.systemd1.Manager",
3214 log_error("Could not allocate message.");
3219 if (!dbus_message_append_args(m,
3220 DBUS_TYPE_UINT32, &pid,
3221 DBUS_TYPE_INVALID)) {
3222 log_error("Could not append arguments to message.");
3227 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3229 log_error("Failed to issue method call: %s", bus_error_message(&error));
3234 if (!dbus_message_get_args(reply, &error,
3235 DBUS_TYPE_OBJECT_PATH, &path,
3236 DBUS_TYPE_INVALID)) {
3237 log_error("Failed to parse reply: %s", bus_error_message(&error));
3242 r = show_one(verb, bus, path, false, new_line);
3246 dbus_message_unref(m);
3249 dbus_message_unref(reply);
3251 dbus_error_free(&error);
3256 static int show(DBusConnection *bus, char **args) {
3258 bool show_properties, new_line = false;
3264 show_properties = streq(args[0], "show");
3266 if (show_properties)
3267 pager_open_if_enabled();
3269 if (show_properties && strv_length(args) <= 1) {
3270 /* If not argument is specified inspect the manager
3273 return show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
3276 STRV_FOREACH(name, args+1) {
3279 if (safe_atou32(*name, &id) < 0) {
3281 /* Interpret as unit name */
3283 n = unit_name_mangle(*name);
3284 p = unit_dbus_path_from_name(n ? n : *name);
3289 r = show_one(args[0], bus, p, show_properties, &new_line);
3295 } else if (show_properties) {
3297 /* Interpret as job id */
3300 if (asprintf(&p, "/org/freedesktop/systemd1/job/%u", id) < 0)
3303 r = show_one(args[0], bus, p, show_properties, &new_line);
3311 /* Interpret as PID */
3313 r = show_one_by_pid(args[0], bus, id, &new_line);
3322 static int dump(DBusConnection *bus, char **args) {
3323 DBusMessage *m = NULL, *reply = NULL;
3328 dbus_error_init(&error);
3330 pager_open_if_enabled();
3332 if (!(m = dbus_message_new_method_call(
3333 "org.freedesktop.systemd1",
3334 "/org/freedesktop/systemd1",
3335 "org.freedesktop.systemd1.Manager",
3337 log_error("Could not allocate message.");
3341 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3342 log_error("Failed to issue method call: %s", bus_error_message(&error));
3347 if (!dbus_message_get_args(reply, &error,
3348 DBUS_TYPE_STRING, &text,
3349 DBUS_TYPE_INVALID)) {
3350 log_error("Failed to parse reply: %s", bus_error_message(&error));
3355 fputs(text, stdout);
3361 dbus_message_unref(m);
3364 dbus_message_unref(reply);
3366 dbus_error_free(&error);
3371 static int snapshot(DBusConnection *bus, char **args) {
3372 DBusMessage *m = NULL, *reply = NULL;
3375 const char *name = "", *path, *id;
3376 dbus_bool_t cleanup = FALSE;
3377 DBusMessageIter iter, sub;
3379 *interface = "org.freedesktop.systemd1.Unit",
3384 dbus_error_init(&error);
3386 m = dbus_message_new_method_call(
3387 "org.freedesktop.systemd1",
3388 "/org/freedesktop/systemd1",
3389 "org.freedesktop.systemd1.Manager",
3392 log_error("Could not allocate message.");
3396 if (strv_length(args) > 1)
3399 n = unit_name_mangle(name);
3400 b = dbus_message_append_args(m,
3401 DBUS_TYPE_STRING, n ? (const char**) &n : &name,
3402 DBUS_TYPE_BOOLEAN, &cleanup,
3406 log_error("Could not append arguments to message.");
3411 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3413 log_error("Failed to issue method call: %s", bus_error_message(&error));
3418 if (!dbus_message_get_args(reply, &error,
3419 DBUS_TYPE_OBJECT_PATH, &path,
3420 DBUS_TYPE_INVALID)) {
3421 log_error("Failed to parse reply: %s", bus_error_message(&error));
3426 dbus_message_unref(m);
3427 m = dbus_message_new_method_call(
3428 "org.freedesktop.systemd1",
3430 "org.freedesktop.DBus.Properties",
3433 log_error("Could not allocate message.");
3437 if (!dbus_message_append_args(m,
3438 DBUS_TYPE_STRING, &interface,
3439 DBUS_TYPE_STRING, &property,
3440 DBUS_TYPE_INVALID)) {
3441 log_error("Could not append arguments to message.");
3446 dbus_message_unref(reply);
3447 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3449 log_error("Failed to issue method call: %s", bus_error_message(&error));
3454 if (!dbus_message_iter_init(reply, &iter) ||
3455 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3456 log_error("Failed to parse reply.");
3461 dbus_message_iter_recurse(&iter, &sub);
3463 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3464 log_error("Failed to parse reply.");
3469 dbus_message_iter_get_basic(&sub, &id);
3477 dbus_message_unref(m);
3480 dbus_message_unref(reply);
3482 dbus_error_free(&error);
3487 static int delete_snapshot(DBusConnection *bus, char **args) {
3488 DBusMessage *m = NULL, *reply = NULL;
3496 dbus_error_init(&error);
3498 STRV_FOREACH(name, args+1) {
3499 const char *path = NULL;
3503 m = dbus_message_new_method_call(
3504 "org.freedesktop.systemd1",
3505 "/org/freedesktop/systemd1",
3506 "org.freedesktop.systemd1.Manager",
3509 log_error("Could not allocate message.");
3514 n = unit_name_mangle(*name);
3515 b = dbus_message_append_args(m,
3516 DBUS_TYPE_STRING, n ? &n : name,
3520 log_error("Could not append arguments to message.");
3525 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3527 log_error("Failed to issue method call: %s", bus_error_message(&error));
3532 if (!dbus_message_get_args(reply, &error,
3533 DBUS_TYPE_OBJECT_PATH, &path,
3534 DBUS_TYPE_INVALID)) {
3535 log_error("Failed to parse reply: %s", bus_error_message(&error));
3540 dbus_message_unref(m);
3541 m = dbus_message_new_method_call(
3542 "org.freedesktop.systemd1",
3544 "org.freedesktop.systemd1.Snapshot",
3547 log_error("Could not allocate message.");
3552 dbus_message_unref(reply);
3553 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3555 log_error("Failed to issue method call: %s", bus_error_message(&error));
3560 dbus_message_unref(m);
3561 dbus_message_unref(reply);
3569 dbus_message_unref(m);
3572 dbus_message_unref(reply);
3574 dbus_error_free(&error);
3579 static int daemon_reload(DBusConnection *bus, char **args) {
3580 DBusMessage *m = NULL, *reply = NULL;
3585 dbus_error_init(&error);
3587 if (arg_action == ACTION_RELOAD)
3589 else if (arg_action == ACTION_REEXEC)
3590 method = "Reexecute";
3592 assert(arg_action == ACTION_SYSTEMCTL);
3595 streq(args[0], "clear-jobs") ||
3596 streq(args[0], "cancel") ? "ClearJobs" :
3597 streq(args[0], "daemon-reexec") ? "Reexecute" :
3598 streq(args[0], "reset-failed") ? "ResetFailed" :
3599 streq(args[0], "halt") ? "Halt" :
3600 streq(args[0], "poweroff") ? "PowerOff" :
3601 streq(args[0], "reboot") ? "Reboot" :
3602 streq(args[0], "kexec") ? "KExec" :
3603 streq(args[0], "exit") ? "Exit" :
3604 /* "daemon-reload" */ "Reload";
3607 if (!(m = dbus_message_new_method_call(
3608 "org.freedesktop.systemd1",
3609 "/org/freedesktop/systemd1",
3610 "org.freedesktop.systemd1.Manager",
3612 log_error("Could not allocate message.");
3616 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3618 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3619 /* There's always a fallback possible for
3620 * legacy actions. */
3625 if (streq(method, "Reexecute") && dbus_error_has_name(&error, DBUS_ERROR_NO_REPLY)) {
3626 /* On reexecution, we expect a disconnect, not
3632 log_error("Failed to issue method call: %s", bus_error_message(&error));
3641 dbus_message_unref(m);
3644 dbus_message_unref(reply);
3646 dbus_error_free(&error);
3651 static int reset_failed(DBusConnection *bus, char **args) {
3652 DBusMessage *m = NULL;
3658 dbus_error_init(&error);
3660 if (strv_length(args) <= 1)
3661 return daemon_reload(bus, args);
3663 STRV_FOREACH(name, args+1) {
3668 m = dbus_message_new_method_call(
3669 "org.freedesktop.systemd1",
3670 "/org/freedesktop/systemd1",
3671 "org.freedesktop.systemd1.Manager",
3674 log_error("Could not allocate message.");
3679 n = unit_name_mangle(*name);
3680 b = dbus_message_append_args(m,
3681 DBUS_TYPE_STRING, n ? &n : name,
3685 log_error("Could not append arguments to message.");
3690 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3692 log_error("Failed to issue method call: %s", bus_error_message(&error));
3697 dbus_message_unref(m);
3698 dbus_message_unref(reply);
3706 dbus_message_unref(m);
3708 dbus_error_free(&error);
3713 static int show_enviroment(DBusConnection *bus, char **args) {
3714 DBusMessage *m = NULL, *reply = NULL;
3716 DBusMessageIter iter, sub, sub2;
3719 *interface = "org.freedesktop.systemd1.Manager",
3720 *property = "Environment";
3722 dbus_error_init(&error);
3724 pager_open_if_enabled();
3726 if (!(m = dbus_message_new_method_call(
3727 "org.freedesktop.systemd1",
3728 "/org/freedesktop/systemd1",
3729 "org.freedesktop.DBus.Properties",
3731 log_error("Could not allocate message.");
3735 if (!dbus_message_append_args(m,
3736 DBUS_TYPE_STRING, &interface,
3737 DBUS_TYPE_STRING, &property,
3738 DBUS_TYPE_INVALID)) {
3739 log_error("Could not append arguments to message.");
3744 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3745 log_error("Failed to issue method call: %s", bus_error_message(&error));
3750 if (!dbus_message_iter_init(reply, &iter) ||
3751 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3752 log_error("Failed to parse reply.");
3757 dbus_message_iter_recurse(&iter, &sub);
3759 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3760 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3761 log_error("Failed to parse reply.");
3766 dbus_message_iter_recurse(&sub, &sub2);
3768 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3771 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3772 log_error("Failed to parse reply.");
3777 dbus_message_iter_get_basic(&sub2, &text);
3778 printf("%s\n", text);
3780 dbus_message_iter_next(&sub2);
3787 dbus_message_unref(m);
3790 dbus_message_unref(reply);
3792 dbus_error_free(&error);
3797 static int switch_root(DBusConnection *bus, char **args) {
3798 DBusMessage *m = NULL, *reply = NULL;
3800 const char *root, *init;
3804 dbus_error_init(&error);
3806 l = strv_length(args);
3807 if (l < 2 || l > 3) {
3808 log_error("Wrong number of arguments.");
3813 init = l >= 3 ? args[2] : "";
3815 m = dbus_message_new_method_call(
3816 "org.freedesktop.systemd1",
3817 "/org/freedesktop/systemd1",
3818 "org.freedesktop.systemd1.Manager",
3821 log_error("Could not allocate message.");
3825 if (!dbus_message_append_args(
3827 DBUS_TYPE_STRING, &root,
3828 DBUS_TYPE_STRING, &init,
3829 DBUS_TYPE_INVALID)) {
3830 log_error("Could not append arguments to message.");
3835 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3837 log_error("Failed to issue method call: %s", bus_error_message(&error));
3846 dbus_message_unref(m);
3849 dbus_message_unref(reply);
3851 dbus_error_free(&error);
3856 static int set_environment(DBusConnection *bus, char **args) {
3857 DBusMessage *m = NULL, *reply = NULL;
3861 DBusMessageIter iter, sub;
3864 dbus_error_init(&error);
3866 method = streq(args[0], "set-environment")
3868 : "UnsetEnvironment";
3870 if (!(m = dbus_message_new_method_call(
3871 "org.freedesktop.systemd1",
3872 "/org/freedesktop/systemd1",
3873 "org.freedesktop.systemd1.Manager",
3876 log_error("Could not allocate message.");
3880 dbus_message_iter_init_append(m, &iter);
3882 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3883 log_error("Could not append arguments to message.");
3888 STRV_FOREACH(name, args+1)
3889 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, name)) {
3890 log_error("Could not append arguments to message.");
3895 if (!dbus_message_iter_close_container(&iter, &sub)) {
3896 log_error("Could not append arguments to message.");
3901 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3902 log_error("Failed to issue method call: %s", bus_error_message(&error));
3911 dbus_message_unref(m);
3914 dbus_message_unref(reply);
3916 dbus_error_free(&error);
3921 static int enable_sysv_units(char **args) {
3924 #if defined (HAVE_SYSV_COMPAT) && (defined(TARGET_FEDORA) || defined(TARGET_MANDRIVA) || defined(TARGET_SUSE) || defined(TARGET_ALTLINUX) || defined(TARGET_MAGEIA))
3925 const char *verb = args[0];
3926 unsigned f = 1, t = 1;
3929 if (arg_scope != UNIT_FILE_SYSTEM)
3932 if (!streq(verb, "enable") &&
3933 !streq(verb, "disable") &&
3934 !streq(verb, "is-enabled"))
3937 /* Processes all SysV units, and reshuffles the array so that
3938 * afterwards only the native units remain */
3941 r = lookup_paths_init(&paths, MANAGER_SYSTEM, false, NULL, NULL, NULL);
3946 for (f = 1; args[f]; f++) {
3949 bool found_native = false, found_sysv;
3951 const char *argv[6] = { "/sbin/chkconfig", NULL, NULL, NULL, NULL };
3952 char **k, *l, *q = NULL;
3959 if (!endswith(name, ".service"))
3962 if (path_is_absolute(name))
3965 STRV_FOREACH(k, paths.unit_path) {
3968 if (!isempty(arg_root))
3969 asprintf(&p, "%s/%s/%s", arg_root, *k, name);
3971 asprintf(&p, "%s/%s", *k, name);
3978 found_native = access(p, F_OK) >= 0;
3989 if (!isempty(arg_root))
3990 asprintf(&p, "%s/" SYSTEM_SYSVINIT_PATH "/%s", arg_root, name);
3992 asprintf(&p, SYSTEM_SYSVINIT_PATH "/%s", name);
3998 p[strlen(p) - sizeof(".service") + 1] = 0;
3999 found_sysv = access(p, F_OK) >= 0;
4006 /* Mark this entry, so that we don't try enabling it as native unit */
4007 args[f] = (char*) "";
4009 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", name);
4011 if (!isempty(arg_root))
4012 argv[c++] = q = strappend("--root=", arg_root);
4014 argv[c++] = path_get_file_name(p);
4016 streq(verb, "enable") ? "on" :
4017 streq(verb, "disable") ? "off" : "--level=5";
4020 l = strv_join((char**)argv, " ");
4028 log_info("Executing %s", l);
4033 log_error("Failed to fork: %m");
4038 } else if (pid == 0) {
4041 execv(argv[0], (char**) argv);
4042 _exit(EXIT_FAILURE);
4048 j = wait_for_terminate(pid, &status);
4050 log_error("Failed to wait for child: %s", strerror(-r));
4055 if (status.si_code == CLD_EXITED) {
4056 if (streq(verb, "is-enabled")) {
4057 if (status.si_status == 0) {
4066 } else if (status.si_status != 0) {
4077 lookup_paths_free(&paths);
4079 /* Drop all SysV units */
4080 for (f = 1, t = 1; args[f]; f++) {
4082 if (isempty(args[f]))
4085 args[t++] = args[f];
4094 static int enable_unit(DBusConnection *bus, char **args) {
4095 const char *verb = args[0];
4096 UnitFileChange *changes = NULL;
4097 unsigned n_changes = 0, i;
4098 int carries_install_info = -1;
4099 DBusMessage *m = NULL, *reply = NULL;
4103 r = enable_sysv_units(args);
4110 dbus_error_init(&error);
4112 if (!bus || avoid_bus()) {
4113 if (streq(verb, "enable")) {
4114 r = unit_file_enable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4115 carries_install_info = r;
4116 } else if (streq(verb, "disable"))
4117 r = unit_file_disable(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
4118 else if (streq(verb, "reenable")) {
4119 r = unit_file_reenable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4120 carries_install_info = r;
4121 } else if (streq(verb, "link"))
4122 r = unit_file_link(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4123 else if (streq(verb, "preset")) {
4124 r = unit_file_preset(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4125 carries_install_info = r;
4126 } else if (streq(verb, "mask"))
4127 r = unit_file_mask(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4128 else if (streq(verb, "unmask"))
4129 r = unit_file_unmask(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
4131 assert_not_reached("Unknown verb");
4134 log_error("Operation failed: %s", strerror(-r));
4139 for (i = 0; i < n_changes; i++) {
4140 if (changes[i].type == UNIT_FILE_SYMLINK)
4141 log_info("ln -s '%s' '%s'", changes[i].source, changes[i].path);
4143 log_info("rm '%s'", changes[i].path);
4149 bool send_force = true, expect_carries_install_info = false;
4151 DBusMessageIter iter, sub, sub2;
4153 if (streq(verb, "enable")) {
4154 method = "EnableUnitFiles";
4155 expect_carries_install_info = true;
4156 } else if (streq(verb, "disable")) {
4157 method = "DisableUnitFiles";
4159 } else if (streq(verb, "reenable")) {
4160 method = "ReenableUnitFiles";
4161 expect_carries_install_info = true;
4162 } else if (streq(verb, "link"))
4163 method = "LinkUnitFiles";
4164 else if (streq(verb, "preset")) {
4165 method = "PresetUnitFiles";
4166 expect_carries_install_info = true;
4167 } else if (streq(verb, "mask"))
4168 method = "MaskUnitFiles";
4169 else if (streq(verb, "unmask")) {
4170 method = "UnmaskUnitFiles";
4173 assert_not_reached("Unknown verb");
4175 m = dbus_message_new_method_call(
4176 "org.freedesktop.systemd1",
4177 "/org/freedesktop/systemd1",
4178 "org.freedesktop.systemd1.Manager",
4185 dbus_message_iter_init_append(m, &iter);
4187 r = bus_append_strv_iter(&iter, args+1);
4189 log_error("Failed to append unit files.");
4194 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &a)) {
4195 log_error("Failed to append runtime boolean.");
4203 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b)) {
4204 log_error("Failed to append force boolean.");
4210 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
4212 log_error("Failed to issue method call: %s", bus_error_message(&error));
4217 if (!dbus_message_iter_init(reply, &iter)) {
4218 log_error("Failed to initialize iterator.");
4222 if (expect_carries_install_info) {
4223 r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_BOOLEAN, &b, true);
4225 log_error("Failed to parse reply.");
4229 carries_install_info = b;
4232 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
4233 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
4234 log_error("Failed to parse reply.");
4239 dbus_message_iter_recurse(&iter, &sub);
4240 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
4241 const char *type, *path, *source;
4243 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
4244 log_error("Failed to parse reply.");
4249 dbus_message_iter_recurse(&sub, &sub2);
4251 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
4252 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0 ||
4253 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &source, false) < 0) {
4254 log_error("Failed to parse reply.");
4260 if (streq(type, "symlink"))
4261 log_info("ln -s '%s' '%s'", source, path);
4263 log_info("rm '%s'", path);
4266 dbus_message_iter_next(&sub);
4269 /* Try to reload if enabeld */
4271 r = daemon_reload(bus, args);
4274 if (carries_install_info == 0)
4275 log_warning("The unit files have no [Install] section. They are not meant to be enabled using systemctl.");
4279 dbus_message_unref(m);
4282 dbus_message_unref(reply);
4284 unit_file_changes_free(changes, n_changes);
4286 dbus_error_free(&error);
4290 static int unit_is_enabled(DBusConnection *bus, char **args) {
4293 DBusMessage *m = NULL, *reply = NULL;
4297 dbus_error_init(&error);
4299 r = enable_sysv_units(args);
4305 if (!bus || avoid_bus()) {
4307 STRV_FOREACH(name, args+1) {
4308 UnitFileState state;
4310 state = unit_file_get_state(arg_scope, arg_root, *name);
4316 if (state == UNIT_FILE_ENABLED ||
4317 state == UNIT_FILE_ENABLED_RUNTIME ||
4318 state == UNIT_FILE_STATIC)
4322 puts(unit_file_state_to_string(state));
4326 STRV_FOREACH(name, args+1) {
4329 m = dbus_message_new_method_call(
4330 "org.freedesktop.systemd1",
4331 "/org/freedesktop/systemd1",
4332 "org.freedesktop.systemd1.Manager",
4333 "GetUnitFileState");
4339 if (!dbus_message_append_args(m,
4340 DBUS_TYPE_STRING, name,
4341 DBUS_TYPE_INVALID)) {
4342 log_error("Could not append arguments to message.");
4347 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
4349 log_error("Failed to issue method call: %s", bus_error_message(&error));
4354 if (!dbus_message_get_args(reply, &error,
4355 DBUS_TYPE_STRING, &s,
4356 DBUS_TYPE_INVALID)) {
4357 log_error("Failed to parse reply: %s", bus_error_message(&error));
4362 dbus_message_unref(m);
4363 dbus_message_unref(reply);
4366 if (streq(s, "enabled") ||
4367 streq(s, "enabled-runtime") ||
4376 r = enabled ? 0 : 1;
4380 dbus_message_unref(m);
4383 dbus_message_unref(reply);
4385 dbus_error_free(&error);
4389 static int systemctl_help(void) {
4391 pager_open_if_enabled();
4393 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4394 "Query or send control commands to the systemd manager.\n\n"
4395 " -h --help Show this help\n"
4396 " --version Show package version\n"
4397 " -t --type=TYPE List only units of a particular type\n"
4398 " -p --property=NAME Show only properties by this name\n"
4399 " -a --all Show all units/properties, including dead/empty ones\n"
4400 " --failed Show only failed units\n"
4401 " --full Don't ellipsize unit names on output\n"
4402 " --fail When queueing a new job, fail if conflicting jobs are\n"
4404 " --ignore-dependencies\n"
4405 " When queueing a new job, ignore all its dependencies\n"
4406 " --kill-who=WHO Who to send signal to\n"
4407 " -s --signal=SIGNAL Which signal to send\n"
4408 " -H --host=[USER@]HOST\n"
4409 " Show information for remote host\n"
4410 " -P --privileged Acquire privileges before execution\n"
4411 " -q --quiet Suppress output\n"
4412 " --no-block Do not wait until operation finished\n"
4413 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4414 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4416 " --no-legend Do not print a legend (column headers and hints)\n"
4417 " --no-pager Do not pipe output into a pager\n"
4418 " --no-ask-password\n"
4419 " Do not ask for system passwords\n"
4420 " --order When generating graph for dot, show only order\n"
4421 " --require When generating graph for dot, show only requirement\n"
4422 " --system Connect to system manager\n"
4423 " --user Connect to user service manager\n"
4424 " --global Enable/disable unit files globally\n"
4425 " -f --force When enabling unit files, override existing symlinks\n"
4426 " When shutting down, execute action immediately\n"
4427 " --root=PATH Enable unit files in the specified root directory\n"
4428 " --runtime Enable unit files only temporarily until next reboot\n"
4429 " -n --lines=INTEGER Journal entries to show\n"
4430 " --follow Follow journal\n"
4431 " -o --output=STRING Change journal output mode (short, short-monotonic,\n"
4432 " verbose, export, json, cat)\n\n"
4434 " list-units List loaded units\n"
4435 " start [NAME...] Start (activate) one or more units\n"
4436 " stop [NAME...] Stop (deactivate) one or more units\n"
4437 " reload [NAME...] Reload one or more units\n"
4438 " restart [NAME...] Start or restart one or more units\n"
4439 " try-restart [NAME...] Restart one or more units if active\n"
4440 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4441 " otherwise start or restart\n"
4442 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4443 " otherwise restart if active\n"
4444 " isolate [NAME] Start one unit and stop all others\n"
4445 " kill [NAME...] Send signal to processes of a unit\n"
4446 " is-active [NAME...] Check whether units are active\n"
4447 " status [NAME...|PID...] Show runtime status of one or more units\n"
4448 " show [NAME...|JOB...] Show properties of one or more\n"
4449 " units/jobs or the manager\n"
4450 " help [NAME...|PID...] Show manual for one or more units\n"
4451 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4453 " load [NAME...] Load one or more units\n\n"
4454 "Unit File Commands:\n"
4455 " list-unit-files List installed unit files\n"
4456 " enable [NAME...] Enable one or more unit files\n"
4457 " disable [NAME...] Disable one or more unit files\n"
4458 " reenable [NAME...] Reenable one or more unit files\n"
4459 " preset [NAME...] Enable/disable one or more unit files\n"
4460 " based on preset configuration\n"
4461 " mask [NAME...] Mask one or more units\n"
4462 " unmask [NAME...] Unmask one or more units\n"
4463 " link [PATH...] Link one or more units files into\n"
4464 " the search path\n"
4465 " is-enabled [NAME...] Check whether unit files are enabled\n\n"
4467 " list-jobs List jobs\n"
4468 " cancel [JOB...] Cancel all, one, or more jobs\n\n"
4469 "Status Commands:\n"
4470 " dump Dump server status\n"
4471 " dot Dump dependency graph for dot(1)\n\n"
4472 "Snapshot Commands:\n"
4473 " snapshot [NAME] Create a snapshot\n"
4474 " delete [NAME...] Remove one or more snapshots\n\n"
4475 "Environment Commands:\n"
4476 " show-environment Dump environment\n"
4477 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4478 " unset-environment [NAME...] Unset one or more environment variables\n\n"
4479 "Manager Lifecycle Commands:\n"
4480 " daemon-reload Reload systemd manager configuration\n"
4481 " daemon-reexec Reexecute systemd manager\n\n"
4482 "System Commands:\n"
4483 " default Enter system default mode\n"
4484 " rescue Enter system rescue mode\n"
4485 " emergency Enter system emergency mode\n"
4486 " halt Shut down and halt the system\n"
4487 " poweroff Shut down and power-off the system\n"
4488 " reboot Shut down and reboot the system\n"
4489 " kexec Shut down and reboot the system with kexec\n"
4490 " exit Request user instance exit\n"
4491 " switch-root [ROOT] [INIT] Change to a different root file system\n"
4492 " suspend Suspend the system\n"
4493 " hibernate Hibernate the system\n",
4494 program_invocation_short_name);
4499 static int halt_help(void) {
4501 printf("%s [OPTIONS...]\n\n"
4502 "%s the system.\n\n"
4503 " --help Show this help\n"
4504 " --halt Halt the machine\n"
4505 " -p --poweroff Switch off the machine\n"
4506 " --reboot Reboot the machine\n"
4507 " -f --force Force immediate halt/power-off/reboot\n"
4508 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4509 " -d --no-wtmp Don't write wtmp record\n"
4510 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4511 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4512 program_invocation_short_name,
4513 arg_action == ACTION_REBOOT ? "Reboot" :
4514 arg_action == ACTION_POWEROFF ? "Power off" :
4520 static int shutdown_help(void) {
4522 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4523 "Shut down the system.\n\n"
4524 " --help Show this help\n"
4525 " -H --halt Halt the machine\n"
4526 " -P --poweroff Power-off the machine\n"
4527 " -r --reboot Reboot the machine\n"
4528 " -h Equivalent to --poweroff, overridden by --halt\n"
4529 " -k Don't halt/power-off/reboot, just send warnings\n"
4530 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4531 " -c Cancel a pending shutdown\n",
4532 program_invocation_short_name);
4537 static int telinit_help(void) {
4539 printf("%s [OPTIONS...] {COMMAND}\n\n"
4540 "Send control commands to the init daemon.\n\n"
4541 " --help Show this help\n"
4542 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4544 " 0 Power-off the machine\n"
4545 " 6 Reboot the machine\n"
4546 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4547 " 1, s, S Enter rescue mode\n"
4548 " q, Q Reload init daemon configuration\n"
4549 " u, U Reexecute init daemon\n",
4550 program_invocation_short_name);
4555 static int runlevel_help(void) {
4557 printf("%s [OPTIONS...]\n\n"
4558 "Prints the previous and current runlevel of the init system.\n\n"
4559 " --help Show this help\n",
4560 program_invocation_short_name);
4565 static int systemctl_parse_argv(int argc, char *argv[]) {
4569 ARG_IGNORE_DEPENDENCIES,
4584 ARG_NO_ASK_PASSWORD,
4591 static const struct option options[] = {
4592 { "help", no_argument, NULL, 'h' },
4593 { "version", no_argument, NULL, ARG_VERSION },
4594 { "type", required_argument, NULL, 't' },
4595 { "property", required_argument, NULL, 'p' },
4596 { "all", no_argument, NULL, 'a' },
4597 { "failed", no_argument, NULL, ARG_FAILED },
4598 { "full", no_argument, NULL, ARG_FULL },
4599 { "fail", no_argument, NULL, ARG_FAIL },
4600 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4601 { "user", no_argument, NULL, ARG_USER },
4602 { "system", no_argument, NULL, ARG_SYSTEM },
4603 { "global", no_argument, NULL, ARG_GLOBAL },
4604 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4605 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
4606 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4607 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4608 { "quiet", no_argument, NULL, 'q' },
4609 { "order", no_argument, NULL, ARG_ORDER },
4610 { "require", no_argument, NULL, ARG_REQUIRE },
4611 { "root", required_argument, NULL, ARG_ROOT },
4612 { "force", no_argument, NULL, ARG_FORCE },
4613 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4614 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4615 { "signal", required_argument, NULL, 's' },
4616 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4617 { "host", required_argument, NULL, 'H' },
4618 { "privileged",no_argument, NULL, 'P' },
4619 { "runtime", no_argument, NULL, ARG_RUNTIME },
4620 { "lines", required_argument, NULL, 'n' },
4621 { "follow", no_argument, NULL, ARG_FOLLOW },
4622 { "output", required_argument, NULL, 'o' },
4623 { NULL, 0, NULL, 0 }
4631 while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:Pn:o:", options, NULL)) >= 0) {
4640 puts(PACKAGE_STRING);
4642 puts(SYSTEMD_FEATURES);
4646 if (unit_type_from_string(optarg) >= 0) {
4650 if (unit_load_state_from_string(optarg) >= 0) {
4651 arg_load_state = optarg;
4654 log_error("Unkown unit type or load state '%s'.",
4660 if (!(l = strv_append(arg_property, optarg)))
4663 strv_free(arg_property);
4666 /* If the user asked for a particular
4667 * property, show it to him, even if it is
4678 arg_job_mode = "fail";
4681 case ARG_IGNORE_DEPENDENCIES:
4682 arg_job_mode = "ignore-dependencies";
4686 arg_scope = UNIT_FILE_USER;
4690 arg_scope = UNIT_FILE_SYSTEM;
4694 arg_scope = UNIT_FILE_GLOBAL;
4698 arg_no_block = true;
4702 arg_no_legend = true;
4706 arg_no_pager = true;
4714 arg_dot = DOT_ORDER;
4718 arg_dot = DOT_REQUIRE;
4746 /* -f is short for both --follow and --force! */
4752 arg_no_reload = true;
4756 arg_kill_who = optarg;
4760 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4761 log_error("Failed to parse signal string %s.", optarg);
4766 case ARG_NO_ASK_PASSWORD:
4767 arg_ask_password = false;
4771 arg_transport = TRANSPORT_POLKIT;
4775 arg_transport = TRANSPORT_SSH;
4784 if (safe_atou(optarg, &arg_lines) < 0) {
4785 log_error("Failed to parse lines '%s'", optarg);
4791 arg_output = output_mode_from_string(optarg);
4792 if (arg_output < 0) {
4793 log_error("Unknown output '%s'.", optarg);
4802 log_error("Unknown option code '%c'.", c);
4807 if (arg_transport != TRANSPORT_NORMAL && arg_scope != UNIT_FILE_SYSTEM) {
4808 log_error("Cannot access user instance remotely.");
4815 static int halt_parse_argv(int argc, char *argv[]) {
4824 static const struct option options[] = {
4825 { "help", no_argument, NULL, ARG_HELP },
4826 { "halt", no_argument, NULL, ARG_HALT },
4827 { "poweroff", no_argument, NULL, 'p' },
4828 { "reboot", no_argument, NULL, ARG_REBOOT },
4829 { "force", no_argument, NULL, 'f' },
4830 { "wtmp-only", no_argument, NULL, 'w' },
4831 { "no-wtmp", no_argument, NULL, 'd' },
4832 { "no-sync", no_argument, NULL, 'n' },
4833 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4834 { NULL, 0, NULL, 0 }
4842 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4843 if (runlevel == '0' || runlevel == '6')
4846 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4854 arg_action = ACTION_HALT;
4858 if (arg_action != ACTION_REBOOT)
4859 arg_action = ACTION_POWEROFF;
4863 arg_action = ACTION_REBOOT;
4888 /* Compatibility nops */
4895 log_error("Unknown option code '%c'.", c);
4900 if (optind < argc) {
4901 log_error("Too many arguments.");
4908 static int parse_time_spec(const char *t, usec_t *_u) {
4912 if (streq(t, "now"))
4914 else if (!strchr(t, ':')) {
4917 if (safe_atou64(t, &u) < 0)
4920 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4929 hour = strtol(t, &e, 10);
4930 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4933 minute = strtol(e+1, &e, 10);
4934 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4937 n = now(CLOCK_REALTIME);
4938 s = (time_t) (n / USEC_PER_SEC);
4941 assert_se(localtime_r(&s, &tm));
4943 tm.tm_hour = (int) hour;
4944 tm.tm_min = (int) minute;
4947 assert_se(s = mktime(&tm));
4949 *_u = (usec_t) s * USEC_PER_SEC;
4952 *_u += USEC_PER_DAY;
4958 static int shutdown_parse_argv(int argc, char *argv[]) {
4965 static const struct option options[] = {
4966 { "help", no_argument, NULL, ARG_HELP },
4967 { "halt", no_argument, NULL, 'H' },
4968 { "poweroff", no_argument, NULL, 'P' },
4969 { "reboot", no_argument, NULL, 'r' },
4970 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
4971 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4972 { NULL, 0, NULL, 0 }
4980 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4988 arg_action = ACTION_HALT;
4992 arg_action = ACTION_POWEROFF;
4997 arg_action = ACTION_KEXEC;
4999 arg_action = ACTION_REBOOT;
5003 arg_action = ACTION_KEXEC;
5007 if (arg_action != ACTION_HALT)
5008 arg_action = ACTION_POWEROFF;
5021 /* Compatibility nops */
5025 arg_action = ACTION_CANCEL_SHUTDOWN;
5032 log_error("Unknown option code '%c'.", c);
5037 if (argc > optind && arg_action != ACTION_CANCEL_SHUTDOWN) {
5038 r = parse_time_spec(argv[optind], &arg_when);
5040 log_error("Failed to parse time specification: %s", argv[optind]);
5044 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
5046 if (argc > optind && arg_action == ACTION_CANCEL_SHUTDOWN)
5047 /* No time argument for shutdown cancel */
5048 arg_wall = argv + optind;
5049 else if (argc > optind + 1)
5050 /* We skip the time argument */
5051 arg_wall = argv + optind + 1;
5058 static int telinit_parse_argv(int argc, char *argv[]) {
5065 static const struct option options[] = {
5066 { "help", no_argument, NULL, ARG_HELP },
5067 { "no-wall", no_argument, NULL, ARG_NO_WALL },
5068 { NULL, 0, NULL, 0 }
5071 static const struct {
5075 { '0', ACTION_POWEROFF },
5076 { '6', ACTION_REBOOT },
5077 { '1', ACTION_RESCUE },
5078 { '2', ACTION_RUNLEVEL2 },
5079 { '3', ACTION_RUNLEVEL3 },
5080 { '4', ACTION_RUNLEVEL4 },
5081 { '5', ACTION_RUNLEVEL5 },
5082 { 's', ACTION_RESCUE },
5083 { 'S', ACTION_RESCUE },
5084 { 'q', ACTION_RELOAD },
5085 { 'Q', ACTION_RELOAD },
5086 { 'u', ACTION_REEXEC },
5087 { 'U', ACTION_REEXEC }
5096 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5111 log_error("Unknown option code '%c'.", c);
5116 if (optind >= argc) {
5121 if (optind + 1 < argc) {
5122 log_error("Too many arguments.");
5126 if (strlen(argv[optind]) != 1) {
5127 log_error("Expected single character argument.");
5131 for (i = 0; i < ELEMENTSOF(table); i++)
5132 if (table[i].from == argv[optind][0])
5135 if (i >= ELEMENTSOF(table)) {
5136 log_error("Unknown command '%s'.", argv[optind]);
5140 arg_action = table[i].to;
5147 static int runlevel_parse_argv(int argc, char *argv[]) {
5153 static const struct option options[] = {
5154 { "help", no_argument, NULL, ARG_HELP },
5155 { NULL, 0, NULL, 0 }
5163 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5174 log_error("Unknown option code '%c'.", c);
5179 if (optind < argc) {
5180 log_error("Too many arguments.");
5187 static int parse_argv(int argc, char *argv[]) {
5191 if (program_invocation_short_name) {
5193 if (strstr(program_invocation_short_name, "halt")) {
5194 arg_action = ACTION_HALT;
5195 return halt_parse_argv(argc, argv);
5196 } else if (strstr(program_invocation_short_name, "poweroff")) {
5197 arg_action = ACTION_POWEROFF;
5198 return halt_parse_argv(argc, argv);
5199 } else if (strstr(program_invocation_short_name, "reboot")) {
5201 arg_action = ACTION_KEXEC;
5203 arg_action = ACTION_REBOOT;
5204 return halt_parse_argv(argc, argv);
5205 } else if (strstr(program_invocation_short_name, "shutdown")) {
5206 arg_action = ACTION_POWEROFF;
5207 return shutdown_parse_argv(argc, argv);
5208 } else if (strstr(program_invocation_short_name, "init")) {
5210 if (sd_booted() > 0) {
5211 arg_action = ACTION_INVALID;
5212 return telinit_parse_argv(argc, argv);
5214 /* Hmm, so some other init system is
5215 * running, we need to forward this
5216 * request to it. For now we simply
5217 * guess that it is Upstart. */
5219 execv("/lib/upstart/telinit", argv);
5221 log_error("Couldn't find an alternative telinit implementation to spawn.");
5225 } else if (strstr(program_invocation_short_name, "runlevel")) {
5226 arg_action = ACTION_RUNLEVEL;
5227 return runlevel_parse_argv(argc, argv);
5231 arg_action = ACTION_SYSTEMCTL;
5232 return systemctl_parse_argv(argc, argv);
5235 static int action_to_runlevel(void) {
5237 static const char table[_ACTION_MAX] = {
5238 [ACTION_HALT] = '0',
5239 [ACTION_POWEROFF] = '0',
5240 [ACTION_REBOOT] = '6',
5241 [ACTION_RUNLEVEL2] = '2',
5242 [ACTION_RUNLEVEL3] = '3',
5243 [ACTION_RUNLEVEL4] = '4',
5244 [ACTION_RUNLEVEL5] = '5',
5245 [ACTION_RESCUE] = '1'
5248 assert(arg_action < _ACTION_MAX);
5250 return table[arg_action];
5253 static int talk_upstart(void) {
5254 DBusMessage *m = NULL, *reply = NULL;
5256 int previous, rl, r;
5258 env1_buf[] = "RUNLEVEL=X",
5259 env2_buf[] = "PREVLEVEL=X";
5260 char *env1 = env1_buf, *env2 = env2_buf;
5261 const char *emit = "runlevel";
5262 dbus_bool_t b_false = FALSE;
5263 DBusMessageIter iter, sub;
5264 DBusConnection *bus;
5266 dbus_error_init(&error);
5268 if (!(rl = action_to_runlevel()))
5271 if (utmp_get_runlevel(&previous, NULL) < 0)
5274 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
5275 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
5280 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
5285 if ((r = bus_check_peercred(bus)) < 0) {
5286 log_error("Failed to verify owner of bus.");
5290 if (!(m = dbus_message_new_method_call(
5291 "com.ubuntu.Upstart",
5292 "/com/ubuntu/Upstart",
5293 "com.ubuntu.Upstart0_6",
5296 log_error("Could not allocate message.");
5301 dbus_message_iter_init_append(m, &iter);
5303 env1_buf[sizeof(env1_buf)-2] = rl;
5304 env2_buf[sizeof(env2_buf)-2] = previous;
5306 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5307 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5308 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5309 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5310 !dbus_message_iter_close_container(&iter, &sub) ||
5311 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5312 log_error("Could not append arguments to message.");
5317 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5319 if (error_is_no_service(&error)) {
5324 log_error("Failed to issue method call: %s", bus_error_message(&error));
5333 dbus_message_unref(m);
5336 dbus_message_unref(reply);
5339 dbus_connection_flush(bus);
5340 dbus_connection_close(bus);
5341 dbus_connection_unref(bus);
5344 dbus_error_free(&error);
5349 static int talk_initctl(void) {
5350 struct init_request request;
5354 if (!(rl = action_to_runlevel()))
5358 request.magic = INIT_MAGIC;
5359 request.sleeptime = 0;
5360 request.cmd = INIT_CMD_RUNLVL;
5361 request.runlevel = rl;
5363 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5365 if (errno == ENOENT)
5368 log_error("Failed to open "INIT_FIFO": %m");
5373 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5374 close_nointr_nofail(fd);
5377 log_error("Failed to write to "INIT_FIFO": %m");
5378 return errno ? -errno : -EIO;
5384 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5386 static const struct {
5394 int (* const dispatch)(DBusConnection *bus, char **args);
5396 { "list-units", LESS, 1, list_units },
5397 { "list-unit-files", EQUAL, 1, list_unit_files },
5398 { "list-jobs", EQUAL, 1, list_jobs },
5399 { "clear-jobs", EQUAL, 1, daemon_reload },
5400 { "load", MORE, 2, load_unit },
5401 { "cancel", MORE, 2, cancel_job },
5402 { "start", MORE, 2, start_unit },
5403 { "stop", MORE, 2, start_unit },
5404 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5405 { "reload", MORE, 2, start_unit },
5406 { "restart", MORE, 2, start_unit },
5407 { "try-restart", MORE, 2, start_unit },
5408 { "reload-or-restart", MORE, 2, start_unit },
5409 { "reload-or-try-restart", MORE, 2, start_unit },
5410 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5411 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5412 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5413 { "isolate", EQUAL, 2, start_unit },
5414 { "kill", MORE, 2, kill_unit },
5415 { "is-active", MORE, 2, check_unit },
5416 { "check", MORE, 2, check_unit },
5417 { "show", MORE, 1, show },
5418 { "status", MORE, 2, show },
5419 { "help", MORE, 2, show },
5420 { "dump", EQUAL, 1, dump },
5421 { "dot", EQUAL, 1, dot },
5422 { "snapshot", LESS, 2, snapshot },
5423 { "delete", MORE, 2, delete_snapshot },
5424 { "daemon-reload", EQUAL, 1, daemon_reload },
5425 { "daemon-reexec", EQUAL, 1, daemon_reload },
5426 { "show-environment", EQUAL, 1, show_enviroment },
5427 { "set-environment", MORE, 2, set_environment },
5428 { "unset-environment", MORE, 2, set_environment },
5429 { "halt", EQUAL, 1, start_special },
5430 { "poweroff", EQUAL, 1, start_special },
5431 { "reboot", EQUAL, 1, start_special },
5432 { "kexec", EQUAL, 1, start_special },
5433 { "suspend", EQUAL, 1, start_special },
5434 { "hibernate", EQUAL, 1, start_special },
5435 { "default", EQUAL, 1, start_special },
5436 { "rescue", EQUAL, 1, start_special },
5437 { "emergency", EQUAL, 1, start_special },
5438 { "exit", EQUAL, 1, start_special },
5439 { "reset-failed", MORE, 1, reset_failed },
5440 { "enable", MORE, 2, enable_unit },
5441 { "disable", MORE, 2, enable_unit },
5442 { "is-enabled", MORE, 2, unit_is_enabled },
5443 { "reenable", MORE, 2, enable_unit },
5444 { "preset", MORE, 2, enable_unit },
5445 { "mask", MORE, 2, enable_unit },
5446 { "unmask", MORE, 2, enable_unit },
5447 { "link", MORE, 2, enable_unit },
5448 { "switch-root", MORE, 2, switch_root },
5458 left = argc - optind;
5461 /* Special rule: no arguments means "list-units" */
5464 if (streq(argv[optind], "help") && !argv[optind+1]) {
5465 log_error("This command expects one or more "
5466 "unit names. Did you mean --help?");
5470 for (i = 0; i < ELEMENTSOF(verbs); i++)
5471 if (streq(argv[optind], verbs[i].verb))
5474 if (i >= ELEMENTSOF(verbs)) {
5475 log_error("Unknown operation '%s'.", argv[optind]);
5480 switch (verbs[i].argc_cmp) {
5483 if (left != verbs[i].argc) {
5484 log_error("Invalid number of arguments.");
5491 if (left < verbs[i].argc) {
5492 log_error("Too few arguments.");
5499 if (left > verbs[i].argc) {
5500 log_error("Too many arguments.");
5507 assert_not_reached("Unknown comparison operator.");
5510 /* Require a bus connection for all operations but
5512 if (!streq(verbs[i].verb, "enable") &&
5513 !streq(verbs[i].verb, "disable") &&
5514 !streq(verbs[i].verb, "is-enabled") &&
5515 !streq(verbs[i].verb, "list-unit-files") &&
5516 !streq(verbs[i].verb, "reenable") &&
5517 !streq(verbs[i].verb, "preset") &&
5518 !streq(verbs[i].verb, "mask") &&
5519 !streq(verbs[i].verb, "unmask") &&
5520 !streq(verbs[i].verb, "link")) {
5522 if (running_in_chroot() > 0) {
5523 log_info("Running in chroot, ignoring request.");
5527 if (((!streq(verbs[i].verb, "reboot") &&
5528 !streq(verbs[i].verb, "halt") &&
5529 !streq(verbs[i].verb, "poweroff")) || arg_force <= 0) && !bus) {
5530 log_error("Failed to get D-Bus connection: %s",
5531 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5537 if (!bus && !avoid_bus()) {
5538 log_error("Failed to get D-Bus connection: %s",
5539 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5544 return verbs[i].dispatch(bus, argv + optind);
5547 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
5549 struct msghdr msghdr;
5550 struct iovec iovec[2];
5551 union sockaddr_union sockaddr;
5552 struct sd_shutdown_command c;
5554 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
5561 c.dry_run = dry_run;
5565 sockaddr.sa.sa_family = AF_UNIX;
5566 strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5569 msghdr.msg_name = &sockaddr;
5570 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5573 iovec[0].iov_base = (char*) &c;
5574 iovec[0].iov_len = offsetof(struct sd_shutdown_command, wall_message);
5576 if (isempty(message))
5577 msghdr.msg_iovlen = 1;
5579 iovec[1].iov_base = (char*) message;
5580 iovec[1].iov_len = strlen(message);
5581 msghdr.msg_iovlen = 2;
5583 msghdr.msg_iov = iovec;
5585 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5586 close_nointr_nofail(fd);
5590 close_nointr_nofail(fd);
5594 static int reload_with_fallback(DBusConnection *bus) {
5597 /* First, try systemd via D-Bus. */
5598 if (daemon_reload(bus, NULL) >= 0)
5602 /* Nothing else worked, so let's try signals */
5603 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5605 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5606 log_error("kill() failed: %m");
5613 static int start_with_fallback(DBusConnection *bus) {
5616 /* First, try systemd via D-Bus. */
5617 if (start_unit(bus, NULL) >= 0)
5621 /* Hmm, talking to systemd via D-Bus didn't work. Then
5622 * let's try to talk to Upstart via D-Bus. */
5623 if (talk_upstart() > 0)
5626 /* Nothing else worked, so let's try
5628 if (talk_initctl() > 0)
5631 log_error("Failed to talk to init daemon.");
5635 warn_wall(arg_action);
5639 static _noreturn_ void halt_now(enum action a) {
5641 /* Make sure C-A-D is handled by the kernel from this
5643 reboot(RB_ENABLE_CAD);
5648 log_info("Halting.");
5649 reboot(RB_HALT_SYSTEM);
5652 case ACTION_POWEROFF:
5653 log_info("Powering off.");
5654 reboot(RB_POWER_OFF);
5658 log_info("Rebooting.");
5659 reboot(RB_AUTOBOOT);
5663 assert_not_reached("Unknown halt action.");
5666 assert_not_reached("Uh? This shouldn't happen.");
5669 static int halt_main(DBusConnection *bus) {
5672 if (geteuid() != 0) {
5673 /* Try logind if we are a normal user and no special
5674 * mode applies. Maybe PolicyKit allows us to shutdown
5677 if (arg_when <= 0 &&
5680 (arg_action == ACTION_POWEROFF ||
5681 arg_action == ACTION_REBOOT)) {
5682 r = reboot_with_logind(bus, arg_action);
5687 log_error("Must be root.");
5694 m = strv_join(arg_wall, " ");
5695 r = send_shutdownd(arg_when,
5696 arg_action == ACTION_HALT ? 'H' :
5697 arg_action == ACTION_POWEROFF ? 'P' :
5698 arg_action == ACTION_KEXEC ? 'K' :
5706 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5708 char date[FORMAT_TIMESTAMP_MAX];
5710 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5711 format_timestamp(date, sizeof(date), arg_when));
5716 if (!arg_dry && !arg_force)
5717 return start_with_fallback(bus);
5720 if (sd_booted() > 0)
5721 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5723 r = utmp_put_shutdown();
5725 log_warning("Failed to write utmp record: %s", strerror(-r));
5735 halt_now(arg_action);
5736 /* We should never reach this. */
5740 static int runlevel_main(void) {
5741 int r, runlevel, previous;
5743 r = utmp_get_runlevel(&runlevel, &previous);
5750 previous <= 0 ? 'N' : previous,
5751 runlevel <= 0 ? 'N' : runlevel);
5756 int main(int argc, char*argv[]) {
5757 int r, retval = EXIT_FAILURE;
5758 DBusConnection *bus = NULL;
5761 dbus_error_init(&error);
5763 log_parse_environment();
5766 r = parse_argv(argc, argv);
5770 retval = EXIT_SUCCESS;
5774 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5775 * let's shortcut this */
5776 if (arg_action == ACTION_RUNLEVEL) {
5777 r = runlevel_main();
5778 retval = r < 0 ? EXIT_FAILURE : r;
5782 if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5783 log_info("Running in chroot, ignoring request.");
5789 if (arg_transport == TRANSPORT_NORMAL)
5790 bus_connect(arg_scope == UNIT_FILE_SYSTEM ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, &bus, &private_bus, &error);
5791 else if (arg_transport == TRANSPORT_POLKIT) {
5792 bus_connect_system_polkit(&bus, &error);
5793 private_bus = false;
5794 } else if (arg_transport == TRANSPORT_SSH) {
5795 bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5796 private_bus = false;
5798 assert_not_reached("Uh, invalid transport...");
5801 switch (arg_action) {
5803 case ACTION_SYSTEMCTL:
5804 r = systemctl_main(bus, argc, argv, &error);
5808 case ACTION_POWEROFF:
5814 case ACTION_RUNLEVEL2:
5815 case ACTION_RUNLEVEL3:
5816 case ACTION_RUNLEVEL4:
5817 case ACTION_RUNLEVEL5:
5819 case ACTION_EMERGENCY:
5820 case ACTION_DEFAULT:
5821 r = start_with_fallback(bus);
5826 r = reload_with_fallback(bus);
5829 case ACTION_CANCEL_SHUTDOWN: {
5833 m = strv_join(arg_wall, " ");
5835 retval = EXIT_FAILURE;
5839 r = send_shutdownd(arg_when, SD_SHUTDOWN_NONE, false, !arg_no_wall, m);
5841 log_warning("Failed to talk to shutdownd, shutdown hasn't been cancelled: %s", strerror(-r));
5846 case ACTION_INVALID:
5847 case ACTION_RUNLEVEL:
5849 assert_not_reached("Unknown action");
5852 retval = r < 0 ? EXIT_FAILURE : r;
5856 dbus_connection_flush(bus);
5857 dbus_connection_close(bus);
5858 dbus_connection_unref(bus);
5861 dbus_error_free(&error);
5865 strv_free(arg_property);
5868 ask_password_agent_close();
5869 polkit_agent_close();