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) {
1127 if (!(m = dbus_message_new_method_call(
1128 "org.freedesktop.systemd1",
1129 "/org/freedesktop/systemd1",
1130 "org.freedesktop.systemd1.Manager",
1132 log_error("Could not allocate message.");
1137 if (!dbus_message_append_args(m,
1138 DBUS_TYPE_STRING, name,
1139 DBUS_TYPE_INVALID)) {
1140 log_error("Could not append arguments to message.");
1145 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1146 log_error("Failed to issue method call: %s", bus_error_message(&error));
1151 dbus_message_unref(m);
1152 dbus_message_unref(reply);
1161 dbus_message_unref(m);
1163 dbus_error_free(&error);
1168 static int cancel_job(DBusConnection *bus, char **args) {
1169 DBusMessage *m = NULL, *reply = NULL;
1174 dbus_error_init(&error);
1179 if (strv_length(args) <= 1)
1180 return daemon_reload(bus, args);
1182 STRV_FOREACH(name, args+1) {
1186 if (!(m = dbus_message_new_method_call(
1187 "org.freedesktop.systemd1",
1188 "/org/freedesktop/systemd1",
1189 "org.freedesktop.systemd1.Manager",
1191 log_error("Could not allocate message.");
1196 if ((r = safe_atou(*name, &id)) < 0) {
1197 log_error("Failed to parse job id: %s", strerror(-r));
1201 assert_cc(sizeof(uint32_t) == sizeof(id));
1202 if (!dbus_message_append_args(m,
1203 DBUS_TYPE_UINT32, &id,
1204 DBUS_TYPE_INVALID)) {
1205 log_error("Could not append arguments to message.");
1210 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1211 log_error("Failed to issue method call: %s", bus_error_message(&error));
1216 if (!dbus_message_get_args(reply, &error,
1217 DBUS_TYPE_OBJECT_PATH, &path,
1218 DBUS_TYPE_INVALID)) {
1219 log_error("Failed to parse reply: %s", bus_error_message(&error));
1224 dbus_message_unref(m);
1225 if (!(m = dbus_message_new_method_call(
1226 "org.freedesktop.systemd1",
1228 "org.freedesktop.systemd1.Job",
1230 log_error("Could not allocate message.");
1235 dbus_message_unref(reply);
1236 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1237 log_error("Failed to issue method call: %s", bus_error_message(&error));
1242 dbus_message_unref(m);
1243 dbus_message_unref(reply);
1251 dbus_message_unref(m);
1254 dbus_message_unref(reply);
1256 dbus_error_free(&error);
1261 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1262 DBusMessage *m = NULL, *reply = NULL;
1263 dbus_bool_t b = FALSE;
1264 DBusMessageIter iter, sub;
1266 *interface = "org.freedesktop.systemd1.Unit",
1267 *property = "NeedDaemonReload",
1270 /* We ignore all errors here, since this is used to show a warning only */
1272 if (!(m = dbus_message_new_method_call(
1273 "org.freedesktop.systemd1",
1274 "/org/freedesktop/systemd1",
1275 "org.freedesktop.systemd1.Manager",
1279 if (!dbus_message_append_args(m,
1280 DBUS_TYPE_STRING, &unit,
1284 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1287 if (!dbus_message_get_args(reply, NULL,
1288 DBUS_TYPE_OBJECT_PATH, &path,
1292 dbus_message_unref(m);
1293 if (!(m = dbus_message_new_method_call(
1294 "org.freedesktop.systemd1",
1296 "org.freedesktop.DBus.Properties",
1300 if (!dbus_message_append_args(m,
1301 DBUS_TYPE_STRING, &interface,
1302 DBUS_TYPE_STRING, &property,
1303 DBUS_TYPE_INVALID)) {
1307 dbus_message_unref(reply);
1308 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1311 if (!dbus_message_iter_init(reply, &iter) ||
1312 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1315 dbus_message_iter_recurse(&iter, &sub);
1317 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1320 dbus_message_iter_get_basic(&sub, &b);
1324 dbus_message_unref(m);
1327 dbus_message_unref(reply);
1332 typedef struct WaitData {
1337 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1345 dbus_error_init(&error);
1347 log_debug("Got D-Bus request: %s.%s() on %s",
1348 dbus_message_get_interface(message),
1349 dbus_message_get_member(message),
1350 dbus_message_get_path(message));
1352 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1353 log_error("Warning! D-Bus connection terminated.");
1354 dbus_connection_close(connection);
1356 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1358 const char *path, *result, *unit;
1359 dbus_bool_t success = true;
1361 if (dbus_message_get_args(message, &error,
1362 DBUS_TYPE_UINT32, &id,
1363 DBUS_TYPE_OBJECT_PATH, &path,
1364 DBUS_TYPE_STRING, &unit,
1365 DBUS_TYPE_STRING, &result,
1366 DBUS_TYPE_INVALID)) {
1369 p = set_remove(d->set, (char*) path);
1373 d->result = strdup(result);
1378 dbus_error_free(&error);
1379 if (dbus_message_get_args(message, &error,
1380 DBUS_TYPE_UINT32, &id,
1381 DBUS_TYPE_OBJECT_PATH, &path,
1382 DBUS_TYPE_STRING, &result,
1383 DBUS_TYPE_INVALID)) {
1386 /* Compatibility with older systemd versions <
1387 * 183 during upgrades. This should be dropped
1389 p = set_remove(d->set, (char*) path);
1393 d->result = strdup(result);
1398 dbus_error_free(&error);
1399 if (dbus_message_get_args(message, &error,
1400 DBUS_TYPE_UINT32, &id,
1401 DBUS_TYPE_OBJECT_PATH, &path,
1402 DBUS_TYPE_BOOLEAN, &success,
1403 DBUS_TYPE_INVALID)) {
1406 /* Compatibility with older systemd versions <
1407 * 19 during upgrades. This should be dropped
1410 p = set_remove(d->set, (char*) path);
1414 d->result = strdup("failed");
1420 log_error("Failed to parse message: %s", bus_error_message(&error));
1424 dbus_error_free(&error);
1425 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1428 static int enable_wait_for_jobs(DBusConnection *bus) {
1436 dbus_error_init(&error);
1437 dbus_bus_add_match(bus,
1439 "sender='org.freedesktop.systemd1',"
1440 "interface='org.freedesktop.systemd1.Manager',"
1441 "member='JobRemoved',"
1442 "path='/org/freedesktop/systemd1'",
1445 if (dbus_error_is_set(&error)) {
1446 log_error("Failed to add match: %s", bus_error_message(&error));
1447 dbus_error_free(&error);
1451 /* This is slightly dirty, since we don't undo the match registrations. */
1455 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1465 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1466 log_error("Failed to add filter.");
1471 while (!set_isempty(s) &&
1472 dbus_connection_read_write_dispatch(bus, -1))
1475 if (!arg_quiet && d.result) {
1476 if (streq(d.result, "timeout"))
1477 log_error("Job timed out.");
1478 else if (streq(d.result, "canceled"))
1479 log_error("Job canceled.");
1480 else if (streq(d.result, "dependency"))
1481 log_error("A dependency job failed. See system journal for details.");
1482 else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
1483 log_error("Job failed. See system journal and 'systemctl status' for details.");
1486 if (streq_ptr(d.result, "timeout"))
1488 else if (streq_ptr(d.result, "canceled"))
1490 else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
1498 /* This is slightly dirty, since we don't undo the filter registration. */
1503 static int get_unit_path(
1504 DBusConnection *bus,
1509 DBusMessage *m = NULL, *reply = NULL;
1517 dbus_error_init(&error);
1519 m = dbus_message_new_method_call("org.freedesktop.systemd1",
1520 "/org/freedesktop/systemd1",
1521 "org.freedesktop.systemd1.Manager",
1524 log_error("Could not allocate message.");
1529 if (!dbus_message_append_args(m,
1530 DBUS_TYPE_STRING, &name,
1531 DBUS_TYPE_INVALID)) {
1532 log_error("Could not append arguments to message.");
1537 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
1539 if (streq(error.name, BUS_ERROR_NO_SUCH_UNIT))
1542 log_error("Failed to issue method call: %s", bus_error_message(&error));
1548 if (!dbus_message_get_args(reply, &error,
1549 DBUS_TYPE_OBJECT_PATH, &path,
1550 DBUS_TYPE_INVALID)) {
1551 log_error("Failed to parse reply: %s", bus_error_message(&error));
1556 *unit_path = strdup(path);
1557 if (!(*unit_path)) {
1558 log_error("Failed to duplicate unit path");
1563 dbus_message_unref(m);
1565 dbus_message_unref(reply);
1567 dbus_error_free(&error);
1572 static int is_socket_listening(
1573 DBusConnection *bus,
1574 const char *socket_name) {
1577 DBusMessage *m = NULL, *reply = NULL;
1578 DBusMessageIter iter, sub;
1579 char *socket_object_path = NULL;
1580 const char *sub_state = NULL,
1581 *interface = "org.freedesktop.systemd1.Unit",
1582 *property = "SubState";
1586 assert(socket_name);
1588 dbus_error_init(&error);
1590 r = get_unit_path(bus, socket_name, &socket_object_path);
1594 m = dbus_message_new_method_call("org.freedesktop.systemd1",
1596 "org.freedesktop.DBus.Properties",
1599 log_error("Could not allocate message.");
1604 if (!dbus_message_append_args(m,
1605 DBUS_TYPE_STRING, &interface,
1606 DBUS_TYPE_STRING, &property,
1607 DBUS_TYPE_INVALID)) {
1608 log_error("Could not append arguments to message.");
1613 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
1615 log_error("Failed to issue method call: %s", bus_error_message(&error));
1620 dbus_message_iter_init(reply, &iter);
1621 dbus_message_iter_recurse(&iter, &sub);
1623 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1624 log_error("Failed to parse reply: %s", bus_error_message(&error));
1628 dbus_message_iter_get_basic(&sub, &sub_state);
1629 r = streq(sub_state, "listening");
1632 dbus_message_unref(m);
1635 dbus_message_unref(reply);
1637 dbus_error_free(&error);
1639 free(socket_object_path);
1643 static void check_listening_sockets(
1644 DBusConnection *bus,
1645 const char *unit_name) {
1648 DBusMessage *m = NULL, *reply = NULL;
1649 DBusMessageIter iter, sub;
1650 const char *service_trigger = NULL,
1651 *interface = "org.freedesktop.systemd1.Unit",
1652 *triggered_by_property = "TriggeredBy";
1654 char *unit_path = NULL;
1655 bool print_warning_label = true;
1657 dbus_error_init(&error);
1659 if (get_unit_path(bus, unit_name, &unit_path) < 0)
1662 m = dbus_message_new_method_call("org.freedesktop.systemd1",
1664 "org.freedesktop.DBus.Properties",
1667 log_error("Could not allocate message.");
1671 if (!dbus_message_append_args(m,
1672 DBUS_TYPE_STRING, &interface,
1673 DBUS_TYPE_STRING, &triggered_by_property,
1674 DBUS_TYPE_INVALID)) {
1675 log_error("Could not append arguments to message.");
1679 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
1681 log_error("Failed to issue method call: %s", bus_error_message(&error));
1685 if (!dbus_message_iter_init(reply, &iter) ||
1686 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1687 log_error("Failed to parse reply: %s", bus_error_message(&error));
1692 dbus_message_iter_recurse(&iter, &sub);
1693 dbus_message_iter_recurse(&sub, &iter);
1696 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1699 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1700 log_error("Failed to parse reply: %s", bus_error_message(&error));
1704 dbus_message_iter_get_basic(&sub, &service_trigger);
1706 if (!endswith(service_trigger, ".socket"))
1709 r = is_socket_listening(bus, service_trigger);
1713 if (print_warning_label) {
1714 log_warning("There are listening sockets associated with %s :", unit_name);
1715 print_warning_label = false;
1717 log_warning("%s", service_trigger);
1720 dbus_message_iter_recurse(&iter, &sub);
1725 dbus_message_unref(m);
1728 dbus_message_unref(reply);
1730 dbus_error_free(&error);
1735 static int start_unit_one(
1736 DBusConnection *bus,
1743 DBusMessage *m = NULL, *reply = NULL;
1752 assert(arg_no_block || s);
1754 if (!(m = dbus_message_new_method_call(
1755 "org.freedesktop.systemd1",
1756 "/org/freedesktop/systemd1",
1757 "org.freedesktop.systemd1.Manager",
1759 log_error("Could not allocate message.");
1764 if (!dbus_message_append_args(m,
1765 DBUS_TYPE_STRING, &name,
1766 DBUS_TYPE_STRING, &mode,
1767 DBUS_TYPE_INVALID)) {
1768 log_error("Could not append arguments to message.");
1773 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1775 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1776 /* There's always a fallback possible for
1777 * legacy actions. */
1782 log_error("Failed to issue method call: %s", bus_error_message(error));
1787 if (!dbus_message_get_args(reply, error,
1788 DBUS_TYPE_OBJECT_PATH, &path,
1789 DBUS_TYPE_INVALID)) {
1790 log_error("Failed to parse reply: %s", bus_error_message(error));
1795 if (need_daemon_reload(bus, name))
1796 log_warning("Warning: Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1797 arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
1799 if (!arg_no_block) {
1802 if (!(p = strdup(path))) {
1803 log_error("Failed to duplicate path.");
1808 if ((r = set_put(s, p)) < 0) {
1810 log_error("Failed to add path to set.");
1815 /* When stopping unit check if we have some listening sockets active */
1816 if (streq(method, "StopUnit") && !arg_quiet)
1817 check_listening_sockets(bus, name);
1823 dbus_message_unref(m);
1826 dbus_message_unref(reply);
1831 static enum action verb_to_action(const char *verb) {
1832 if (streq(verb, "halt"))
1834 else if (streq(verb, "poweroff"))
1835 return ACTION_POWEROFF;
1836 else if (streq(verb, "reboot"))
1837 return ACTION_REBOOT;
1838 else if (streq(verb, "kexec"))
1839 return ACTION_KEXEC;
1840 else if (streq(verb, "rescue"))
1841 return ACTION_RESCUE;
1842 else if (streq(verb, "emergency"))
1843 return ACTION_EMERGENCY;
1844 else if (streq(verb, "default"))
1845 return ACTION_DEFAULT;
1846 else if (streq(verb, "exit"))
1848 else if (streq(verb, "suspend"))
1849 return ACTION_SUSPEND;
1850 else if (streq(verb, "hibernate"))
1851 return ACTION_HIBERNATE;
1853 return ACTION_INVALID;
1856 static int start_unit(DBusConnection *bus, char **args) {
1858 static const char * const table[_ACTION_MAX] = {
1859 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1860 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1861 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1862 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1863 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1864 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1865 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1866 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1867 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1868 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1869 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1870 [ACTION_EXIT] = SPECIAL_EXIT_TARGET,
1871 [ACTION_SUSPEND] = SPECIAL_SUSPEND_TARGET,
1872 [ACTION_HIBERNATE] = SPECIAL_HIBERNATE_TARGET
1876 const char *method, *mode, *one_name;
1881 dbus_error_init(&error);
1885 ask_password_agent_open_if_enabled();
1887 if (arg_action == ACTION_SYSTEMCTL) {
1889 streq(args[0], "stop") ||
1890 streq(args[0], "condstop") ? "StopUnit" :
1891 streq(args[0], "reload") ? "ReloadUnit" :
1892 streq(args[0], "restart") ? "RestartUnit" :
1894 streq(args[0], "try-restart") ||
1895 streq(args[0], "condrestart") ? "TryRestartUnit" :
1897 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1899 streq(args[0], "reload-or-try-restart") ||
1900 streq(args[0], "condreload") ||
1902 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1906 (streq(args[0], "isolate") ||
1907 streq(args[0], "rescue") ||
1908 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1910 one_name = table[verb_to_action(args[0])];
1913 assert(arg_action < ELEMENTSOF(table));
1914 assert(table[arg_action]);
1916 method = "StartUnit";
1918 mode = (arg_action == ACTION_EMERGENCY ||
1919 arg_action == ACTION_RESCUE ||
1920 arg_action == ACTION_RUNLEVEL2 ||
1921 arg_action == ACTION_RUNLEVEL3 ||
1922 arg_action == ACTION_RUNLEVEL4 ||
1923 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1925 one_name = table[arg_action];
1928 if (!arg_no_block) {
1929 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1930 log_error("Could not watch jobs: %s", strerror(-ret));
1934 if (!(s = set_new(string_hash_func, string_compare_func))) {
1935 log_error("Failed to allocate set.");
1942 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1945 STRV_FOREACH(name, args+1)
1946 if ((r = start_unit_one(bus, method, *name, mode, &error, s)) != 0) {
1947 ret = translate_bus_error_to_exit_status(r, &error);
1948 dbus_error_free(&error);
1953 if ((r = wait_for_jobs(bus, s)) < 0) {
1962 dbus_error_free(&error);
1967 /* Ask systemd-logind, which might grant access to unprivileged users
1968 * through PolicyKit */
1969 static int reboot_with_logind(DBusConnection *bus, enum action a) {
1972 DBusMessage *m = NULL, *reply = NULL;
1974 dbus_bool_t interactive = true;
1977 dbus_error_init(&error);
1979 polkit_agent_open_if_enabled();
1987 case ACTION_POWEROFF:
1988 method = "PowerOff";
1991 case ACTION_SUSPEND:
1995 case ACTION_HIBERNATE:
1996 method = "Hibernate";
2003 m = dbus_message_new_method_call(
2004 "org.freedesktop.login1",
2005 "/org/freedesktop/login1",
2006 "org.freedesktop.login1.Manager",
2009 log_error("Could not allocate message.");
2014 if (!dbus_message_append_args(m,
2015 DBUS_TYPE_BOOLEAN, &interactive,
2016 DBUS_TYPE_INVALID)) {
2017 log_error("Could not append arguments to message.");
2022 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
2024 if (error_is_no_service(&error)) {
2025 log_debug("Failed to issue method call: %s", bus_error_message(&error));
2030 if (dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2031 log_debug("Failed to issue method call: %s", bus_error_message(&error));
2036 log_info("Failed to issue method call: %s", bus_error_message(&error));
2045 dbus_message_unref(m);
2048 dbus_message_unref(reply);
2050 dbus_error_free(&error);
2058 static int start_special(DBusConnection *bus, char **args) {
2064 a = verb_to_action(args[0]);
2066 if (arg_force >= 2 && geteuid() != 0) {
2067 log_error("Must be root.");
2071 if (arg_force >= 2 &&
2072 (a == ACTION_HALT ||
2073 a == ACTION_POWEROFF ||
2074 a == ACTION_REBOOT))
2077 if (arg_force >= 1 &&
2078 (a == ACTION_HALT ||
2079 a == ACTION_POWEROFF ||
2080 a == ACTION_REBOOT ||
2081 a == ACTION_KEXEC ||
2083 return daemon_reload(bus, args);
2085 /* first try logind, to allow authentication with polkit */
2086 if (geteuid() != 0 &&
2087 (a == ACTION_POWEROFF ||
2088 a == ACTION_REBOOT ||
2089 a == ACTION_SUSPEND ||
2090 a == ACTION_HIBERNATE)) {
2091 r = reboot_with_logind(bus, a);
2096 r = start_unit(bus, args);
2103 static int check_unit(DBusConnection *bus, char **args) {
2104 DBusMessage *m = NULL, *reply = NULL;
2106 *interface = "org.freedesktop.systemd1.Unit",
2107 *property = "ActiveState";
2108 int r = 3; /* According to LSB: "program is not running" */
2115 dbus_error_init(&error);
2117 STRV_FOREACH(name, args+1) {
2118 const char *path = NULL;
2120 DBusMessageIter iter, sub;
2122 if (!(m = dbus_message_new_method_call(
2123 "org.freedesktop.systemd1",
2124 "/org/freedesktop/systemd1",
2125 "org.freedesktop.systemd1.Manager",
2127 log_error("Could not allocate message.");
2132 if (!dbus_message_append_args(m,
2133 DBUS_TYPE_STRING, name,
2134 DBUS_TYPE_INVALID)) {
2135 log_error("Could not append arguments to message.");
2140 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2142 /* Hmm, cannot figure out anything about this unit... */
2146 dbus_error_free(&error);
2147 dbus_message_unref(m);
2152 if (!dbus_message_get_args(reply, &error,
2153 DBUS_TYPE_OBJECT_PATH, &path,
2154 DBUS_TYPE_INVALID)) {
2155 log_error("Failed to parse reply: %s", bus_error_message(&error));
2160 dbus_message_unref(m);
2161 if (!(m = dbus_message_new_method_call(
2162 "org.freedesktop.systemd1",
2164 "org.freedesktop.DBus.Properties",
2166 log_error("Could not allocate message.");
2171 if (!dbus_message_append_args(m,
2172 DBUS_TYPE_STRING, &interface,
2173 DBUS_TYPE_STRING, &property,
2174 DBUS_TYPE_INVALID)) {
2175 log_error("Could not append arguments to message.");
2180 dbus_message_unref(reply);
2181 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2182 log_error("Failed to issue method call: %s", bus_error_message(&error));
2187 if (!dbus_message_iter_init(reply, &iter) ||
2188 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2189 log_error("Failed to parse reply.");
2194 dbus_message_iter_recurse(&iter, &sub);
2196 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2197 log_error("Failed to parse reply.");
2202 dbus_message_iter_get_basic(&sub, &state);
2207 if (streq(state, "active") || streq(state, "reloading"))
2210 dbus_message_unref(m);
2211 dbus_message_unref(reply);
2217 dbus_message_unref(m);
2220 dbus_message_unref(reply);
2222 dbus_error_free(&error);
2227 static int kill_unit(DBusConnection *bus, char **args) {
2228 DBusMessage *m = NULL;
2236 dbus_error_init(&error);
2239 arg_kill_who = "all";
2242 arg_kill_mode = streq(arg_kill_who, "all") ? "control-group" : "process";
2244 STRV_FOREACH(name, args+1) {
2247 if (!(m = dbus_message_new_method_call(
2248 "org.freedesktop.systemd1",
2249 "/org/freedesktop/systemd1",
2250 "org.freedesktop.systemd1.Manager",
2252 log_error("Could not allocate message.");
2257 if (!dbus_message_append_args(m,
2258 DBUS_TYPE_STRING, name,
2259 DBUS_TYPE_STRING, &arg_kill_who,
2260 DBUS_TYPE_STRING, &arg_kill_mode,
2261 DBUS_TYPE_INT32, &arg_signal,
2262 DBUS_TYPE_INVALID)) {
2263 log_error("Could not append arguments to message.");
2268 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2269 log_error("Failed to issue method call: %s", bus_error_message(&error));
2270 dbus_error_free(&error);
2274 dbus_message_unref(m);
2277 dbus_message_unref(reply);
2283 dbus_message_unref(m);
2285 dbus_error_free(&error);
2290 typedef struct ExecStatusInfo {
2298 usec_t start_timestamp;
2299 usec_t exit_timestamp;
2304 LIST_FIELDS(struct ExecStatusInfo, exec);
2307 static void exec_status_info_free(ExecStatusInfo *i) {
2316 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
2317 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
2318 DBusMessageIter sub2, sub3;
2322 int32_t code, status;
2328 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
2331 dbus_message_iter_recurse(sub, &sub2);
2333 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
2336 if (!(i->path = strdup(path)))
2339 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
2340 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
2344 dbus_message_iter_recurse(&sub2, &sub3);
2345 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
2346 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
2347 dbus_message_iter_next(&sub3);
2352 if (!(i->argv = new0(char*, n+1)))
2356 dbus_message_iter_recurse(&sub2, &sub3);
2357 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
2360 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
2361 dbus_message_iter_get_basic(&sub3, &s);
2362 dbus_message_iter_next(&sub3);
2364 if (!(i->argv[n++] = strdup(s)))
2368 if (!dbus_message_iter_next(&sub2) ||
2369 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
2370 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
2371 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
2372 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
2373 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
2374 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
2375 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
2376 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
2380 i->start_timestamp = (usec_t) start_timestamp;
2381 i->exit_timestamp = (usec_t) exit_timestamp;
2382 i->pid = (pid_t) pid;
2389 typedef struct UnitStatusInfo {
2391 const char *load_state;
2392 const char *active_state;
2393 const char *sub_state;
2394 const char *unit_file_state;
2396 const char *description;
2397 const char *following;
2399 char **documentation;
2401 const char *fragment_path;
2402 const char *source_path;
2403 const char *default_control_group;
2405 const char *load_error;
2408 usec_t inactive_exit_timestamp;
2409 usec_t inactive_exit_timestamp_monotonic;
2410 usec_t active_enter_timestamp;
2411 usec_t active_exit_timestamp;
2412 usec_t inactive_enter_timestamp;
2414 bool need_daemon_reload;
2419 const char *status_text;
2422 usec_t start_timestamp;
2423 usec_t exit_timestamp;
2425 int exit_code, exit_status;
2427 usec_t condition_timestamp;
2428 bool condition_result;
2431 unsigned n_accepted;
2432 unsigned n_connections;
2436 const char *sysfs_path;
2438 /* Mount, Automount */
2444 LIST_HEAD(ExecStatusInfo, exec);
2447 static void print_status_info(UnitStatusInfo *i) {
2449 const char *on, *off, *ss;
2451 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
2452 char since2[FORMAT_TIMESTAMP_MAX], *s2;
2457 /* This shows pretty information about a unit. See
2458 * print_property() for a low-level property printer */
2460 printf("%s", strna(i->id));
2462 if (i->description && !streq_ptr(i->id, i->description))
2463 printf(" - %s", i->description);
2468 printf("\t Follow: unit currently follows state of %s\n", i->following);
2470 if (streq_ptr(i->load_state, "error")) {
2471 on = ansi_highlight_red(true);
2472 off = ansi_highlight_red(false);
2476 path = i->source_path ? i->source_path : i->fragment_path;
2479 printf("\t Loaded: %s%s%s (Reason: %s)\n", on, strna(i->load_state), off, i->load_error);
2480 else if (path && i->unit_file_state)
2481 printf("\t Loaded: %s%s%s (%s; %s)\n", on, strna(i->load_state), off, path, i->unit_file_state);
2483 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, path);
2485 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
2487 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
2489 if (streq_ptr(i->active_state, "failed")) {
2490 on = ansi_highlight_red(true);
2491 off = ansi_highlight_red(false);
2492 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
2493 on = ansi_highlight_green(true);
2494 off = ansi_highlight_green(false);
2499 printf("\t Active: %s%s (%s)%s",
2501 strna(i->active_state),
2505 printf("\t Active: %s%s%s",
2507 strna(i->active_state),
2510 if (!isempty(i->result) && !streq(i->result, "success"))
2511 printf(" (Result: %s)", i->result);
2513 timestamp = (streq_ptr(i->active_state, "active") ||
2514 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
2515 (streq_ptr(i->active_state, "inactive") ||
2516 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
2517 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
2518 i->active_exit_timestamp;
2520 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
2521 s2 = format_timestamp(since2, sizeof(since2), timestamp);
2524 printf(" since %s; %s\n", s2, s1);
2526 printf(" since %s\n", s2);
2530 if (!i->condition_result && i->condition_timestamp > 0) {
2531 s1 = format_timestamp_pretty(since1, sizeof(since1), i->condition_timestamp);
2532 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
2535 printf("\t start condition failed at %s; %s\n", s2, s1);
2537 printf("\t start condition failed at %s\n", s2);
2541 printf("\t Device: %s\n", i->sysfs_path);
2543 printf("\t Where: %s\n", i->where);
2545 printf("\t What: %s\n", i->what);
2547 if (!strv_isempty(i->documentation)) {
2551 STRV_FOREACH(t, i->documentation) {
2553 printf("\t Docs: %s\n", *t);
2556 printf("\t %s\n", *t);
2561 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
2563 LIST_FOREACH(exec, p, i->exec) {
2567 /* Only show exited processes here */
2571 t = strv_join(p->argv, " ");
2572 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
2575 good = is_clean_exit_lsb(p->code, p->status);
2577 on = ansi_highlight_red(true);
2578 off = ansi_highlight_red(false);
2582 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
2584 if (p->code == CLD_EXITED) {
2587 printf("status=%i", p->status);
2589 c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD);
2594 printf("signal=%s", signal_to_string(p->status));
2596 printf(")%s\n", off);
2598 if (i->main_pid == p->pid &&
2599 i->start_timestamp == p->start_timestamp &&
2600 i->exit_timestamp == p->start_timestamp)
2601 /* Let's not show this twice */
2604 if (p->pid == i->control_pid)
2608 if (i->main_pid > 0 || i->control_pid > 0) {
2611 if (i->main_pid > 0) {
2612 printf("Main PID: %u", (unsigned) i->main_pid);
2616 get_process_comm(i->main_pid, &t);
2621 } else if (i->exit_code > 0) {
2622 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2624 if (i->exit_code == CLD_EXITED) {
2627 printf("status=%i", i->exit_status);
2629 c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD);
2634 printf("signal=%s", signal_to_string(i->exit_status));
2639 if (i->main_pid > 0 && i->control_pid > 0)
2642 if (i->control_pid > 0) {
2645 printf(" Control: %u", (unsigned) i->control_pid);
2647 get_process_comm(i->control_pid, &t);
2658 printf("\t Status: \"%s\"\n", i->status_text);
2660 if (i->default_control_group) {
2663 printf("\t CGroup: %s\n", i->default_control_group);
2665 if (arg_transport != TRANSPORT_SSH) {
2675 if (i->main_pid > 0)
2676 extra[k++] = i->main_pid;
2678 if (i->control_pid > 0)
2679 extra[k++] = i->control_pid;
2681 show_cgroup_and_extra_by_spec(i->default_control_group, "\t\t ", c, false, arg_all, extra, k);
2685 if (i->id && arg_transport != TRANSPORT_SSH) {
2687 show_journal_by_unit(i->id, arg_output, 0, i->inactive_exit_timestamp_monotonic, arg_lines, arg_all, arg_follow);
2690 if (i->need_daemon_reload)
2691 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2692 ansi_highlight_red(true),
2693 ansi_highlight_red(false),
2694 arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
2697 static void show_unit_help(UnitStatusInfo *i) {
2702 if (!i->documentation) {
2703 log_info("Documentation for %s not known.", i->id);
2707 STRV_FOREACH(p, i->documentation) {
2709 if (startswith(*p, "man:")) {
2712 char *page = NULL, *section = NULL;
2713 const char *args[4] = { "man", NULL, NULL, NULL };
2718 if ((*p)[k-1] == ')')
2719 e = strrchr(*p, '(');
2722 page = strndup((*p) + 4, e - *p - 4);
2724 log_error("Out of memory.");
2728 section = strndup(e + 1, *p + k - e - 2);
2731 log_error("Out of memory");
2742 log_error("Failed to fork: %m");
2750 execvp(args[0], (char**) args);
2751 log_error("Failed to execute man: %m");
2752 _exit(EXIT_FAILURE);
2758 wait_for_terminate(pid, NULL);
2760 log_info("Can't show %s.", *p);
2764 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2770 switch (dbus_message_iter_get_arg_type(iter)) {
2772 case DBUS_TYPE_STRING: {
2775 dbus_message_iter_get_basic(iter, &s);
2778 if (streq(name, "Id"))
2780 else if (streq(name, "LoadState"))
2782 else if (streq(name, "ActiveState"))
2783 i->active_state = s;
2784 else if (streq(name, "SubState"))
2786 else if (streq(name, "Description"))
2788 else if (streq(name, "FragmentPath"))
2789 i->fragment_path = s;
2790 else if (streq(name, "SourcePath"))
2792 else if (streq(name, "DefaultControlGroup"))
2793 i->default_control_group = s;
2794 else if (streq(name, "StatusText"))
2796 else if (streq(name, "SysFSPath"))
2798 else if (streq(name, "Where"))
2800 else if (streq(name, "What"))
2802 else if (streq(name, "Following"))
2804 else if (streq(name, "UnitFileState"))
2805 i->unit_file_state = s;
2806 else if (streq(name, "Result"))
2813 case DBUS_TYPE_BOOLEAN: {
2816 dbus_message_iter_get_basic(iter, &b);
2818 if (streq(name, "Accept"))
2820 else if (streq(name, "NeedDaemonReload"))
2821 i->need_daemon_reload = b;
2822 else if (streq(name, "ConditionResult"))
2823 i->condition_result = b;
2828 case DBUS_TYPE_UINT32: {
2831 dbus_message_iter_get_basic(iter, &u);
2833 if (streq(name, "MainPID")) {
2835 i->main_pid = (pid_t) u;
2838 } else if (streq(name, "ControlPID"))
2839 i->control_pid = (pid_t) u;
2840 else if (streq(name, "ExecMainPID")) {
2842 i->main_pid = (pid_t) u;
2843 } else if (streq(name, "NAccepted"))
2845 else if (streq(name, "NConnections"))
2846 i->n_connections = u;
2851 case DBUS_TYPE_INT32: {
2854 dbus_message_iter_get_basic(iter, &j);
2856 if (streq(name, "ExecMainCode"))
2857 i->exit_code = (int) j;
2858 else if (streq(name, "ExecMainStatus"))
2859 i->exit_status = (int) j;
2864 case DBUS_TYPE_UINT64: {
2867 dbus_message_iter_get_basic(iter, &u);
2869 if (streq(name, "ExecMainStartTimestamp"))
2870 i->start_timestamp = (usec_t) u;
2871 else if (streq(name, "ExecMainExitTimestamp"))
2872 i->exit_timestamp = (usec_t) u;
2873 else if (streq(name, "ActiveEnterTimestamp"))
2874 i->active_enter_timestamp = (usec_t) u;
2875 else if (streq(name, "InactiveEnterTimestamp"))
2876 i->inactive_enter_timestamp = (usec_t) u;
2877 else if (streq(name, "InactiveExitTimestamp"))
2878 i->inactive_exit_timestamp = (usec_t) u;
2879 else if (streq(name, "InactiveExitTimestampMonotonic"))
2880 i->inactive_exit_timestamp_monotonic = (usec_t) u;
2881 else if (streq(name, "ActiveExitTimestamp"))
2882 i->active_exit_timestamp = (usec_t) u;
2883 else if (streq(name, "ConditionTimestamp"))
2884 i->condition_timestamp = (usec_t) u;
2889 case DBUS_TYPE_ARRAY: {
2891 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2892 startswith(name, "Exec")) {
2893 DBusMessageIter sub;
2895 dbus_message_iter_recurse(iter, &sub);
2896 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2897 ExecStatusInfo *info;
2900 if (!(info = new0(ExecStatusInfo, 1)))
2903 if (!(info->name = strdup(name))) {
2908 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2913 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2915 dbus_message_iter_next(&sub);
2917 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING &&
2918 streq(name, "Documentation")) {
2920 DBusMessageIter sub;
2922 dbus_message_iter_recurse(iter, &sub);
2923 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING) {
2927 dbus_message_iter_get_basic(&sub, &s);
2929 l = strv_append(i->documentation, s);
2933 strv_free(i->documentation);
2934 i->documentation = l;
2936 dbus_message_iter_next(&sub);
2943 case DBUS_TYPE_STRUCT: {
2945 if (streq(name, "LoadError")) {
2946 DBusMessageIter sub;
2947 const char *n, *message;
2950 dbus_message_iter_recurse(iter, &sub);
2952 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &n, true);
2956 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &message, false);
2960 if (!isempty(message))
2961 i->load_error = message;
2971 static int print_property(const char *name, DBusMessageIter *iter) {
2975 /* This is a low-level property printer, see
2976 * print_status_info() for the nicer output */
2978 if (arg_property && !strv_find(arg_property, name))
2981 switch (dbus_message_iter_get_arg_type(iter)) {
2983 case DBUS_TYPE_STRUCT: {
2984 DBusMessageIter sub;
2985 dbus_message_iter_recurse(iter, &sub);
2987 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2990 dbus_message_iter_get_basic(&sub, &u);
2993 printf("%s=%u\n", name, (unsigned) u);
2995 printf("%s=\n", name);
2998 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
3001 dbus_message_iter_get_basic(&sub, &s);
3003 if (arg_all || s[0])
3004 printf("%s=%s\n", name, s);
3007 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "LoadError")) {
3008 const char *a = NULL, *b = NULL;
3010 if (bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &a, true) >= 0)
3011 bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &b, false);
3013 if (arg_all || !isempty(a) || !isempty(b))
3014 printf("%s=%s \"%s\"\n", name, strempty(a), strempty(b));
3022 case DBUS_TYPE_ARRAY:
3024 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
3025 DBusMessageIter sub, sub2;
3027 dbus_message_iter_recurse(iter, &sub);
3028 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3032 dbus_message_iter_recurse(&sub, &sub2);
3034 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
3035 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
3036 printf("EnvironmentFile=%s (ignore_errors=%s)\n", path, yes_no(ignore));
3038 dbus_message_iter_next(&sub);
3043 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
3044 DBusMessageIter sub, sub2;
3046 dbus_message_iter_recurse(iter, &sub);
3047 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3048 const char *type, *path;
3050 dbus_message_iter_recurse(&sub, &sub2);
3052 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
3053 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
3054 printf("%s=%s\n", type, path);
3056 dbus_message_iter_next(&sub);
3061 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
3062 DBusMessageIter sub, sub2;
3064 dbus_message_iter_recurse(iter, &sub);
3065 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3067 uint64_t value, next_elapse;
3069 dbus_message_iter_recurse(&sub, &sub2);
3071 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
3072 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
3073 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
3074 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
3076 printf("%s={ value=%s ; next_elapse=%s }\n",
3078 format_timespan(timespan1, sizeof(timespan1), value),
3079 format_timespan(timespan2, sizeof(timespan2), next_elapse));
3082 dbus_message_iter_next(&sub);
3087 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "ControlGroupAttributes")) {
3088 DBusMessageIter sub, sub2;
3090 dbus_message_iter_recurse(iter, &sub);
3091 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3092 const char *controller, *attr, *value;
3094 dbus_message_iter_recurse(&sub, &sub2);
3096 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &controller, true) >= 0 &&
3097 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &attr, true) >= 0 &&
3098 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &value, false) >= 0) {
3100 printf("ControlGroupAttribute={ controller=%s ; attribute=%s ; value=\"%s\" }\n",
3106 dbus_message_iter_next(&sub);
3111 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
3112 DBusMessageIter sub;
3114 dbus_message_iter_recurse(iter, &sub);
3115 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3116 ExecStatusInfo info;
3119 if (exec_status_info_deserialize(&sub, &info) >= 0) {
3120 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
3123 t = strv_join(info.argv, " ");
3125 printf("%s={ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
3129 yes_no(info.ignore),
3130 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
3131 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
3132 (unsigned) info. pid,
3133 sigchld_code_to_string(info.code),
3135 info.code == CLD_EXITED ? "" : "/",
3136 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
3142 strv_free(info.argv);
3144 dbus_message_iter_next(&sub);
3153 if (generic_print_property(name, iter, arg_all) > 0)
3157 printf("%s=[unprintable]\n", name);
3162 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
3163 DBusMessage *m = NULL, *reply = NULL;
3164 const char *interface = "";
3167 DBusMessageIter iter, sub, sub2, sub3;
3168 UnitStatusInfo info;
3176 dbus_error_init(&error);
3178 if (!(m = dbus_message_new_method_call(
3179 "org.freedesktop.systemd1",
3181 "org.freedesktop.DBus.Properties",
3183 log_error("Could not allocate message.");
3188 if (!dbus_message_append_args(m,
3189 DBUS_TYPE_STRING, &interface,
3190 DBUS_TYPE_INVALID)) {
3191 log_error("Could not append arguments to message.");
3196 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3197 log_error("Failed to issue method call: %s", bus_error_message(&error));
3202 if (!dbus_message_iter_init(reply, &iter) ||
3203 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
3204 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
3205 log_error("Failed to parse reply.");
3210 dbus_message_iter_recurse(&iter, &sub);
3217 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
3220 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
3221 log_error("Failed to parse reply.");
3226 dbus_message_iter_recurse(&sub, &sub2);
3228 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
3229 log_error("Failed to parse reply.");
3234 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
3235 log_error("Failed to parse reply.");
3240 dbus_message_iter_recurse(&sub2, &sub3);
3242 if (show_properties)
3243 r = print_property(name, &sub3);
3245 r = status_property(name, &sub3, &info);
3248 log_error("Failed to parse reply.");
3253 dbus_message_iter_next(&sub);
3258 if (!show_properties) {
3259 if (streq(verb, "help"))
3260 show_unit_help(&info);
3262 print_status_info(&info);
3265 strv_free(info.documentation);
3267 if (!streq_ptr(info.active_state, "active") &&
3268 !streq_ptr(info.active_state, "reloading") &&
3269 streq(verb, "status"))
3270 /* According to LSB: "program not running" */
3273 while ((p = info.exec)) {
3274 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
3275 exec_status_info_free(p);
3280 dbus_message_unref(m);
3283 dbus_message_unref(reply);
3285 dbus_error_free(&error);
3290 static int show_one_by_pid(const char *verb, DBusConnection *bus, uint32_t pid, bool *new_line) {
3291 DBusMessage *m = NULL, *reply = NULL;
3292 const char *path = NULL;
3296 dbus_error_init(&error);
3298 m = dbus_message_new_method_call(
3299 "org.freedesktop.systemd1",
3300 "/org/freedesktop/systemd1",
3301 "org.freedesktop.systemd1.Manager",
3304 log_error("Could not allocate message.");
3309 if (!dbus_message_append_args(m,
3310 DBUS_TYPE_UINT32, &pid,
3311 DBUS_TYPE_INVALID)) {
3312 log_error("Could not append arguments to message.");
3317 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3319 log_error("Failed to issue method call: %s", bus_error_message(&error));
3324 if (!dbus_message_get_args(reply, &error,
3325 DBUS_TYPE_OBJECT_PATH, &path,
3326 DBUS_TYPE_INVALID)) {
3327 log_error("Failed to parse reply: %s", bus_error_message(&error));
3332 r = show_one(verb, bus, path, false, new_line);
3336 dbus_message_unref(m);
3339 dbus_message_unref(reply);
3341 dbus_error_free(&error);
3346 static int show(DBusConnection *bus, char **args) {
3348 bool show_properties, new_line = false;
3354 show_properties = streq(args[0], "show");
3356 if (show_properties)
3357 pager_open_if_enabled();
3359 if (show_properties && strv_length(args) <= 1) {
3360 /* If not argument is specified inspect the manager
3363 return show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
3366 STRV_FOREACH(name, args+1) {
3369 if (safe_atou32(*name, &id) < 0) {
3371 /* Interpret as unit name */
3374 e = bus_path_escape(*name);
3377 p = strappend("/org/freedesktop/systemd1/unit/", e);
3382 r = show_one(args[0], bus, p, show_properties, &new_line);
3388 } else if (show_properties) {
3390 /* Interpret as job id */
3393 if (asprintf(&p, "/org/freedesktop/systemd1/job/%u", id) < 0)
3396 r = show_one(args[0], bus, p, show_properties, &new_line);
3404 /* Interpret as PID */
3406 r = show_one_by_pid(args[0], bus, id, &new_line);
3415 static int dump(DBusConnection *bus, char **args) {
3416 DBusMessage *m = NULL, *reply = NULL;
3421 dbus_error_init(&error);
3423 pager_open_if_enabled();
3425 if (!(m = dbus_message_new_method_call(
3426 "org.freedesktop.systemd1",
3427 "/org/freedesktop/systemd1",
3428 "org.freedesktop.systemd1.Manager",
3430 log_error("Could not allocate message.");
3434 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3435 log_error("Failed to issue method call: %s", bus_error_message(&error));
3440 if (!dbus_message_get_args(reply, &error,
3441 DBUS_TYPE_STRING, &text,
3442 DBUS_TYPE_INVALID)) {
3443 log_error("Failed to parse reply: %s", bus_error_message(&error));
3448 fputs(text, stdout);
3454 dbus_message_unref(m);
3457 dbus_message_unref(reply);
3459 dbus_error_free(&error);
3464 static int snapshot(DBusConnection *bus, char **args) {
3465 DBusMessage *m = NULL, *reply = NULL;
3468 const char *name = "", *path, *id;
3469 dbus_bool_t cleanup = FALSE;
3470 DBusMessageIter iter, sub;
3472 *interface = "org.freedesktop.systemd1.Unit",
3475 dbus_error_init(&error);
3477 if (!(m = dbus_message_new_method_call(
3478 "org.freedesktop.systemd1",
3479 "/org/freedesktop/systemd1",
3480 "org.freedesktop.systemd1.Manager",
3481 "CreateSnapshot"))) {
3482 log_error("Could not allocate message.");
3486 if (strv_length(args) > 1)
3489 if (!dbus_message_append_args(m,
3490 DBUS_TYPE_STRING, &name,
3491 DBUS_TYPE_BOOLEAN, &cleanup,
3492 DBUS_TYPE_INVALID)) {
3493 log_error("Could not append arguments to message.");
3498 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3499 log_error("Failed to issue method call: %s", bus_error_message(&error));
3504 if (!dbus_message_get_args(reply, &error,
3505 DBUS_TYPE_OBJECT_PATH, &path,
3506 DBUS_TYPE_INVALID)) {
3507 log_error("Failed to parse reply: %s", bus_error_message(&error));
3512 dbus_message_unref(m);
3513 if (!(m = dbus_message_new_method_call(
3514 "org.freedesktop.systemd1",
3516 "org.freedesktop.DBus.Properties",
3518 log_error("Could not allocate message.");
3522 if (!dbus_message_append_args(m,
3523 DBUS_TYPE_STRING, &interface,
3524 DBUS_TYPE_STRING, &property,
3525 DBUS_TYPE_INVALID)) {
3526 log_error("Could not append arguments to message.");
3531 dbus_message_unref(reply);
3532 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3533 log_error("Failed to issue method call: %s", bus_error_message(&error));
3538 if (!dbus_message_iter_init(reply, &iter) ||
3539 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3540 log_error("Failed to parse reply.");
3545 dbus_message_iter_recurse(&iter, &sub);
3547 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3548 log_error("Failed to parse reply.");
3553 dbus_message_iter_get_basic(&sub, &id);
3561 dbus_message_unref(m);
3564 dbus_message_unref(reply);
3566 dbus_error_free(&error);
3571 static int delete_snapshot(DBusConnection *bus, char **args) {
3572 DBusMessage *m = NULL, *reply = NULL;
3580 dbus_error_init(&error);
3582 STRV_FOREACH(name, args+1) {
3583 const char *path = NULL;
3585 if (!(m = dbus_message_new_method_call(
3586 "org.freedesktop.systemd1",
3587 "/org/freedesktop/systemd1",
3588 "org.freedesktop.systemd1.Manager",
3590 log_error("Could not allocate message.");
3595 if (!dbus_message_append_args(m,
3596 DBUS_TYPE_STRING, name,
3597 DBUS_TYPE_INVALID)) {
3598 log_error("Could not append arguments to message.");
3603 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3604 log_error("Failed to issue method call: %s", bus_error_message(&error));
3609 if (!dbus_message_get_args(reply, &error,
3610 DBUS_TYPE_OBJECT_PATH, &path,
3611 DBUS_TYPE_INVALID)) {
3612 log_error("Failed to parse reply: %s", bus_error_message(&error));
3617 dbus_message_unref(m);
3618 if (!(m = dbus_message_new_method_call(
3619 "org.freedesktop.systemd1",
3621 "org.freedesktop.systemd1.Snapshot",
3623 log_error("Could not allocate message.");
3628 dbus_message_unref(reply);
3629 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3630 log_error("Failed to issue method call: %s", bus_error_message(&error));
3635 dbus_message_unref(m);
3636 dbus_message_unref(reply);
3644 dbus_message_unref(m);
3647 dbus_message_unref(reply);
3649 dbus_error_free(&error);
3654 static int daemon_reload(DBusConnection *bus, char **args) {
3655 DBusMessage *m = NULL, *reply = NULL;
3660 dbus_error_init(&error);
3662 if (arg_action == ACTION_RELOAD)
3664 else if (arg_action == ACTION_REEXEC)
3665 method = "Reexecute";
3667 assert(arg_action == ACTION_SYSTEMCTL);
3670 streq(args[0], "clear-jobs") ||
3671 streq(args[0], "cancel") ? "ClearJobs" :
3672 streq(args[0], "daemon-reexec") ? "Reexecute" :
3673 streq(args[0], "reset-failed") ? "ResetFailed" :
3674 streq(args[0], "halt") ? "Halt" :
3675 streq(args[0], "poweroff") ? "PowerOff" :
3676 streq(args[0], "reboot") ? "Reboot" :
3677 streq(args[0], "kexec") ? "KExec" :
3678 streq(args[0], "exit") ? "Exit" :
3679 /* "daemon-reload" */ "Reload";
3682 if (!(m = dbus_message_new_method_call(
3683 "org.freedesktop.systemd1",
3684 "/org/freedesktop/systemd1",
3685 "org.freedesktop.systemd1.Manager",
3687 log_error("Could not allocate message.");
3691 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3693 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3694 /* There's always a fallback possible for
3695 * legacy actions. */
3700 if (streq(method, "Reexecute") && dbus_error_has_name(&error, DBUS_ERROR_NO_REPLY)) {
3701 /* On reexecution, we expect a disconnect, not
3707 log_error("Failed to issue method call: %s", bus_error_message(&error));
3716 dbus_message_unref(m);
3719 dbus_message_unref(reply);
3721 dbus_error_free(&error);
3726 static int reset_failed(DBusConnection *bus, char **args) {
3727 DBusMessage *m = NULL;
3733 dbus_error_init(&error);
3735 if (strv_length(args) <= 1)
3736 return daemon_reload(bus, args);
3738 STRV_FOREACH(name, args+1) {
3741 if (!(m = dbus_message_new_method_call(
3742 "org.freedesktop.systemd1",
3743 "/org/freedesktop/systemd1",
3744 "org.freedesktop.systemd1.Manager",
3745 "ResetFailedUnit"))) {
3746 log_error("Could not allocate message.");
3751 if (!dbus_message_append_args(m,
3752 DBUS_TYPE_STRING, name,
3753 DBUS_TYPE_INVALID)) {
3754 log_error("Could not append arguments to message.");
3759 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3760 log_error("Failed to issue method call: %s", bus_error_message(&error));
3765 dbus_message_unref(m);
3766 dbus_message_unref(reply);
3774 dbus_message_unref(m);
3776 dbus_error_free(&error);
3781 static int show_enviroment(DBusConnection *bus, char **args) {
3782 DBusMessage *m = NULL, *reply = NULL;
3784 DBusMessageIter iter, sub, sub2;
3787 *interface = "org.freedesktop.systemd1.Manager",
3788 *property = "Environment";
3790 dbus_error_init(&error);
3792 pager_open_if_enabled();
3794 if (!(m = dbus_message_new_method_call(
3795 "org.freedesktop.systemd1",
3796 "/org/freedesktop/systemd1",
3797 "org.freedesktop.DBus.Properties",
3799 log_error("Could not allocate message.");
3803 if (!dbus_message_append_args(m,
3804 DBUS_TYPE_STRING, &interface,
3805 DBUS_TYPE_STRING, &property,
3806 DBUS_TYPE_INVALID)) {
3807 log_error("Could not append arguments to message.");
3812 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3813 log_error("Failed to issue method call: %s", bus_error_message(&error));
3818 if (!dbus_message_iter_init(reply, &iter) ||
3819 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3820 log_error("Failed to parse reply.");
3825 dbus_message_iter_recurse(&iter, &sub);
3827 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3828 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3829 log_error("Failed to parse reply.");
3834 dbus_message_iter_recurse(&sub, &sub2);
3836 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3839 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3840 log_error("Failed to parse reply.");
3845 dbus_message_iter_get_basic(&sub2, &text);
3846 printf("%s\n", text);
3848 dbus_message_iter_next(&sub2);
3855 dbus_message_unref(m);
3858 dbus_message_unref(reply);
3860 dbus_error_free(&error);
3865 static int switch_root(DBusConnection *bus, char **args) {
3866 DBusMessage *m = NULL, *reply = NULL;
3868 const char *root, *init;
3872 dbus_error_init(&error);
3874 l = strv_length(args);
3875 if (l < 2 || l > 3) {
3876 log_error("Wrong number of arguments.");
3881 init = l >= 3 ? args[2] : "";
3883 m = dbus_message_new_method_call(
3884 "org.freedesktop.systemd1",
3885 "/org/freedesktop/systemd1",
3886 "org.freedesktop.systemd1.Manager",
3889 log_error("Could not allocate message.");
3893 if (!dbus_message_append_args(
3895 DBUS_TYPE_STRING, &root,
3896 DBUS_TYPE_STRING, &init,
3897 DBUS_TYPE_INVALID)) {
3898 log_error("Could not append arguments to message.");
3903 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3905 log_error("Failed to issue method call: %s", bus_error_message(&error));
3914 dbus_message_unref(m);
3917 dbus_message_unref(reply);
3919 dbus_error_free(&error);
3924 static int set_environment(DBusConnection *bus, char **args) {
3925 DBusMessage *m = NULL, *reply = NULL;
3929 DBusMessageIter iter, sub;
3932 dbus_error_init(&error);
3934 method = streq(args[0], "set-environment")
3936 : "UnsetEnvironment";
3938 if (!(m = dbus_message_new_method_call(
3939 "org.freedesktop.systemd1",
3940 "/org/freedesktop/systemd1",
3941 "org.freedesktop.systemd1.Manager",
3944 log_error("Could not allocate message.");
3948 dbus_message_iter_init_append(m, &iter);
3950 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3951 log_error("Could not append arguments to message.");
3956 STRV_FOREACH(name, args+1)
3957 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, name)) {
3958 log_error("Could not append arguments to message.");
3963 if (!dbus_message_iter_close_container(&iter, &sub)) {
3964 log_error("Could not append arguments to message.");
3969 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3970 log_error("Failed to issue method call: %s", bus_error_message(&error));
3979 dbus_message_unref(m);
3982 dbus_message_unref(reply);
3984 dbus_error_free(&error);
3989 static int enable_sysv_units(char **args) {
3992 #if defined (HAVE_SYSV_COMPAT) && (defined(TARGET_FEDORA) || defined(TARGET_MANDRIVA) || defined(TARGET_SUSE) || defined(TARGET_MEEGO) || defined(TARGET_ALTLINUX) || defined(TARGET_MAGEIA))
3993 const char *verb = args[0];
3994 unsigned f = 1, t = 1;
3997 if (arg_scope != UNIT_FILE_SYSTEM)
4000 if (!streq(verb, "enable") &&
4001 !streq(verb, "disable") &&
4002 !streq(verb, "is-enabled"))
4005 /* Processes all SysV units, and reshuffles the array so that
4006 * afterwards only the native units remain */
4009 r = lookup_paths_init(&paths, MANAGER_SYSTEM, false, NULL, NULL, NULL);
4014 for (f = 1; args[f]; f++) {
4017 bool found_native = false, found_sysv;
4019 const char *argv[6] = { "/sbin/chkconfig", NULL, NULL, NULL, NULL };
4020 char **k, *l, *q = NULL;
4027 if (!endswith(name, ".service"))
4030 if (path_is_absolute(name))
4033 STRV_FOREACH(k, paths.unit_path) {
4036 if (!isempty(arg_root))
4037 asprintf(&p, "%s/%s/%s", arg_root, *k, name);
4039 asprintf(&p, "%s/%s", *k, name);
4042 log_error("No memory");
4047 found_native = access(p, F_OK) >= 0;
4058 if (!isempty(arg_root))
4059 asprintf(&p, "%s/" SYSTEM_SYSVINIT_PATH "/%s", arg_root, name);
4061 asprintf(&p, SYSTEM_SYSVINIT_PATH "/%s", name);
4063 log_error("No memory");
4068 p[strlen(p) - sizeof(".service") + 1] = 0;
4069 found_sysv = access(p, F_OK) >= 0;
4076 /* Mark this entry, so that we don't try enabling it as native unit */
4077 args[f] = (char*) "";
4079 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", name);
4081 if (!isempty(arg_root))
4082 argv[c++] = q = strappend("--root=", arg_root);
4084 argv[c++] = path_get_file_name(p);
4086 streq(verb, "enable") ? "on" :
4087 streq(verb, "disable") ? "off" : "--level=5";
4090 l = strv_join((char**)argv, " ");
4092 log_error("No memory.");
4099 log_info("Executing %s", l);
4104 log_error("Failed to fork: %m");
4109 } else if (pid == 0) {
4112 execv(argv[0], (char**) argv);
4113 _exit(EXIT_FAILURE);
4119 j = wait_for_terminate(pid, &status);
4121 log_error("Failed to wait for child: %s", strerror(-r));
4126 if (status.si_code == CLD_EXITED) {
4127 if (streq(verb, "is-enabled")) {
4128 if (status.si_status == 0) {
4137 } else if (status.si_status != 0) {
4148 lookup_paths_free(&paths);
4150 /* Drop all SysV units */
4151 for (f = 1, t = 1; args[f]; f++) {
4153 if (isempty(args[f]))
4156 args[t++] = args[f];
4165 static int enable_unit(DBusConnection *bus, char **args) {
4166 const char *verb = args[0];
4167 UnitFileChange *changes = NULL;
4168 unsigned n_changes = 0, i;
4169 int carries_install_info = -1;
4170 DBusMessage *m = NULL, *reply = NULL;
4174 r = enable_sysv_units(args);
4181 dbus_error_init(&error);
4183 if (!bus || avoid_bus()) {
4184 if (streq(verb, "enable")) {
4185 r = unit_file_enable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4186 carries_install_info = r;
4187 } else if (streq(verb, "disable"))
4188 r = unit_file_disable(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
4189 else if (streq(verb, "reenable")) {
4190 r = unit_file_reenable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4191 carries_install_info = r;
4192 } else if (streq(verb, "link"))
4193 r = unit_file_link(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4194 else if (streq(verb, "preset")) {
4195 r = unit_file_preset(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4196 carries_install_info = r;
4197 } else if (streq(verb, "mask"))
4198 r = unit_file_mask(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4199 else if (streq(verb, "unmask"))
4200 r = unit_file_unmask(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
4202 assert_not_reached("Unknown verb");
4205 log_error("Operation failed: %s", strerror(-r));
4210 for (i = 0; i < n_changes; i++) {
4211 if (changes[i].type == UNIT_FILE_SYMLINK)
4212 log_info("ln -s '%s' '%s'", changes[i].source, changes[i].path);
4214 log_info("rm '%s'", changes[i].path);
4220 bool send_force = true, expect_carries_install_info = false;
4222 DBusMessageIter iter, sub, sub2;
4224 if (streq(verb, "enable")) {
4225 method = "EnableUnitFiles";
4226 expect_carries_install_info = true;
4227 } else if (streq(verb, "disable")) {
4228 method = "DisableUnitFiles";
4230 } else if (streq(verb, "reenable")) {
4231 method = "ReenableUnitFiles";
4232 expect_carries_install_info = true;
4233 } else if (streq(verb, "link"))
4234 method = "LinkUnitFiles";
4235 else if (streq(verb, "preset")) {
4236 method = "PresetUnitFiles";
4237 expect_carries_install_info = true;
4238 } else if (streq(verb, "mask"))
4239 method = "MaskUnitFiles";
4240 else if (streq(verb, "unmask")) {
4241 method = "UnmaskUnitFiles";
4244 assert_not_reached("Unknown verb");
4246 m = dbus_message_new_method_call(
4247 "org.freedesktop.systemd1",
4248 "/org/freedesktop/systemd1",
4249 "org.freedesktop.systemd1.Manager",
4252 log_error("Out of memory");
4257 dbus_message_iter_init_append(m, &iter);
4259 r = bus_append_strv_iter(&iter, args+1);
4261 log_error("Failed to append unit files.");
4266 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &a)) {
4267 log_error("Failed to append runtime boolean.");
4275 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b)) {
4276 log_error("Failed to append force boolean.");
4282 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
4284 log_error("Failed to issue method call: %s", bus_error_message(&error));
4289 if (!dbus_message_iter_init(reply, &iter)) {
4290 log_error("Failed to initialize iterator.");
4294 if (expect_carries_install_info) {
4295 r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_BOOLEAN, &b, true);
4297 log_error("Failed to parse reply.");
4301 carries_install_info = b;
4304 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
4305 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
4306 log_error("Failed to parse reply.");
4311 dbus_message_iter_recurse(&iter, &sub);
4312 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
4313 const char *type, *path, *source;
4315 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
4316 log_error("Failed to parse reply.");
4321 dbus_message_iter_recurse(&sub, &sub2);
4323 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
4324 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0 ||
4325 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &source, false) < 0) {
4326 log_error("Failed to parse reply.");
4332 if (streq(type, "symlink"))
4333 log_info("ln -s '%s' '%s'", source, path);
4335 log_info("rm '%s'", path);
4338 dbus_message_iter_next(&sub);
4341 /* Try to reload if enabeld */
4343 r = daemon_reload(bus, args);
4346 if (carries_install_info == 0)
4347 log_warning("Warning: unit files do not carry install information. No operation executed.");
4351 dbus_message_unref(m);
4354 dbus_message_unref(reply);
4356 unit_file_changes_free(changes, n_changes);
4358 dbus_error_free(&error);
4362 static int unit_is_enabled(DBusConnection *bus, char **args) {
4365 DBusMessage *m = NULL, *reply = NULL;
4369 dbus_error_init(&error);
4371 r = enable_sysv_units(args);
4377 if (!bus || avoid_bus()) {
4379 STRV_FOREACH(name, args+1) {
4380 UnitFileState state;
4382 state = unit_file_get_state(arg_scope, arg_root, *name);
4388 if (state == UNIT_FILE_ENABLED ||
4389 state == UNIT_FILE_ENABLED_RUNTIME ||
4390 state == UNIT_FILE_STATIC)
4394 puts(unit_file_state_to_string(state));
4398 STRV_FOREACH(name, args+1) {
4401 m = dbus_message_new_method_call(
4402 "org.freedesktop.systemd1",
4403 "/org/freedesktop/systemd1",
4404 "org.freedesktop.systemd1.Manager",
4405 "GetUnitFileState");
4407 log_error("Out of memory");
4412 if (!dbus_message_append_args(m,
4413 DBUS_TYPE_STRING, name,
4414 DBUS_TYPE_INVALID)) {
4415 log_error("Could not append arguments to message.");
4420 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
4422 log_error("Failed to issue method call: %s", bus_error_message(&error));
4427 if (!dbus_message_get_args(reply, &error,
4428 DBUS_TYPE_STRING, &s,
4429 DBUS_TYPE_INVALID)) {
4430 log_error("Failed to parse reply: %s", bus_error_message(&error));
4435 dbus_message_unref(m);
4436 dbus_message_unref(reply);
4439 if (streq(s, "enabled") ||
4440 streq(s, "enabled-runtime") ||
4449 r = enabled ? 0 : 1;
4453 dbus_message_unref(m);
4456 dbus_message_unref(reply);
4458 dbus_error_free(&error);
4462 static int systemctl_help(void) {
4464 pager_open_if_enabled();
4466 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4467 "Query or send control commands to the systemd manager.\n\n"
4468 " -h --help Show this help\n"
4469 " --version Show package version\n"
4470 " -t --type=TYPE List only units of a particular type\n"
4471 " -p --property=NAME Show only properties by this name\n"
4472 " -a --all Show all units/properties, including dead/empty ones\n"
4473 " --failed Show only failed units\n"
4474 " --full Don't ellipsize unit names on output\n"
4475 " --fail When queueing a new job, fail if conflicting jobs are\n"
4477 " --ignore-dependencies\n"
4478 " When queueing a new job, ignore all its dependencies\n"
4479 " --kill-who=WHO Who to send signal to\n"
4480 " -s --signal=SIGNAL Which signal to send\n"
4481 " -H --host=[USER@]HOST\n"
4482 " Show information for remote host\n"
4483 " -P --privileged Acquire privileges before execution\n"
4484 " -q --quiet Suppress output\n"
4485 " --no-block Do not wait until operation finished\n"
4486 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4487 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4489 " --no-legend Do not print a legend (column headers and hints)\n"
4490 " --no-pager Do not pipe output into a pager\n"
4491 " --no-ask-password\n"
4492 " Do not ask for system passwords\n"
4493 " --order When generating graph for dot, show only order\n"
4494 " --require When generating graph for dot, show only requirement\n"
4495 " --system Connect to system manager\n"
4496 " --user Connect to user service manager\n"
4497 " --global Enable/disable unit files globally\n"
4498 " -f --force When enabling unit files, override existing symlinks\n"
4499 " When shutting down, execute action immediately\n"
4500 " --root=PATH Enable unit files in the specified root directory\n"
4501 " --runtime Enable unit files only temporarily until next reboot\n"
4502 " -n --lines=INTEGER Journal entries to show\n"
4503 " --follow Follow journal\n"
4504 " -o --output=STRING Change journal output mode (short, short-monotonic,\n"
4505 " verbose, export, json, cat)\n\n"
4507 " list-units List loaded units\n"
4508 " start [NAME...] Start (activate) one or more units\n"
4509 " stop [NAME...] Stop (deactivate) one or more units\n"
4510 " reload [NAME...] Reload one or more units\n"
4511 " restart [NAME...] Start or restart one or more units\n"
4512 " try-restart [NAME...] Restart one or more units if active\n"
4513 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4514 " otherwise start or restart\n"
4515 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4516 " otherwise restart if active\n"
4517 " isolate [NAME] Start one unit and stop all others\n"
4518 " kill [NAME...] Send signal to processes of a unit\n"
4519 " is-active [NAME...] Check whether units are active\n"
4520 " status [NAME...|PID...] Show runtime status of one or more units\n"
4521 " show [NAME...|JOB...] Show properties of one or more\n"
4522 " units/jobs or the manager\n"
4523 " help [NAME...|PID...] Show manual for one or more units\n"
4524 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4526 " load [NAME...] Load one or more units\n\n"
4527 "Unit File Commands:\n"
4528 " list-unit-files List installed unit files\n"
4529 " enable [NAME...] Enable one or more unit files\n"
4530 " disable [NAME...] Disable one or more unit files\n"
4531 " reenable [NAME...] Reenable one or more unit files\n"
4532 " preset [NAME...] Enable/disable one or more unit files\n"
4533 " based on preset configuration\n"
4534 " mask [NAME...] Mask one or more units\n"
4535 " unmask [NAME...] Unmask one or more units\n"
4536 " link [PATH...] Link one or more units files into\n"
4537 " the search path\n"
4538 " is-enabled [NAME...] Check whether unit files are enabled\n\n"
4540 " list-jobs List jobs\n"
4541 " cancel [JOB...] Cancel all, one, or more jobs\n\n"
4542 "Status Commands:\n"
4543 " dump Dump server status\n"
4544 " dot Dump dependency graph for dot(1)\n\n"
4545 "Snapshot Commands:\n"
4546 " snapshot [NAME] Create a snapshot\n"
4547 " delete [NAME...] Remove one or more snapshots\n\n"
4548 "Environment Commands:\n"
4549 " show-environment Dump environment\n"
4550 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4551 " unset-environment [NAME...] Unset one or more environment variables\n\n"
4552 "Manager Lifecycle Commands:\n"
4553 " daemon-reload Reload systemd manager configuration\n"
4554 " daemon-reexec Reexecute systemd manager\n\n"
4555 "System Commands:\n"
4556 " default Enter system default mode\n"
4557 " rescue Enter system rescue mode\n"
4558 " emergency Enter system emergency mode\n"
4559 " halt Shut down and halt the system\n"
4560 " poweroff Shut down and power-off the system\n"
4561 " reboot Shut down and reboot the system\n"
4562 " kexec Shut down and reboot the system with kexec\n"
4563 " exit Request user instance exit\n"
4564 " switch-root [ROOT] [INIT] Change to a different root file system\n"
4565 " suspend Suspend the system\n"
4566 " hibernate Hibernate the system\n",
4567 program_invocation_short_name);
4572 static int halt_help(void) {
4574 printf("%s [OPTIONS...]\n\n"
4575 "%s the system.\n\n"
4576 " --help Show this help\n"
4577 " --halt Halt the machine\n"
4578 " -p --poweroff Switch off the machine\n"
4579 " --reboot Reboot the machine\n"
4580 " -f --force Force immediate halt/power-off/reboot\n"
4581 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4582 " -d --no-wtmp Don't write wtmp record\n"
4583 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4584 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4585 program_invocation_short_name,
4586 arg_action == ACTION_REBOOT ? "Reboot" :
4587 arg_action == ACTION_POWEROFF ? "Power off" :
4593 static int shutdown_help(void) {
4595 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4596 "Shut down the system.\n\n"
4597 " --help Show this help\n"
4598 " -H --halt Halt the machine\n"
4599 " -P --poweroff Power-off the machine\n"
4600 " -r --reboot Reboot the machine\n"
4601 " -h Equivalent to --poweroff, overridden by --halt\n"
4602 " -k Don't halt/power-off/reboot, just send warnings\n"
4603 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4604 " -c Cancel a pending shutdown\n",
4605 program_invocation_short_name);
4610 static int telinit_help(void) {
4612 printf("%s [OPTIONS...] {COMMAND}\n\n"
4613 "Send control commands to the init daemon.\n\n"
4614 " --help Show this help\n"
4615 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4617 " 0 Power-off the machine\n"
4618 " 6 Reboot the machine\n"
4619 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4620 " 1, s, S Enter rescue mode\n"
4621 " q, Q Reload init daemon configuration\n"
4622 " u, U Reexecute init daemon\n",
4623 program_invocation_short_name);
4628 static int runlevel_help(void) {
4630 printf("%s [OPTIONS...]\n\n"
4631 "Prints the previous and current runlevel of the init system.\n\n"
4632 " --help Show this help\n",
4633 program_invocation_short_name);
4638 static int systemctl_parse_argv(int argc, char *argv[]) {
4642 ARG_IGNORE_DEPENDENCIES,
4658 ARG_NO_ASK_PASSWORD,
4665 static const struct option options[] = {
4666 { "help", no_argument, NULL, 'h' },
4667 { "version", no_argument, NULL, ARG_VERSION },
4668 { "type", required_argument, NULL, 't' },
4669 { "property", required_argument, NULL, 'p' },
4670 { "all", no_argument, NULL, 'a' },
4671 { "failed", no_argument, NULL, ARG_FAILED },
4672 { "full", no_argument, NULL, ARG_FULL },
4673 { "fail", no_argument, NULL, ARG_FAIL },
4674 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4675 { "user", no_argument, NULL, ARG_USER },
4676 { "system", no_argument, NULL, ARG_SYSTEM },
4677 { "global", no_argument, NULL, ARG_GLOBAL },
4678 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4679 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
4680 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4681 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4682 { "quiet", no_argument, NULL, 'q' },
4683 { "order", no_argument, NULL, ARG_ORDER },
4684 { "require", no_argument, NULL, ARG_REQUIRE },
4685 { "root", required_argument, NULL, ARG_ROOT },
4686 { "force", no_argument, NULL, ARG_FORCE },
4687 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4688 { "kill-mode", required_argument, NULL, ARG_KILL_MODE }, /* undocumented on purpose */
4689 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4690 { "signal", required_argument, NULL, 's' },
4691 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4692 { "host", required_argument, NULL, 'H' },
4693 { "privileged",no_argument, NULL, 'P' },
4694 { "runtime", no_argument, NULL, ARG_RUNTIME },
4695 { "lines", required_argument, NULL, 'n' },
4696 { "follow", no_argument, NULL, ARG_FOLLOW },
4697 { "output", required_argument, NULL, 'o' },
4698 { NULL, 0, NULL, 0 }
4706 while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:Pn:o:", options, NULL)) >= 0) {
4715 puts(PACKAGE_STRING);
4717 puts(SYSTEMD_FEATURES);
4727 if (!(l = strv_append(arg_property, optarg)))
4730 strv_free(arg_property);
4733 /* If the user asked for a particular
4734 * property, show it to him, even if it is
4745 arg_job_mode = "fail";
4748 case ARG_IGNORE_DEPENDENCIES:
4749 arg_job_mode = "ignore-dependencies";
4753 arg_scope = UNIT_FILE_USER;
4757 arg_scope = UNIT_FILE_SYSTEM;
4761 arg_scope = UNIT_FILE_GLOBAL;
4765 arg_no_block = true;
4769 arg_no_legend = true;
4773 arg_no_pager = true;
4781 arg_dot = DOT_ORDER;
4785 arg_dot = DOT_REQUIRE;
4813 /* -f is short for both --follow and --force! */
4819 arg_no_reload = true;
4823 arg_kill_who = optarg;
4827 arg_kill_mode = optarg;
4831 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4832 log_error("Failed to parse signal string %s.", optarg);
4837 case ARG_NO_ASK_PASSWORD:
4838 arg_ask_password = false;
4842 arg_transport = TRANSPORT_POLKIT;
4846 arg_transport = TRANSPORT_SSH;
4855 if (safe_atou(optarg, &arg_lines) < 0) {
4856 log_error("Failed to parse lines '%s'", optarg);
4862 arg_output = output_mode_from_string(optarg);
4863 if (arg_output < 0) {
4864 log_error("Unknown output '%s'.", optarg);
4873 log_error("Unknown option code %c", c);
4878 if (arg_transport != TRANSPORT_NORMAL && arg_scope != UNIT_FILE_SYSTEM) {
4879 log_error("Cannot access user instance remotely.");
4886 static int halt_parse_argv(int argc, char *argv[]) {
4895 static const struct option options[] = {
4896 { "help", no_argument, NULL, ARG_HELP },
4897 { "halt", no_argument, NULL, ARG_HALT },
4898 { "poweroff", no_argument, NULL, 'p' },
4899 { "reboot", no_argument, NULL, ARG_REBOOT },
4900 { "force", no_argument, NULL, 'f' },
4901 { "wtmp-only", no_argument, NULL, 'w' },
4902 { "no-wtmp", no_argument, NULL, 'd' },
4903 { "no-sync", no_argument, NULL, 'n' },
4904 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4905 { NULL, 0, NULL, 0 }
4913 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4914 if (runlevel == '0' || runlevel == '6')
4917 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4925 arg_action = ACTION_HALT;
4929 if (arg_action != ACTION_REBOOT)
4930 arg_action = ACTION_POWEROFF;
4934 arg_action = ACTION_REBOOT;
4959 /* Compatibility nops */
4966 log_error("Unknown option code %c", c);
4971 if (optind < argc) {
4972 log_error("Too many arguments.");
4979 static int parse_time_spec(const char *t, usec_t *_u) {
4983 if (streq(t, "now"))
4985 else if (!strchr(t, ':')) {
4988 if (safe_atou64(t, &u) < 0)
4991 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
5000 hour = strtol(t, &e, 10);
5001 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
5004 minute = strtol(e+1, &e, 10);
5005 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
5008 n = now(CLOCK_REALTIME);
5009 s = (time_t) (n / USEC_PER_SEC);
5012 assert_se(localtime_r(&s, &tm));
5014 tm.tm_hour = (int) hour;
5015 tm.tm_min = (int) minute;
5018 assert_se(s = mktime(&tm));
5020 *_u = (usec_t) s * USEC_PER_SEC;
5023 *_u += USEC_PER_DAY;
5029 static int shutdown_parse_argv(int argc, char *argv[]) {
5036 static const struct option options[] = {
5037 { "help", no_argument, NULL, ARG_HELP },
5038 { "halt", no_argument, NULL, 'H' },
5039 { "poweroff", no_argument, NULL, 'P' },
5040 { "reboot", no_argument, NULL, 'r' },
5041 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
5042 { "no-wall", no_argument, NULL, ARG_NO_WALL },
5043 { NULL, 0, NULL, 0 }
5051 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
5059 arg_action = ACTION_HALT;
5063 arg_action = ACTION_POWEROFF;
5068 arg_action = ACTION_KEXEC;
5070 arg_action = ACTION_REBOOT;
5074 arg_action = ACTION_KEXEC;
5078 if (arg_action != ACTION_HALT)
5079 arg_action = ACTION_POWEROFF;
5092 /* Compatibility nops */
5096 arg_action = ACTION_CANCEL_SHUTDOWN;
5103 log_error("Unknown option code %c", c);
5108 if (argc > optind) {
5109 r = parse_time_spec(argv[optind], &arg_when);
5111 log_error("Failed to parse time specification: %s", argv[optind]);
5115 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
5117 /* We skip the time argument */
5118 if (argc > optind + 1)
5119 arg_wall = argv + optind + 1;
5126 static int telinit_parse_argv(int argc, char *argv[]) {
5133 static const struct option options[] = {
5134 { "help", no_argument, NULL, ARG_HELP },
5135 { "no-wall", no_argument, NULL, ARG_NO_WALL },
5136 { NULL, 0, NULL, 0 }
5139 static const struct {
5143 { '0', ACTION_POWEROFF },
5144 { '6', ACTION_REBOOT },
5145 { '1', ACTION_RESCUE },
5146 { '2', ACTION_RUNLEVEL2 },
5147 { '3', ACTION_RUNLEVEL3 },
5148 { '4', ACTION_RUNLEVEL4 },
5149 { '5', ACTION_RUNLEVEL5 },
5150 { 's', ACTION_RESCUE },
5151 { 'S', ACTION_RESCUE },
5152 { 'q', ACTION_RELOAD },
5153 { 'Q', ACTION_RELOAD },
5154 { 'u', ACTION_REEXEC },
5155 { 'U', ACTION_REEXEC }
5164 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5179 log_error("Unknown option code %c", c);
5184 if (optind >= argc) {
5189 if (optind + 1 < argc) {
5190 log_error("Too many arguments.");
5194 if (strlen(argv[optind]) != 1) {
5195 log_error("Expected single character argument.");
5199 for (i = 0; i < ELEMENTSOF(table); i++)
5200 if (table[i].from == argv[optind][0])
5203 if (i >= ELEMENTSOF(table)) {
5204 log_error("Unknown command %s.", argv[optind]);
5208 arg_action = table[i].to;
5215 static int runlevel_parse_argv(int argc, char *argv[]) {
5221 static const struct option options[] = {
5222 { "help", no_argument, NULL, ARG_HELP },
5223 { NULL, 0, NULL, 0 }
5231 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5242 log_error("Unknown option code %c", c);
5247 if (optind < argc) {
5248 log_error("Too many arguments.");
5255 static int parse_argv(int argc, char *argv[]) {
5259 if (program_invocation_short_name) {
5261 if (strstr(program_invocation_short_name, "halt")) {
5262 arg_action = ACTION_HALT;
5263 return halt_parse_argv(argc, argv);
5264 } else if (strstr(program_invocation_short_name, "poweroff")) {
5265 arg_action = ACTION_POWEROFF;
5266 return halt_parse_argv(argc, argv);
5267 } else if (strstr(program_invocation_short_name, "reboot")) {
5269 arg_action = ACTION_KEXEC;
5271 arg_action = ACTION_REBOOT;
5272 return halt_parse_argv(argc, argv);
5273 } else if (strstr(program_invocation_short_name, "shutdown")) {
5274 arg_action = ACTION_POWEROFF;
5275 return shutdown_parse_argv(argc, argv);
5276 } else if (strstr(program_invocation_short_name, "init")) {
5278 if (sd_booted() > 0) {
5279 arg_action = ACTION_INVALID;
5280 return telinit_parse_argv(argc, argv);
5282 /* Hmm, so some other init system is
5283 * running, we need to forward this
5284 * request to it. For now we simply
5285 * guess that it is Upstart. */
5287 execv("/lib/upstart/telinit", argv);
5289 log_error("Couldn't find an alternative telinit implementation to spawn.");
5293 } else if (strstr(program_invocation_short_name, "runlevel")) {
5294 arg_action = ACTION_RUNLEVEL;
5295 return runlevel_parse_argv(argc, argv);
5299 arg_action = ACTION_SYSTEMCTL;
5300 return systemctl_parse_argv(argc, argv);
5303 static int action_to_runlevel(void) {
5305 static const char table[_ACTION_MAX] = {
5306 [ACTION_HALT] = '0',
5307 [ACTION_POWEROFF] = '0',
5308 [ACTION_REBOOT] = '6',
5309 [ACTION_RUNLEVEL2] = '2',
5310 [ACTION_RUNLEVEL3] = '3',
5311 [ACTION_RUNLEVEL4] = '4',
5312 [ACTION_RUNLEVEL5] = '5',
5313 [ACTION_RESCUE] = '1'
5316 assert(arg_action < _ACTION_MAX);
5318 return table[arg_action];
5321 static int talk_upstart(void) {
5322 DBusMessage *m = NULL, *reply = NULL;
5324 int previous, rl, r;
5326 env1_buf[] = "RUNLEVEL=X",
5327 env2_buf[] = "PREVLEVEL=X";
5328 char *env1 = env1_buf, *env2 = env2_buf;
5329 const char *emit = "runlevel";
5330 dbus_bool_t b_false = FALSE;
5331 DBusMessageIter iter, sub;
5332 DBusConnection *bus;
5334 dbus_error_init(&error);
5336 if (!(rl = action_to_runlevel()))
5339 if (utmp_get_runlevel(&previous, NULL) < 0)
5342 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
5343 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
5348 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
5353 if ((r = bus_check_peercred(bus)) < 0) {
5354 log_error("Failed to verify owner of bus.");
5358 if (!(m = dbus_message_new_method_call(
5359 "com.ubuntu.Upstart",
5360 "/com/ubuntu/Upstart",
5361 "com.ubuntu.Upstart0_6",
5364 log_error("Could not allocate message.");
5369 dbus_message_iter_init_append(m, &iter);
5371 env1_buf[sizeof(env1_buf)-2] = rl;
5372 env2_buf[sizeof(env2_buf)-2] = previous;
5374 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5375 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5376 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5377 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5378 !dbus_message_iter_close_container(&iter, &sub) ||
5379 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5380 log_error("Could not append arguments to message.");
5385 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5387 if (error_is_no_service(&error)) {
5392 log_error("Failed to issue method call: %s", bus_error_message(&error));
5401 dbus_message_unref(m);
5404 dbus_message_unref(reply);
5407 dbus_connection_flush(bus);
5408 dbus_connection_close(bus);
5409 dbus_connection_unref(bus);
5412 dbus_error_free(&error);
5417 static int talk_initctl(void) {
5418 struct init_request request;
5422 if (!(rl = action_to_runlevel()))
5426 request.magic = INIT_MAGIC;
5427 request.sleeptime = 0;
5428 request.cmd = INIT_CMD_RUNLVL;
5429 request.runlevel = rl;
5431 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5433 if (errno == ENOENT)
5436 log_error("Failed to open "INIT_FIFO": %m");
5441 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5442 close_nointr_nofail(fd);
5445 log_error("Failed to write to "INIT_FIFO": %m");
5446 return errno ? -errno : -EIO;
5452 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5454 static const struct {
5462 int (* const dispatch)(DBusConnection *bus, char **args);
5464 { "list-units", LESS, 1, list_units },
5465 { "list-unit-files", EQUAL, 1, list_unit_files },
5466 { "list-jobs", EQUAL, 1, list_jobs },
5467 { "clear-jobs", EQUAL, 1, daemon_reload },
5468 { "load", MORE, 2, load_unit },
5469 { "cancel", MORE, 2, cancel_job },
5470 { "start", MORE, 2, start_unit },
5471 { "stop", MORE, 2, start_unit },
5472 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5473 { "reload", MORE, 2, start_unit },
5474 { "restart", MORE, 2, start_unit },
5475 { "try-restart", MORE, 2, start_unit },
5476 { "reload-or-restart", MORE, 2, start_unit },
5477 { "reload-or-try-restart", MORE, 2, start_unit },
5478 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5479 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5480 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5481 { "isolate", EQUAL, 2, start_unit },
5482 { "kill", MORE, 2, kill_unit },
5483 { "is-active", MORE, 2, check_unit },
5484 { "check", MORE, 2, check_unit },
5485 { "show", MORE, 1, show },
5486 { "status", MORE, 2, show },
5487 { "help", MORE, 2, show },
5488 { "dump", EQUAL, 1, dump },
5489 { "dot", EQUAL, 1, dot },
5490 { "snapshot", LESS, 2, snapshot },
5491 { "delete", MORE, 2, delete_snapshot },
5492 { "daemon-reload", EQUAL, 1, daemon_reload },
5493 { "daemon-reexec", EQUAL, 1, daemon_reload },
5494 { "show-environment", EQUAL, 1, show_enviroment },
5495 { "set-environment", MORE, 2, set_environment },
5496 { "unset-environment", MORE, 2, set_environment },
5497 { "halt", EQUAL, 1, start_special },
5498 { "poweroff", EQUAL, 1, start_special },
5499 { "reboot", EQUAL, 1, start_special },
5500 { "kexec", EQUAL, 1, start_special },
5501 { "suspend", EQUAL, 1, start_special },
5502 { "hibernate", EQUAL, 1, start_special },
5503 { "default", EQUAL, 1, start_special },
5504 { "rescue", EQUAL, 1, start_special },
5505 { "emergency", EQUAL, 1, start_special },
5506 { "exit", EQUAL, 1, start_special },
5507 { "reset-failed", MORE, 1, reset_failed },
5508 { "enable", MORE, 2, enable_unit },
5509 { "disable", MORE, 2, enable_unit },
5510 { "is-enabled", MORE, 2, unit_is_enabled },
5511 { "reenable", MORE, 2, enable_unit },
5512 { "preset", MORE, 2, enable_unit },
5513 { "mask", MORE, 2, enable_unit },
5514 { "unmask", MORE, 2, enable_unit },
5515 { "link", MORE, 2, enable_unit },
5516 { "switch-root", MORE, 2, switch_root },
5526 left = argc - optind;
5529 /* Special rule: no arguments means "list-units" */
5532 if (streq(argv[optind], "help") && !argv[optind+1]) {
5533 log_error("This command expects one or more "
5534 "unit names. Did you mean --help?");
5538 for (i = 0; i < ELEMENTSOF(verbs); i++)
5539 if (streq(argv[optind], verbs[i].verb))
5542 if (i >= ELEMENTSOF(verbs)) {
5543 log_error("Unknown operation %s", argv[optind]);
5548 switch (verbs[i].argc_cmp) {
5551 if (left != verbs[i].argc) {
5552 log_error("Invalid number of arguments.");
5559 if (left < verbs[i].argc) {
5560 log_error("Too few arguments.");
5567 if (left > verbs[i].argc) {
5568 log_error("Too many arguments.");
5575 assert_not_reached("Unknown comparison operator.");
5578 /* Require a bus connection for all operations but
5580 if (!streq(verbs[i].verb, "enable") &&
5581 !streq(verbs[i].verb, "disable") &&
5582 !streq(verbs[i].verb, "is-enabled") &&
5583 !streq(verbs[i].verb, "list-unit-files") &&
5584 !streq(verbs[i].verb, "reenable") &&
5585 !streq(verbs[i].verb, "preset") &&
5586 !streq(verbs[i].verb, "mask") &&
5587 !streq(verbs[i].verb, "unmask") &&
5588 !streq(verbs[i].verb, "link")) {
5590 if (running_in_chroot() > 0) {
5591 log_info("Running in chroot, ignoring request.");
5595 if (((!streq(verbs[i].verb, "reboot") &&
5596 !streq(verbs[i].verb, "halt") &&
5597 !streq(verbs[i].verb, "poweroff")) || arg_force <= 0) && !bus) {
5598 log_error("Failed to get D-Bus connection: %s",
5599 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5605 if (!bus && !avoid_bus()) {
5606 log_error("Failed to get D-Bus connection: %s",
5607 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5612 return verbs[i].dispatch(bus, argv + optind);
5615 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
5617 struct msghdr msghdr;
5618 struct iovec iovec[2];
5619 union sockaddr_union sockaddr;
5620 struct sd_shutdown_command c;
5622 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
5629 c.dry_run = dry_run;
5633 sockaddr.sa.sa_family = AF_UNIX;
5634 strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5637 msghdr.msg_name = &sockaddr;
5638 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5641 iovec[0].iov_base = (char*) &c;
5642 iovec[0].iov_len = offsetof(struct sd_shutdown_command, wall_message);
5644 if (isempty(message))
5645 msghdr.msg_iovlen = 1;
5647 iovec[1].iov_base = (char*) message;
5648 iovec[1].iov_len = strlen(message);
5649 msghdr.msg_iovlen = 2;
5651 msghdr.msg_iov = iovec;
5653 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5654 close_nointr_nofail(fd);
5658 close_nointr_nofail(fd);
5662 static int reload_with_fallback(DBusConnection *bus) {
5665 /* First, try systemd via D-Bus. */
5666 if (daemon_reload(bus, NULL) >= 0)
5670 /* Nothing else worked, so let's try signals */
5671 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5673 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5674 log_error("kill() failed: %m");
5681 static int start_with_fallback(DBusConnection *bus) {
5684 /* First, try systemd via D-Bus. */
5685 if (start_unit(bus, NULL) >= 0)
5689 /* Hmm, talking to systemd via D-Bus didn't work. Then
5690 * let's try to talk to Upstart via D-Bus. */
5691 if (talk_upstart() > 0)
5694 /* Nothing else worked, so let's try
5696 if (talk_initctl() > 0)
5699 log_error("Failed to talk to init daemon.");
5703 warn_wall(arg_action);
5707 static void halt_now(enum action a) {
5709 /* Make sure C-A-D is handled by the kernel from this
5711 reboot(RB_ENABLE_CAD);
5716 log_info("Halting.");
5717 reboot(RB_HALT_SYSTEM);
5720 case ACTION_POWEROFF:
5721 log_info("Powering off.");
5722 reboot(RB_POWER_OFF);
5726 log_info("Rebooting.");
5727 reboot(RB_AUTOBOOT);
5731 assert_not_reached("Unknown halt action.");
5734 assert_not_reached("Uh? This shouldn't happen.");
5737 static int halt_main(DBusConnection *bus) {
5740 if (geteuid() != 0) {
5741 /* Try logind if we are a normal user and no special
5742 * mode applies. Maybe PolicyKit allows us to shutdown
5745 if (arg_when <= 0 &&
5748 (arg_action == ACTION_POWEROFF ||
5749 arg_action == ACTION_REBOOT)) {
5750 r = reboot_with_logind(bus, arg_action);
5755 log_error("Must be root.");
5762 m = strv_join(arg_wall, " ");
5763 r = send_shutdownd(arg_when,
5764 arg_action == ACTION_HALT ? 'H' :
5765 arg_action == ACTION_POWEROFF ? 'P' :
5766 arg_action == ACTION_KEXEC ? 'K' :
5774 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5776 char date[FORMAT_TIMESTAMP_MAX];
5778 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5779 format_timestamp(date, sizeof(date), arg_when));
5784 if (!arg_dry && !arg_force)
5785 return start_with_fallback(bus);
5788 if (sd_booted() > 0)
5789 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5791 r = utmp_put_shutdown();
5793 log_warning("Failed to write utmp record: %s", strerror(-r));
5803 halt_now(arg_action);
5804 /* We should never reach this. */
5808 static int runlevel_main(void) {
5809 int r, runlevel, previous;
5811 r = utmp_get_runlevel(&runlevel, &previous);
5818 previous <= 0 ? 'N' : previous,
5819 runlevel <= 0 ? 'N' : runlevel);
5824 int main(int argc, char*argv[]) {
5825 int r, retval = EXIT_FAILURE;
5826 DBusConnection *bus = NULL;
5829 dbus_error_init(&error);
5831 log_parse_environment();
5834 r = parse_argv(argc, argv);
5838 retval = EXIT_SUCCESS;
5842 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5843 * let's shortcut this */
5844 if (arg_action == ACTION_RUNLEVEL) {
5845 r = runlevel_main();
5846 retval = r < 0 ? EXIT_FAILURE : r;
5850 if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5851 log_info("Running in chroot, ignoring request.");
5857 if (arg_transport == TRANSPORT_NORMAL)
5858 bus_connect(arg_scope == UNIT_FILE_SYSTEM ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, &bus, &private_bus, &error);
5859 else if (arg_transport == TRANSPORT_POLKIT) {
5860 bus_connect_system_polkit(&bus, &error);
5861 private_bus = false;
5862 } else if (arg_transport == TRANSPORT_SSH) {
5863 bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5864 private_bus = false;
5866 assert_not_reached("Uh, invalid transport...");
5869 switch (arg_action) {
5871 case ACTION_SYSTEMCTL:
5872 r = systemctl_main(bus, argc, argv, &error);
5876 case ACTION_POWEROFF:
5882 case ACTION_RUNLEVEL2:
5883 case ACTION_RUNLEVEL3:
5884 case ACTION_RUNLEVEL4:
5885 case ACTION_RUNLEVEL5:
5887 case ACTION_EMERGENCY:
5888 case ACTION_DEFAULT:
5889 r = start_with_fallback(bus);
5894 r = reload_with_fallback(bus);
5897 case ACTION_CANCEL_SHUTDOWN:
5898 r = send_shutdownd(0, 0, false, false, NULL);
5901 case ACTION_INVALID:
5902 case ACTION_RUNLEVEL:
5904 assert_not_reached("Unknown action");
5907 retval = r < 0 ? EXIT_FAILURE : r;
5911 dbus_connection_flush(bus);
5912 dbus_connection_close(bus);
5913 dbus_connection_unref(bus);
5916 dbus_error_free(&error);
5920 strv_free(arg_property);
5923 ask_password_agent_close();
5924 polkit_agent_close();