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 char **arg_property = NULL;
69 static bool arg_all = false;
70 static const char *arg_job_mode = "replace";
71 static UnitFileScope arg_scope = UNIT_FILE_SYSTEM;
72 static bool arg_no_block = false;
73 static bool arg_no_legend = false;
74 static bool arg_no_pager = false;
75 static bool arg_no_wtmp = false;
76 static bool arg_no_sync = false;
77 static bool arg_no_wall = false;
78 static bool arg_no_reload = false;
79 static bool arg_dry = false;
80 static bool arg_quiet = false;
81 static bool arg_full = false;
82 static int arg_force = 0;
83 static bool arg_ask_password = true;
84 static bool arg_failed = false;
85 static bool arg_runtime = false;
86 static char **arg_wall = NULL;
87 static const char *arg_kill_who = NULL;
88 static const char *arg_kill_mode = 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!"
264 p = strv_join(arg_wall, " ");
266 log_error("Failed to join strings.");
282 utmp_wall(table[a], NULL);
285 static bool avoid_bus(void) {
287 if (running_in_chroot() > 0)
290 if (sd_booted() <= 0)
293 if (!isempty(arg_root))
296 if (arg_scope == UNIT_FILE_GLOBAL)
304 const char *description;
305 const char *load_state;
306 const char *active_state;
307 const char *sub_state;
308 const char *following;
309 const char *unit_path;
311 const char *job_type;
312 const char *job_path;
315 static int compare_unit_info(const void *a, const void *b) {
317 const struct unit_info *u = a, *v = b;
319 d1 = strrchr(u->id, '.');
320 d2 = strrchr(v->id, '.');
325 if ((r = strcasecmp(d1, d2)) != 0)
329 return strcasecmp(u->id, v->id);
332 static bool output_show_unit(const struct unit_info *u) {
336 return streq(u->active_state, "failed");
338 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
339 streq(dot+1, arg_type))) &&
340 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0);
343 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
344 unsigned id_len, max_id_len, active_len, sub_len, job_len, desc_len, n_shown = 0;
345 const struct unit_info *u;
347 max_id_len = sizeof("UNIT")-1;
348 active_len = sizeof("ACTIVE")-1;
349 sub_len = sizeof("SUB")-1;
350 job_len = sizeof("JOB")-1;
353 for (u = unit_infos; u < unit_infos + c; u++) {
354 if (!output_show_unit(u))
357 max_id_len = MAX(max_id_len, strlen(u->id));
358 active_len = MAX(active_len, strlen(u->active_state));
359 sub_len = MAX(sub_len, strlen(u->sub_state));
361 job_len = MAX(job_len, strlen(u->job_type));
366 id_len = MIN(max_id_len, 25);
367 basic_len = 5 + id_len + 6 + active_len + sub_len + job_len;
368 if (basic_len < (unsigned) columns()) {
369 unsigned extra_len, incr;
370 extra_len = columns() - basic_len;
371 /* Either UNIT already got 25, or is fully satisfied.
372 * Grant up to 25 to DESC now. */
373 incr = MIN(extra_len, 25);
376 /* split the remaining space between UNIT and DESC,
377 * but do not give UNIT more than it needs. */
379 incr = MIN(extra_len / 2, max_id_len - id_len);
381 desc_len += extra_len - incr;
387 if (!arg_no_legend) {
388 printf("%-*s %-6s %-*s %-*s %-*s ", id_len, "UNIT", "LOAD",
389 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
390 if (!arg_full && arg_no_pager)
391 printf("%.*s\n", desc_len, "DESCRIPTION");
393 printf("%s\n", "DESCRIPTION");
396 for (u = unit_infos; u < unit_infos + c; u++) {
398 const char *on_loaded, *off_loaded;
399 const char *on_active, *off_active;
401 if (!output_show_unit(u))
406 if (streq(u->load_state, "error")) {
407 on_loaded = ansi_highlight_red(true);
408 off_loaded = ansi_highlight_red(false);
410 on_loaded = off_loaded = "";
412 if (streq(u->active_state, "failed")) {
413 on_active = ansi_highlight_red(true);
414 off_active = ansi_highlight_red(false);
416 on_active = off_active = "";
418 e = arg_full ? NULL : ellipsize(u->id, id_len, 33);
420 printf("%-*s %s%-6s%s %s%-*s %-*s%s %-*s ",
421 id_len, e ? e : u->id,
422 on_loaded, u->load_state, off_loaded,
423 on_active, active_len, u->active_state,
424 sub_len, u->sub_state, off_active,
425 job_len, u->job_id ? u->job_type : "");
426 if (!arg_full && arg_no_pager)
427 printf("%.*s\n", desc_len, u->description);
429 printf("%s\n", u->description);
434 if (!arg_no_legend) {
435 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
436 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
437 "SUB = The low-level unit activation state, values depend on unit type.\n"
438 "JOB = Pending job for the unit.\n");
441 printf("\n%u units listed.\n", n_shown);
443 printf("\n%u units listed. Pass --all to see inactive units, too.\n", n_shown);
447 static int list_units(DBusConnection *bus, char **args) {
448 DBusMessage *m = NULL, *reply = NULL;
451 DBusMessageIter iter, sub, sub2;
452 unsigned c = 0, n_units = 0;
453 struct unit_info *unit_infos = NULL;
455 dbus_error_init(&error);
459 pager_open_if_enabled();
461 if (!(m = dbus_message_new_method_call(
462 "org.freedesktop.systemd1",
463 "/org/freedesktop/systemd1",
464 "org.freedesktop.systemd1.Manager",
466 log_error("Could not allocate message.");
470 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
471 log_error("Failed to issue method call: %s", bus_error_message(&error));
476 if (!dbus_message_iter_init(reply, &iter) ||
477 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
478 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
479 log_error("Failed to parse reply.");
484 dbus_message_iter_recurse(&iter, &sub);
486 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
489 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
490 log_error("Failed to parse reply.");
498 n_units = MAX(2*c, 16);
499 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
502 log_error("Failed to allocate unit array.");
512 dbus_message_iter_recurse(&sub, &sub2);
514 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
515 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
516 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
517 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
518 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
519 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
520 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
521 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
522 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
523 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
524 log_error("Failed to parse reply.");
529 dbus_message_iter_next(&sub);
534 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
535 output_units_list(unit_infos, c);
542 dbus_message_unref(m);
545 dbus_message_unref(reply);
549 dbus_error_free(&error);
554 static int compare_unit_file_list(const void *a, const void *b) {
556 const UnitFileList *u = a, *v = b;
558 d1 = strrchr(u->path, '.');
559 d2 = strrchr(v->path, '.');
564 r = strcasecmp(d1, d2);
569 return strcasecmp(path_get_file_name(u->path), path_get_file_name(v->path));
572 static bool output_show_unit_file(const UnitFileList *u) {
575 return !arg_type || ((dot = strrchr(u->path, '.')) && streq(dot+1, arg_type));
578 static void output_unit_file_list(const UnitFileList *units, unsigned c) {
579 unsigned max_id_len, id_cols, state_cols, n_shown = 0;
580 const UnitFileList *u;
582 max_id_len = sizeof("UNIT FILE")-1;
583 state_cols = sizeof("STATE")-1;
584 for (u = units; u < units + c; u++) {
585 if (!output_show_unit_file(u))
588 max_id_len = MAX(max_id_len, strlen(path_get_file_name(u->path)));
589 state_cols = MAX(state_cols, strlen(unit_file_state_to_string(u->state)));
594 id_cols = MIN(max_id_len, 25);
595 basic_cols = 1 + id_cols + state_cols;
596 if (basic_cols < (unsigned) columns())
597 id_cols += MIN(columns() - basic_cols, max_id_len - id_cols);
599 id_cols = max_id_len;
602 printf("%-*s %-*s\n", id_cols, "UNIT FILE", state_cols, "STATE");
604 for (u = units; u < units + c; u++) {
606 const char *on, *off;
609 if (!output_show_unit_file(u))
614 if (u->state == UNIT_FILE_MASKED ||
615 u->state == UNIT_FILE_MASKED_RUNTIME ||
616 u->state == UNIT_FILE_DISABLED) {
617 on = ansi_highlight_red(true);
618 off = ansi_highlight_red(false);
619 } else if (u->state == UNIT_FILE_ENABLED) {
620 on = ansi_highlight_green(true);
621 off = ansi_highlight_green(false);
625 id = path_get_file_name(u->path);
627 e = arg_full ? NULL : ellipsize(id, id_cols, 33);
629 printf("%-*s %s%-*s%s\n",
631 on, state_cols, unit_file_state_to_string(u->state), off);
637 printf("\n%u unit files listed.\n", n_shown);
640 static int list_unit_files(DBusConnection *bus, char **args) {
641 DBusMessage *m = NULL, *reply = NULL;
644 DBusMessageIter iter, sub, sub2;
645 unsigned c = 0, n_units = 0;
646 UnitFileList *units = NULL;
648 dbus_error_init(&error);
650 pager_open_if_enabled();
657 h = hashmap_new(string_hash_func, string_compare_func);
659 log_error("Out of memory");
663 r = unit_file_get_list(arg_scope, arg_root, h);
665 unit_file_list_free(h);
666 log_error("Failed to get unit file list: %s", strerror(-r));
670 n_units = hashmap_size(h);
671 units = new(UnitFileList, n_units);
673 unit_file_list_free(h);
674 log_error("Out of memory");
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=\"darkgrey\"]",
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";
2141 arg_kill_mode = streq(arg_kill_who, "all") ? "control-group" : "process";
2143 STRV_FOREACH(name, args+1) {
2148 m = dbus_message_new_method_call(
2149 "org.freedesktop.systemd1",
2150 "/org/freedesktop/systemd1",
2151 "org.freedesktop.systemd1.Manager",
2154 log_error("Could not allocate message.");
2159 n = unit_name_mangle(*name);
2160 b = dbus_message_append_args(m,
2161 DBUS_TYPE_STRING, n ? &n : name,
2162 DBUS_TYPE_STRING, &arg_kill_who,
2163 DBUS_TYPE_STRING, &arg_kill_mode,
2164 DBUS_TYPE_INT32, &arg_signal,
2168 log_error("Could not append arguments to message.");
2173 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
2175 log_error("Failed to issue method call: %s", bus_error_message(&error));
2176 dbus_error_free(&error);
2180 dbus_message_unref(m);
2183 dbus_message_unref(reply);
2189 dbus_message_unref(m);
2191 dbus_error_free(&error);
2196 typedef struct ExecStatusInfo {
2204 usec_t start_timestamp;
2205 usec_t exit_timestamp;
2210 LIST_FIELDS(struct ExecStatusInfo, exec);
2213 static void exec_status_info_free(ExecStatusInfo *i) {
2222 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
2223 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
2224 DBusMessageIter sub2, sub3;
2228 int32_t code, status;
2234 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
2237 dbus_message_iter_recurse(sub, &sub2);
2239 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
2242 if (!(i->path = strdup(path)))
2245 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
2246 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
2250 dbus_message_iter_recurse(&sub2, &sub3);
2251 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
2252 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
2253 dbus_message_iter_next(&sub3);
2258 if (!(i->argv = new0(char*, n+1)))
2262 dbus_message_iter_recurse(&sub2, &sub3);
2263 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
2266 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
2267 dbus_message_iter_get_basic(&sub3, &s);
2268 dbus_message_iter_next(&sub3);
2270 if (!(i->argv[n++] = strdup(s)))
2274 if (!dbus_message_iter_next(&sub2) ||
2275 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
2276 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
2277 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
2278 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
2279 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
2280 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
2281 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
2282 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
2286 i->start_timestamp = (usec_t) start_timestamp;
2287 i->exit_timestamp = (usec_t) exit_timestamp;
2288 i->pid = (pid_t) pid;
2295 typedef struct UnitStatusInfo {
2297 const char *load_state;
2298 const char *active_state;
2299 const char *sub_state;
2300 const char *unit_file_state;
2302 const char *description;
2303 const char *following;
2305 char **documentation;
2307 const char *fragment_path;
2308 const char *source_path;
2309 const char *default_control_group;
2311 const char *load_error;
2314 usec_t inactive_exit_timestamp;
2315 usec_t inactive_exit_timestamp_monotonic;
2316 usec_t active_enter_timestamp;
2317 usec_t active_exit_timestamp;
2318 usec_t inactive_enter_timestamp;
2320 bool need_daemon_reload;
2325 const char *status_text;
2328 usec_t start_timestamp;
2329 usec_t exit_timestamp;
2331 int exit_code, exit_status;
2333 usec_t condition_timestamp;
2334 bool condition_result;
2337 unsigned n_accepted;
2338 unsigned n_connections;
2342 const char *sysfs_path;
2344 /* Mount, Automount */
2350 LIST_HEAD(ExecStatusInfo, exec);
2353 static void print_status_info(UnitStatusInfo *i) {
2355 const char *on, *off, *ss;
2357 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
2358 char since2[FORMAT_TIMESTAMP_MAX], *s2;
2363 /* This shows pretty information about a unit. See
2364 * print_property() for a low-level property printer */
2366 printf("%s", strna(i->id));
2368 if (i->description && !streq_ptr(i->id, i->description))
2369 printf(" - %s", i->description);
2374 printf("\t Follow: unit currently follows state of %s\n", i->following);
2376 if (streq_ptr(i->load_state, "error")) {
2377 on = ansi_highlight_red(true);
2378 off = ansi_highlight_red(false);
2382 path = i->source_path ? i->source_path : i->fragment_path;
2385 printf("\t Loaded: %s%s%s (Reason: %s)\n", on, strna(i->load_state), off, i->load_error);
2386 else if (path && i->unit_file_state)
2387 printf("\t Loaded: %s%s%s (%s; %s)\n", on, strna(i->load_state), off, path, i->unit_file_state);
2389 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, path);
2391 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
2393 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
2395 if (streq_ptr(i->active_state, "failed")) {
2396 on = ansi_highlight_red(true);
2397 off = ansi_highlight_red(false);
2398 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
2399 on = ansi_highlight_green(true);
2400 off = ansi_highlight_green(false);
2405 printf("\t Active: %s%s (%s)%s",
2407 strna(i->active_state),
2411 printf("\t Active: %s%s%s",
2413 strna(i->active_state),
2416 if (!isempty(i->result) && !streq(i->result, "success"))
2417 printf(" (Result: %s)", i->result);
2419 timestamp = (streq_ptr(i->active_state, "active") ||
2420 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
2421 (streq_ptr(i->active_state, "inactive") ||
2422 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
2423 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
2424 i->active_exit_timestamp;
2426 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
2427 s2 = format_timestamp(since2, sizeof(since2), timestamp);
2430 printf(" since %s; %s\n", s2, s1);
2432 printf(" since %s\n", s2);
2436 if (!i->condition_result && i->condition_timestamp > 0) {
2437 s1 = format_timestamp_pretty(since1, sizeof(since1), i->condition_timestamp);
2438 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
2441 printf("\t start condition failed at %s; %s\n", s2, s1);
2443 printf("\t start condition failed at %s\n", s2);
2447 printf("\t Device: %s\n", i->sysfs_path);
2449 printf("\t Where: %s\n", i->where);
2451 printf("\t What: %s\n", i->what);
2453 if (!strv_isempty(i->documentation)) {
2457 STRV_FOREACH(t, i->documentation) {
2459 printf("\t Docs: %s\n", *t);
2462 printf("\t %s\n", *t);
2467 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
2469 LIST_FOREACH(exec, p, i->exec) {
2473 /* Only show exited processes here */
2477 t = strv_join(p->argv, " ");
2478 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
2481 good = is_clean_exit_lsb(p->code, p->status);
2483 on = ansi_highlight_red(true);
2484 off = ansi_highlight_red(false);
2488 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
2490 if (p->code == CLD_EXITED) {
2493 printf("status=%i", p->status);
2495 c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD);
2500 printf("signal=%s", signal_to_string(p->status));
2502 printf(")%s\n", off);
2504 if (i->main_pid == p->pid &&
2505 i->start_timestamp == p->start_timestamp &&
2506 i->exit_timestamp == p->start_timestamp)
2507 /* Let's not show this twice */
2510 if (p->pid == i->control_pid)
2514 if (i->main_pid > 0 || i->control_pid > 0) {
2517 if (i->main_pid > 0) {
2518 printf("Main PID: %u", (unsigned) i->main_pid);
2522 get_process_comm(i->main_pid, &t);
2527 } else if (i->exit_code > 0) {
2528 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2530 if (i->exit_code == CLD_EXITED) {
2533 printf("status=%i", i->exit_status);
2535 c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD);
2540 printf("signal=%s", signal_to_string(i->exit_status));
2545 if (i->main_pid > 0 && i->control_pid > 0)
2548 if (i->control_pid > 0) {
2551 printf(" Control: %u", (unsigned) i->control_pid);
2553 get_process_comm(i->control_pid, &t);
2564 printf("\t Status: \"%s\"\n", i->status_text);
2566 if (i->default_control_group) {
2569 printf("\t CGroup: %s\n", i->default_control_group);
2571 if (arg_transport != TRANSPORT_SSH) {
2581 if (i->main_pid > 0)
2582 extra[k++] = i->main_pid;
2584 if (i->control_pid > 0)
2585 extra[k++] = i->control_pid;
2587 show_cgroup_and_extra_by_spec(i->default_control_group, "\t\t ", c, false, arg_all, extra, k);
2591 if (i->id && arg_transport != TRANSPORT_SSH) {
2593 show_journal_by_unit(i->id, arg_output, 0, i->inactive_exit_timestamp_monotonic, arg_lines, arg_all, arg_follow, !arg_quiet);
2596 if (i->need_daemon_reload)
2597 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2598 ansi_highlight_red(true),
2599 ansi_highlight_red(false),
2600 arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
2603 static void show_unit_help(UnitStatusInfo *i) {
2608 if (!i->documentation) {
2609 log_info("Documentation for %s not known.", i->id);
2613 STRV_FOREACH(p, i->documentation) {
2615 if (startswith(*p, "man:")) {
2618 char *page = NULL, *section = NULL;
2619 const char *args[4] = { "man", NULL, NULL, NULL };
2624 if ((*p)[k-1] == ')')
2625 e = strrchr(*p, '(');
2628 page = strndup((*p) + 4, e - *p - 4);
2630 log_error("Out of memory.");
2634 section = strndup(e + 1, *p + k - e - 2);
2637 log_error("Out of memory");
2648 log_error("Failed to fork: %m");
2656 execvp(args[0], (char**) args);
2657 log_error("Failed to execute man: %m");
2658 _exit(EXIT_FAILURE);
2664 wait_for_terminate(pid, NULL);
2666 log_info("Can't show: %s", *p);
2670 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2676 switch (dbus_message_iter_get_arg_type(iter)) {
2678 case DBUS_TYPE_STRING: {
2681 dbus_message_iter_get_basic(iter, &s);
2684 if (streq(name, "Id"))
2686 else if (streq(name, "LoadState"))
2688 else if (streq(name, "ActiveState"))
2689 i->active_state = s;
2690 else if (streq(name, "SubState"))
2692 else if (streq(name, "Description"))
2694 else if (streq(name, "FragmentPath"))
2695 i->fragment_path = s;
2696 else if (streq(name, "SourcePath"))
2698 else if (streq(name, "DefaultControlGroup"))
2699 i->default_control_group = s;
2700 else if (streq(name, "StatusText"))
2702 else if (streq(name, "SysFSPath"))
2704 else if (streq(name, "Where"))
2706 else if (streq(name, "What"))
2708 else if (streq(name, "Following"))
2710 else if (streq(name, "UnitFileState"))
2711 i->unit_file_state = s;
2712 else if (streq(name, "Result"))
2719 case DBUS_TYPE_BOOLEAN: {
2722 dbus_message_iter_get_basic(iter, &b);
2724 if (streq(name, "Accept"))
2726 else if (streq(name, "NeedDaemonReload"))
2727 i->need_daemon_reload = b;
2728 else if (streq(name, "ConditionResult"))
2729 i->condition_result = b;
2734 case DBUS_TYPE_UINT32: {
2737 dbus_message_iter_get_basic(iter, &u);
2739 if (streq(name, "MainPID")) {
2741 i->main_pid = (pid_t) u;
2744 } else if (streq(name, "ControlPID"))
2745 i->control_pid = (pid_t) u;
2746 else if (streq(name, "ExecMainPID")) {
2748 i->main_pid = (pid_t) u;
2749 } else if (streq(name, "NAccepted"))
2751 else if (streq(name, "NConnections"))
2752 i->n_connections = u;
2757 case DBUS_TYPE_INT32: {
2760 dbus_message_iter_get_basic(iter, &j);
2762 if (streq(name, "ExecMainCode"))
2763 i->exit_code = (int) j;
2764 else if (streq(name, "ExecMainStatus"))
2765 i->exit_status = (int) j;
2770 case DBUS_TYPE_UINT64: {
2773 dbus_message_iter_get_basic(iter, &u);
2775 if (streq(name, "ExecMainStartTimestamp"))
2776 i->start_timestamp = (usec_t) u;
2777 else if (streq(name, "ExecMainExitTimestamp"))
2778 i->exit_timestamp = (usec_t) u;
2779 else if (streq(name, "ActiveEnterTimestamp"))
2780 i->active_enter_timestamp = (usec_t) u;
2781 else if (streq(name, "InactiveEnterTimestamp"))
2782 i->inactive_enter_timestamp = (usec_t) u;
2783 else if (streq(name, "InactiveExitTimestamp"))
2784 i->inactive_exit_timestamp = (usec_t) u;
2785 else if (streq(name, "InactiveExitTimestampMonotonic"))
2786 i->inactive_exit_timestamp_monotonic = (usec_t) u;
2787 else if (streq(name, "ActiveExitTimestamp"))
2788 i->active_exit_timestamp = (usec_t) u;
2789 else if (streq(name, "ConditionTimestamp"))
2790 i->condition_timestamp = (usec_t) u;
2795 case DBUS_TYPE_ARRAY: {
2797 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2798 startswith(name, "Exec")) {
2799 DBusMessageIter sub;
2801 dbus_message_iter_recurse(iter, &sub);
2802 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2803 ExecStatusInfo *info;
2806 if (!(info = new0(ExecStatusInfo, 1)))
2809 if (!(info->name = strdup(name))) {
2814 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2819 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2821 dbus_message_iter_next(&sub);
2823 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING &&
2824 streq(name, "Documentation")) {
2826 DBusMessageIter sub;
2828 dbus_message_iter_recurse(iter, &sub);
2829 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING) {
2833 dbus_message_iter_get_basic(&sub, &s);
2835 l = strv_append(i->documentation, s);
2839 strv_free(i->documentation);
2840 i->documentation = l;
2842 dbus_message_iter_next(&sub);
2849 case DBUS_TYPE_STRUCT: {
2851 if (streq(name, "LoadError")) {
2852 DBusMessageIter sub;
2853 const char *n, *message;
2856 dbus_message_iter_recurse(iter, &sub);
2858 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &n, true);
2862 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &message, false);
2866 if (!isempty(message))
2867 i->load_error = message;
2877 static int print_property(const char *name, DBusMessageIter *iter) {
2881 /* This is a low-level property printer, see
2882 * print_status_info() for the nicer output */
2884 if (arg_property && !strv_find(arg_property, name))
2887 switch (dbus_message_iter_get_arg_type(iter)) {
2889 case DBUS_TYPE_STRUCT: {
2890 DBusMessageIter sub;
2891 dbus_message_iter_recurse(iter, &sub);
2893 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2896 dbus_message_iter_get_basic(&sub, &u);
2899 printf("%s=%u\n", name, (unsigned) u);
2901 printf("%s=\n", name);
2904 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2907 dbus_message_iter_get_basic(&sub, &s);
2909 if (arg_all || s[0])
2910 printf("%s=%s\n", name, s);
2913 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "LoadError")) {
2914 const char *a = NULL, *b = NULL;
2916 if (bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &a, true) >= 0)
2917 bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &b, false);
2919 if (arg_all || !isempty(a) || !isempty(b))
2920 printf("%s=%s \"%s\"\n", name, strempty(a), strempty(b));
2928 case DBUS_TYPE_ARRAY:
2930 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
2931 DBusMessageIter sub, sub2;
2933 dbus_message_iter_recurse(iter, &sub);
2934 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2938 dbus_message_iter_recurse(&sub, &sub2);
2940 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
2941 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
2942 printf("EnvironmentFile=%s (ignore_errors=%s)\n", path, yes_no(ignore));
2944 dbus_message_iter_next(&sub);
2949 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2950 DBusMessageIter sub, sub2;
2952 dbus_message_iter_recurse(iter, &sub);
2953 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2954 const char *type, *path;
2956 dbus_message_iter_recurse(&sub, &sub2);
2958 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2959 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2960 printf("%s=%s\n", type, path);
2962 dbus_message_iter_next(&sub);
2967 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2968 DBusMessageIter sub, sub2;
2970 dbus_message_iter_recurse(iter, &sub);
2971 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2973 uint64_t value, next_elapse;
2975 dbus_message_iter_recurse(&sub, &sub2);
2977 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2978 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2979 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2980 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2982 printf("%s={ value=%s ; next_elapse=%s }\n",
2984 format_timespan(timespan1, sizeof(timespan1), value),
2985 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2988 dbus_message_iter_next(&sub);
2993 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "ControlGroupAttributes")) {
2994 DBusMessageIter sub, sub2;
2996 dbus_message_iter_recurse(iter, &sub);
2997 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2998 const char *controller, *attr, *value;
3000 dbus_message_iter_recurse(&sub, &sub2);
3002 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &controller, true) >= 0 &&
3003 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &attr, true) >= 0 &&
3004 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &value, false) >= 0) {
3006 printf("ControlGroupAttribute={ controller=%s ; attribute=%s ; value=\"%s\" }\n",
3012 dbus_message_iter_next(&sub);
3017 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
3018 DBusMessageIter sub;
3020 dbus_message_iter_recurse(iter, &sub);
3021 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3022 ExecStatusInfo info;
3025 if (exec_status_info_deserialize(&sub, &info) >= 0) {
3026 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
3029 t = strv_join(info.argv, " ");
3031 printf("%s={ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
3035 yes_no(info.ignore),
3036 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
3037 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
3038 (unsigned) info. pid,
3039 sigchld_code_to_string(info.code),
3041 info.code == CLD_EXITED ? "" : "/",
3042 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
3048 strv_free(info.argv);
3050 dbus_message_iter_next(&sub);
3059 if (generic_print_property(name, iter, arg_all) > 0)
3063 printf("%s=[unprintable]\n", name);
3068 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
3069 DBusMessage *m = NULL, *reply = NULL;
3070 const char *interface = "";
3073 DBusMessageIter iter, sub, sub2, sub3;
3074 UnitStatusInfo info;
3082 dbus_error_init(&error);
3084 if (!(m = dbus_message_new_method_call(
3085 "org.freedesktop.systemd1",
3087 "org.freedesktop.DBus.Properties",
3089 log_error("Could not allocate message.");
3094 if (!dbus_message_append_args(m,
3095 DBUS_TYPE_STRING, &interface,
3096 DBUS_TYPE_INVALID)) {
3097 log_error("Could not append arguments to message.");
3102 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3103 log_error("Failed to issue method call: %s", bus_error_message(&error));
3108 if (!dbus_message_iter_init(reply, &iter) ||
3109 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
3110 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
3111 log_error("Failed to parse reply.");
3116 dbus_message_iter_recurse(&iter, &sub);
3123 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
3126 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
3127 log_error("Failed to parse reply.");
3132 dbus_message_iter_recurse(&sub, &sub2);
3134 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
3135 log_error("Failed to parse reply.");
3140 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
3141 log_error("Failed to parse reply.");
3146 dbus_message_iter_recurse(&sub2, &sub3);
3148 if (show_properties)
3149 r = print_property(name, &sub3);
3151 r = status_property(name, &sub3, &info);
3154 log_error("Failed to parse reply.");
3159 dbus_message_iter_next(&sub);
3164 if (!show_properties) {
3165 if (streq(verb, "help"))
3166 show_unit_help(&info);
3168 print_status_info(&info);
3171 strv_free(info.documentation);
3173 if (!streq_ptr(info.active_state, "active") &&
3174 !streq_ptr(info.active_state, "reloading") &&
3175 streq(verb, "status"))
3176 /* According to LSB: "program not running" */
3179 while ((p = info.exec)) {
3180 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
3181 exec_status_info_free(p);
3186 dbus_message_unref(m);
3189 dbus_message_unref(reply);
3191 dbus_error_free(&error);
3196 static int show_one_by_pid(const char *verb, DBusConnection *bus, uint32_t pid, bool *new_line) {
3197 DBusMessage *m = NULL, *reply = NULL;
3198 const char *path = NULL;
3202 dbus_error_init(&error);
3204 m = dbus_message_new_method_call(
3205 "org.freedesktop.systemd1",
3206 "/org/freedesktop/systemd1",
3207 "org.freedesktop.systemd1.Manager",
3210 log_error("Could not allocate message.");
3215 if (!dbus_message_append_args(m,
3216 DBUS_TYPE_UINT32, &pid,
3217 DBUS_TYPE_INVALID)) {
3218 log_error("Could not append arguments to message.");
3223 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3225 log_error("Failed to issue method call: %s", bus_error_message(&error));
3230 if (!dbus_message_get_args(reply, &error,
3231 DBUS_TYPE_OBJECT_PATH, &path,
3232 DBUS_TYPE_INVALID)) {
3233 log_error("Failed to parse reply: %s", bus_error_message(&error));
3238 r = show_one(verb, bus, path, false, new_line);
3242 dbus_message_unref(m);
3245 dbus_message_unref(reply);
3247 dbus_error_free(&error);
3252 static int show(DBusConnection *bus, char **args) {
3254 bool show_properties, new_line = false;
3260 show_properties = streq(args[0], "show");
3262 if (show_properties)
3263 pager_open_if_enabled();
3265 if (show_properties && strv_length(args) <= 1) {
3266 /* If not argument is specified inspect the manager
3269 return show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
3272 STRV_FOREACH(name, args+1) {
3275 if (safe_atou32(*name, &id) < 0) {
3277 /* Interpret as unit name */
3279 n = unit_name_mangle(*name);
3280 p = unit_dbus_path_from_name(n ? n : *name);
3283 log_error("Out of memory");
3287 r = show_one(args[0], bus, p, show_properties, &new_line);
3293 } else if (show_properties) {
3295 /* Interpret as job id */
3298 if (asprintf(&p, "/org/freedesktop/systemd1/job/%u", id) < 0) {
3299 log_error("Out of memory");
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_MEEGO) || 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);
3974 log_error("No memory");
3979 found_native = access(p, F_OK) >= 0;
3990 if (!isempty(arg_root))
3991 asprintf(&p, "%s/" SYSTEM_SYSVINIT_PATH "/%s", arg_root, name);
3993 asprintf(&p, SYSTEM_SYSVINIT_PATH "/%s", name);
3995 log_error("No memory");
4000 p[strlen(p) - sizeof(".service") + 1] = 0;
4001 found_sysv = access(p, F_OK) >= 0;
4008 /* Mark this entry, so that we don't try enabling it as native unit */
4009 args[f] = (char*) "";
4011 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", name);
4013 if (!isempty(arg_root))
4014 argv[c++] = q = strappend("--root=", arg_root);
4016 argv[c++] = path_get_file_name(p);
4018 streq(verb, "enable") ? "on" :
4019 streq(verb, "disable") ? "off" : "--level=5";
4022 l = strv_join((char**)argv, " ");
4024 log_error("No memory.");
4031 log_info("Executing %s", l);
4036 log_error("Failed to fork: %m");
4041 } else if (pid == 0) {
4044 execv(argv[0], (char**) argv);
4045 _exit(EXIT_FAILURE);
4051 j = wait_for_terminate(pid, &status);
4053 log_error("Failed to wait for child: %s", strerror(-r));
4058 if (status.si_code == CLD_EXITED) {
4059 if (streq(verb, "is-enabled")) {
4060 if (status.si_status == 0) {
4069 } else if (status.si_status != 0) {
4080 lookup_paths_free(&paths);
4082 /* Drop all SysV units */
4083 for (f = 1, t = 1; args[f]; f++) {
4085 if (isempty(args[f]))
4088 args[t++] = args[f];
4097 static int enable_unit(DBusConnection *bus, char **args) {
4098 const char *verb = args[0];
4099 UnitFileChange *changes = NULL;
4100 unsigned n_changes = 0, i;
4101 int carries_install_info = -1;
4102 DBusMessage *m = NULL, *reply = NULL;
4106 r = enable_sysv_units(args);
4113 dbus_error_init(&error);
4115 if (!bus || avoid_bus()) {
4116 if (streq(verb, "enable")) {
4117 r = unit_file_enable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4118 carries_install_info = r;
4119 } else if (streq(verb, "disable"))
4120 r = unit_file_disable(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
4121 else if (streq(verb, "reenable")) {
4122 r = unit_file_reenable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4123 carries_install_info = r;
4124 } else if (streq(verb, "link"))
4125 r = unit_file_link(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4126 else if (streq(verb, "preset")) {
4127 r = unit_file_preset(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4128 carries_install_info = r;
4129 } else if (streq(verb, "mask"))
4130 r = unit_file_mask(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4131 else if (streq(verb, "unmask"))
4132 r = unit_file_unmask(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
4134 assert_not_reached("Unknown verb");
4137 log_error("Operation failed: %s", strerror(-r));
4142 for (i = 0; i < n_changes; i++) {
4143 if (changes[i].type == UNIT_FILE_SYMLINK)
4144 log_info("ln -s '%s' '%s'", changes[i].source, changes[i].path);
4146 log_info("rm '%s'", changes[i].path);
4152 bool send_force = true, expect_carries_install_info = false;
4154 DBusMessageIter iter, sub, sub2;
4156 if (streq(verb, "enable")) {
4157 method = "EnableUnitFiles";
4158 expect_carries_install_info = true;
4159 } else if (streq(verb, "disable")) {
4160 method = "DisableUnitFiles";
4162 } else if (streq(verb, "reenable")) {
4163 method = "ReenableUnitFiles";
4164 expect_carries_install_info = true;
4165 } else if (streq(verb, "link"))
4166 method = "LinkUnitFiles";
4167 else if (streq(verb, "preset")) {
4168 method = "PresetUnitFiles";
4169 expect_carries_install_info = true;
4170 } else if (streq(verb, "mask"))
4171 method = "MaskUnitFiles";
4172 else if (streq(verb, "unmask")) {
4173 method = "UnmaskUnitFiles";
4176 assert_not_reached("Unknown verb");
4178 m = dbus_message_new_method_call(
4179 "org.freedesktop.systemd1",
4180 "/org/freedesktop/systemd1",
4181 "org.freedesktop.systemd1.Manager",
4184 log_error("Out of memory");
4189 dbus_message_iter_init_append(m, &iter);
4191 r = bus_append_strv_iter(&iter, args+1);
4193 log_error("Failed to append unit files.");
4198 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &a)) {
4199 log_error("Failed to append runtime boolean.");
4207 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b)) {
4208 log_error("Failed to append force boolean.");
4214 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
4216 log_error("Failed to issue method call: %s", bus_error_message(&error));
4221 if (!dbus_message_iter_init(reply, &iter)) {
4222 log_error("Failed to initialize iterator.");
4226 if (expect_carries_install_info) {
4227 r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_BOOLEAN, &b, true);
4229 log_error("Failed to parse reply.");
4233 carries_install_info = b;
4236 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
4237 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
4238 log_error("Failed to parse reply.");
4243 dbus_message_iter_recurse(&iter, &sub);
4244 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
4245 const char *type, *path, *source;
4247 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
4248 log_error("Failed to parse reply.");
4253 dbus_message_iter_recurse(&sub, &sub2);
4255 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
4256 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0 ||
4257 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &source, false) < 0) {
4258 log_error("Failed to parse reply.");
4264 if (streq(type, "symlink"))
4265 log_info("ln -s '%s' '%s'", source, path);
4267 log_info("rm '%s'", path);
4270 dbus_message_iter_next(&sub);
4273 /* Try to reload if enabeld */
4275 r = daemon_reload(bus, args);
4278 if (carries_install_info == 0)
4279 log_warning("The unit files have no [Install] section. They are not meant to be enabled using systemctl.");
4283 dbus_message_unref(m);
4286 dbus_message_unref(reply);
4288 unit_file_changes_free(changes, n_changes);
4290 dbus_error_free(&error);
4294 static int unit_is_enabled(DBusConnection *bus, char **args) {
4297 DBusMessage *m = NULL, *reply = NULL;
4301 dbus_error_init(&error);
4303 r = enable_sysv_units(args);
4309 if (!bus || avoid_bus()) {
4311 STRV_FOREACH(name, args+1) {
4312 UnitFileState state;
4314 state = unit_file_get_state(arg_scope, arg_root, *name);
4320 if (state == UNIT_FILE_ENABLED ||
4321 state == UNIT_FILE_ENABLED_RUNTIME ||
4322 state == UNIT_FILE_STATIC)
4326 puts(unit_file_state_to_string(state));
4330 STRV_FOREACH(name, args+1) {
4333 m = dbus_message_new_method_call(
4334 "org.freedesktop.systemd1",
4335 "/org/freedesktop/systemd1",
4336 "org.freedesktop.systemd1.Manager",
4337 "GetUnitFileState");
4339 log_error("Out of memory");
4344 if (!dbus_message_append_args(m,
4345 DBUS_TYPE_STRING, name,
4346 DBUS_TYPE_INVALID)) {
4347 log_error("Could not append arguments to message.");
4352 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
4354 log_error("Failed to issue method call: %s", bus_error_message(&error));
4359 if (!dbus_message_get_args(reply, &error,
4360 DBUS_TYPE_STRING, &s,
4361 DBUS_TYPE_INVALID)) {
4362 log_error("Failed to parse reply: %s", bus_error_message(&error));
4367 dbus_message_unref(m);
4368 dbus_message_unref(reply);
4371 if (streq(s, "enabled") ||
4372 streq(s, "enabled-runtime") ||
4381 r = enabled ? 0 : 1;
4385 dbus_message_unref(m);
4388 dbus_message_unref(reply);
4390 dbus_error_free(&error);
4394 static int systemctl_help(void) {
4396 pager_open_if_enabled();
4398 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4399 "Query or send control commands to the systemd manager.\n\n"
4400 " -h --help Show this help\n"
4401 " --version Show package version\n"
4402 " -t --type=TYPE List only units of a particular type\n"
4403 " -p --property=NAME Show only properties by this name\n"
4404 " -a --all Show all units/properties, including dead/empty ones\n"
4405 " --failed Show only failed units\n"
4406 " --full Don't ellipsize unit names on output\n"
4407 " --fail When queueing a new job, fail if conflicting jobs are\n"
4409 " --ignore-dependencies\n"
4410 " When queueing a new job, ignore all its dependencies\n"
4411 " --kill-who=WHO Who to send signal to\n"
4412 " -s --signal=SIGNAL Which signal to send\n"
4413 " -H --host=[USER@]HOST\n"
4414 " Show information for remote host\n"
4415 " -P --privileged Acquire privileges before execution\n"
4416 " -q --quiet Suppress output\n"
4417 " --no-block Do not wait until operation finished\n"
4418 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4419 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4421 " --no-legend Do not print a legend (column headers and hints)\n"
4422 " --no-pager Do not pipe output into a pager\n"
4423 " --no-ask-password\n"
4424 " Do not ask for system passwords\n"
4425 " --order When generating graph for dot, show only order\n"
4426 " --require When generating graph for dot, show only requirement\n"
4427 " --system Connect to system manager\n"
4428 " --user Connect to user service manager\n"
4429 " --global Enable/disable unit files globally\n"
4430 " -f --force When enabling unit files, override existing symlinks\n"
4431 " When shutting down, execute action immediately\n"
4432 " --root=PATH Enable unit files in the specified root directory\n"
4433 " --runtime Enable unit files only temporarily until next reboot\n"
4434 " -n --lines=INTEGER Journal entries to show\n"
4435 " --follow Follow journal\n"
4436 " -o --output=STRING Change journal output mode (short, short-monotonic,\n"
4437 " verbose, export, json, cat)\n\n"
4439 " list-units List loaded units\n"
4440 " start [NAME...] Start (activate) one or more units\n"
4441 " stop [NAME...] Stop (deactivate) one or more units\n"
4442 " reload [NAME...] Reload one or more units\n"
4443 " restart [NAME...] Start or restart one or more units\n"
4444 " try-restart [NAME...] Restart one or more units if active\n"
4445 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4446 " otherwise start or restart\n"
4447 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4448 " otherwise restart if active\n"
4449 " isolate [NAME] Start one unit and stop all others\n"
4450 " kill [NAME...] Send signal to processes of a unit\n"
4451 " is-active [NAME...] Check whether units are active\n"
4452 " status [NAME...|PID...] Show runtime status of one or more units\n"
4453 " show [NAME...|JOB...] Show properties of one or more\n"
4454 " units/jobs or the manager\n"
4455 " help [NAME...|PID...] Show manual for one or more units\n"
4456 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4458 " load [NAME...] Load one or more units\n\n"
4459 "Unit File Commands:\n"
4460 " list-unit-files List installed unit files\n"
4461 " enable [NAME...] Enable one or more unit files\n"
4462 " disable [NAME...] Disable one or more unit files\n"
4463 " reenable [NAME...] Reenable one or more unit files\n"
4464 " preset [NAME...] Enable/disable one or more unit files\n"
4465 " based on preset configuration\n"
4466 " mask [NAME...] Mask one or more units\n"
4467 " unmask [NAME...] Unmask one or more units\n"
4468 " link [PATH...] Link one or more units files into\n"
4469 " the search path\n"
4470 " is-enabled [NAME...] Check whether unit files are enabled\n\n"
4472 " list-jobs List jobs\n"
4473 " cancel [JOB...] Cancel all, one, or more jobs\n\n"
4474 "Status Commands:\n"
4475 " dump Dump server status\n"
4476 " dot Dump dependency graph for dot(1)\n\n"
4477 "Snapshot Commands:\n"
4478 " snapshot [NAME] Create a snapshot\n"
4479 " delete [NAME...] Remove one or more snapshots\n\n"
4480 "Environment Commands:\n"
4481 " show-environment Dump environment\n"
4482 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4483 " unset-environment [NAME...] Unset one or more environment variables\n\n"
4484 "Manager Lifecycle Commands:\n"
4485 " daemon-reload Reload systemd manager configuration\n"
4486 " daemon-reexec Reexecute systemd manager\n\n"
4487 "System Commands:\n"
4488 " default Enter system default mode\n"
4489 " rescue Enter system rescue mode\n"
4490 " emergency Enter system emergency mode\n"
4491 " halt Shut down and halt the system\n"
4492 " poweroff Shut down and power-off the system\n"
4493 " reboot Shut down and reboot the system\n"
4494 " kexec Shut down and reboot the system with kexec\n"
4495 " exit Request user instance exit\n"
4496 " switch-root [ROOT] [INIT] Change to a different root file system\n"
4497 " suspend Suspend the system\n"
4498 " hibernate Hibernate the system\n",
4499 program_invocation_short_name);
4504 static int halt_help(void) {
4506 printf("%s [OPTIONS...]\n\n"
4507 "%s the system.\n\n"
4508 " --help Show this help\n"
4509 " --halt Halt the machine\n"
4510 " -p --poweroff Switch off the machine\n"
4511 " --reboot Reboot the machine\n"
4512 " -f --force Force immediate halt/power-off/reboot\n"
4513 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4514 " -d --no-wtmp Don't write wtmp record\n"
4515 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4516 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4517 program_invocation_short_name,
4518 arg_action == ACTION_REBOOT ? "Reboot" :
4519 arg_action == ACTION_POWEROFF ? "Power off" :
4525 static int shutdown_help(void) {
4527 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4528 "Shut down the system.\n\n"
4529 " --help Show this help\n"
4530 " -H --halt Halt the machine\n"
4531 " -P --poweroff Power-off the machine\n"
4532 " -r --reboot Reboot the machine\n"
4533 " -h Equivalent to --poweroff, overridden by --halt\n"
4534 " -k Don't halt/power-off/reboot, just send warnings\n"
4535 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4536 " -c Cancel a pending shutdown\n",
4537 program_invocation_short_name);
4542 static int telinit_help(void) {
4544 printf("%s [OPTIONS...] {COMMAND}\n\n"
4545 "Send control commands to the init daemon.\n\n"
4546 " --help Show this help\n"
4547 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4549 " 0 Power-off the machine\n"
4550 " 6 Reboot the machine\n"
4551 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4552 " 1, s, S Enter rescue mode\n"
4553 " q, Q Reload init daemon configuration\n"
4554 " u, U Reexecute init daemon\n",
4555 program_invocation_short_name);
4560 static int runlevel_help(void) {
4562 printf("%s [OPTIONS...]\n\n"
4563 "Prints the previous and current runlevel of the init system.\n\n"
4564 " --help Show this help\n",
4565 program_invocation_short_name);
4570 static int systemctl_parse_argv(int argc, char *argv[]) {
4574 ARG_IGNORE_DEPENDENCIES,
4590 ARG_NO_ASK_PASSWORD,
4597 static const struct option options[] = {
4598 { "help", no_argument, NULL, 'h' },
4599 { "version", no_argument, NULL, ARG_VERSION },
4600 { "type", required_argument, NULL, 't' },
4601 { "property", required_argument, NULL, 'p' },
4602 { "all", no_argument, NULL, 'a' },
4603 { "failed", no_argument, NULL, ARG_FAILED },
4604 { "full", no_argument, NULL, ARG_FULL },
4605 { "fail", no_argument, NULL, ARG_FAIL },
4606 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4607 { "user", no_argument, NULL, ARG_USER },
4608 { "system", no_argument, NULL, ARG_SYSTEM },
4609 { "global", no_argument, NULL, ARG_GLOBAL },
4610 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4611 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
4612 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4613 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4614 { "quiet", no_argument, NULL, 'q' },
4615 { "order", no_argument, NULL, ARG_ORDER },
4616 { "require", no_argument, NULL, ARG_REQUIRE },
4617 { "root", required_argument, NULL, ARG_ROOT },
4618 { "force", no_argument, NULL, ARG_FORCE },
4619 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4620 { "kill-mode", required_argument, NULL, ARG_KILL_MODE }, /* undocumented on purpose */
4621 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4622 { "signal", required_argument, NULL, 's' },
4623 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4624 { "host", required_argument, NULL, 'H' },
4625 { "privileged",no_argument, NULL, 'P' },
4626 { "runtime", no_argument, NULL, ARG_RUNTIME },
4627 { "lines", required_argument, NULL, 'n' },
4628 { "follow", no_argument, NULL, ARG_FOLLOW },
4629 { "output", required_argument, NULL, 'o' },
4630 { NULL, 0, NULL, 0 }
4638 while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:Pn:o:", options, NULL)) >= 0) {
4647 puts(PACKAGE_STRING);
4649 puts(SYSTEMD_FEATURES);
4659 if (!(l = strv_append(arg_property, optarg)))
4662 strv_free(arg_property);
4665 /* If the user asked for a particular
4666 * property, show it to him, even if it is
4677 arg_job_mode = "fail";
4680 case ARG_IGNORE_DEPENDENCIES:
4681 arg_job_mode = "ignore-dependencies";
4685 arg_scope = UNIT_FILE_USER;
4689 arg_scope = UNIT_FILE_SYSTEM;
4693 arg_scope = UNIT_FILE_GLOBAL;
4697 arg_no_block = true;
4701 arg_no_legend = true;
4705 arg_no_pager = true;
4713 arg_dot = DOT_ORDER;
4717 arg_dot = DOT_REQUIRE;
4745 /* -f is short for both --follow and --force! */
4751 arg_no_reload = true;
4755 arg_kill_who = optarg;
4759 arg_kill_mode = optarg;
4763 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4764 log_error("Failed to parse signal string %s.", optarg);
4769 case ARG_NO_ASK_PASSWORD:
4770 arg_ask_password = false;
4774 arg_transport = TRANSPORT_POLKIT;
4778 arg_transport = TRANSPORT_SSH;
4787 if (safe_atou(optarg, &arg_lines) < 0) {
4788 log_error("Failed to parse lines '%s'", optarg);
4794 arg_output = output_mode_from_string(optarg);
4795 if (arg_output < 0) {
4796 log_error("Unknown output '%s'.", optarg);
4805 log_error("Unknown option code '%c'.", c);
4810 if (arg_transport != TRANSPORT_NORMAL && arg_scope != UNIT_FILE_SYSTEM) {
4811 log_error("Cannot access user instance remotely.");
4818 static int halt_parse_argv(int argc, char *argv[]) {
4827 static const struct option options[] = {
4828 { "help", no_argument, NULL, ARG_HELP },
4829 { "halt", no_argument, NULL, ARG_HALT },
4830 { "poweroff", no_argument, NULL, 'p' },
4831 { "reboot", no_argument, NULL, ARG_REBOOT },
4832 { "force", no_argument, NULL, 'f' },
4833 { "wtmp-only", no_argument, NULL, 'w' },
4834 { "no-wtmp", no_argument, NULL, 'd' },
4835 { "no-sync", no_argument, NULL, 'n' },
4836 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4837 { NULL, 0, NULL, 0 }
4845 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4846 if (runlevel == '0' || runlevel == '6')
4849 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4857 arg_action = ACTION_HALT;
4861 if (arg_action != ACTION_REBOOT)
4862 arg_action = ACTION_POWEROFF;
4866 arg_action = ACTION_REBOOT;
4891 /* Compatibility nops */
4898 log_error("Unknown option code '%c'.", c);
4903 if (optind < argc) {
4904 log_error("Too many arguments.");
4911 static int parse_time_spec(const char *t, usec_t *_u) {
4915 if (streq(t, "now"))
4917 else if (!strchr(t, ':')) {
4920 if (safe_atou64(t, &u) < 0)
4923 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4932 hour = strtol(t, &e, 10);
4933 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4936 minute = strtol(e+1, &e, 10);
4937 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4940 n = now(CLOCK_REALTIME);
4941 s = (time_t) (n / USEC_PER_SEC);
4944 assert_se(localtime_r(&s, &tm));
4946 tm.tm_hour = (int) hour;
4947 tm.tm_min = (int) minute;
4950 assert_se(s = mktime(&tm));
4952 *_u = (usec_t) s * USEC_PER_SEC;
4955 *_u += USEC_PER_DAY;
4961 static int shutdown_parse_argv(int argc, char *argv[]) {
4968 static const struct option options[] = {
4969 { "help", no_argument, NULL, ARG_HELP },
4970 { "halt", no_argument, NULL, 'H' },
4971 { "poweroff", no_argument, NULL, 'P' },
4972 { "reboot", no_argument, NULL, 'r' },
4973 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
4974 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4975 { NULL, 0, NULL, 0 }
4983 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4991 arg_action = ACTION_HALT;
4995 arg_action = ACTION_POWEROFF;
5000 arg_action = ACTION_KEXEC;
5002 arg_action = ACTION_REBOOT;
5006 arg_action = ACTION_KEXEC;
5010 if (arg_action != ACTION_HALT)
5011 arg_action = ACTION_POWEROFF;
5024 /* Compatibility nops */
5028 arg_action = ACTION_CANCEL_SHUTDOWN;
5035 log_error("Unknown option code '%c'.", c);
5040 if (argc > optind) {
5041 r = parse_time_spec(argv[optind], &arg_when);
5043 log_error("Failed to parse time specification: %s", argv[optind]);
5047 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
5049 /* We skip the time argument */
5050 if (argc > optind + 1)
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 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:
5830 r = send_shutdownd(0, 0, false, false, NULL);
5833 case ACTION_INVALID:
5834 case ACTION_RUNLEVEL:
5836 assert_not_reached("Unknown action");
5839 retval = r < 0 ? EXIT_FAILURE : r;
5843 dbus_connection_flush(bus);
5844 dbus_connection_close(bus);
5845 dbus_connection_unref(bus);
5848 dbus_error_free(&error);
5852 strv_free(arg_property);
5855 ask_password_agent_close();
5856 polkit_agent_close();