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;
1520 m = dbus_message_new_method_call("org.freedesktop.systemd1",
1521 "/org/freedesktop/systemd1",
1522 "org.freedesktop.systemd1.Manager",
1525 log_error("Could not allocate message.");
1530 if (!dbus_message_append_args(m,
1531 DBUS_TYPE_STRING, &name,
1532 DBUS_TYPE_INVALID)) {
1533 log_error("Could not append arguments to message.");
1538 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error);
1540 if (streq(error->name, BUS_ERROR_NO_SUCH_UNIT)) {
1541 dbus_error_free(error);
1544 log_error("Failed to issue method call: %s", bus_error_message(error));
1550 if (!dbus_message_get_args(reply, error,
1551 DBUS_TYPE_OBJECT_PATH, unit_path,
1552 DBUS_TYPE_INVALID)) {
1553 log_error("Failed to parse reply: %s", bus_error_message(error));
1558 *unit_path = strdup(*unit_path);
1559 if (!(*unit_path)) {
1560 log_error("Failed to duplicate unit path");
1565 dbus_message_unref(m);
1567 dbus_message_unref(reply);
1571 static int is_socket_listening(
1572 DBusConnection *bus,
1574 const char *socket_name) {
1576 DBusMessage *m = NULL, *reply = NULL;
1577 DBusMessageIter iter, sub;
1578 char *socket_object_path = NULL;
1579 const char *sub_state = NULL,
1580 *interface = "org.freedesktop.systemd1.Unit",
1581 *property = "SubState";
1586 assert(socket_name);
1588 if ((r = get_unit_path(bus, error, socket_name, &socket_object_path)) < 0) {
1591 m = dbus_message_new_method_call("org.freedesktop.systemd1",
1593 "org.freedesktop.DBus.Properties",
1596 log_error("Could not allocate message.");
1601 if (!dbus_message_append_args(m,
1602 DBUS_TYPE_STRING, &interface,
1603 DBUS_TYPE_STRING, &property,
1604 DBUS_TYPE_INVALID)) {
1605 log_error("Could not append arguments to message.");
1610 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error);
1612 log_error("Failed to issue method call: %s", bus_error_message(error));
1617 dbus_message_iter_init(reply, &iter);
1618 dbus_message_iter_recurse(&iter, &sub);
1620 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1621 log_error("Failed to parse reply: %s", bus_error_message(error));
1625 dbus_message_iter_get_basic(&sub, &sub_state);
1626 r = streq(sub_state, "listening");
1629 dbus_message_unref(m);
1632 dbus_message_unref(reply);
1634 free(socket_object_path);
1638 static void check_listening_sockets(
1639 DBusConnection *bus,
1641 const char *unit_name) {
1643 DBusMessage *m = NULL, *reply = NULL;
1644 DBusMessageIter iter, sub;
1645 const char *service_trigger = NULL,
1646 *interface = "org.freedesktop.systemd1.Unit",
1647 *triggered_by_property = "TriggeredBy";
1649 char *unit_path = NULL;
1650 int print_warning_label = 1;
1652 if ((get_unit_path(bus, error, unit_name, &unit_path) < 0)) {
1656 m = dbus_message_new_method_call("org.freedesktop.systemd1",
1658 "org.freedesktop.DBus.Properties",
1661 log_error("Could not allocate message.");
1665 if (!dbus_message_append_args(m,
1666 DBUS_TYPE_STRING, &interface,
1667 DBUS_TYPE_STRING, &triggered_by_property,
1668 DBUS_TYPE_INVALID)) {
1669 log_error("Could not append arguments to message.");
1673 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error);
1675 log_error("Failed to issue method call: %s", bus_error_message(error));
1679 if (!dbus_message_iter_init(reply, &iter) ||
1680 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1681 log_error("Failed to parse reply: %s", bus_error_message(error));
1686 dbus_message_iter_recurse(&iter, &sub);
1687 dbus_message_iter_recurse(&sub, &iter);
1690 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1693 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1694 log_error("Failed to parse reply: %s", bus_error_message(error));
1698 dbus_message_iter_get_basic(&sub, &service_trigger);
1700 if (endswith(service_trigger, ".socket")) {
1701 r = is_socket_listening(bus, error, service_trigger);
1703 dbus_message_iter_recurse(&iter, &sub);
1709 if (print_warning_label) {
1710 log_warning("There are listening sockets associated with %s :", unit_name);
1711 print_warning_label = 0;
1713 log_warning("%s",service_trigger);
1715 log_error("Failed to issue function call: %s", bus_error_message(error));
1718 dbus_message_iter_recurse(&iter, &sub);
1723 dbus_message_unref(m);
1726 dbus_message_unref(reply);
1731 static int start_unit_one(
1732 DBusConnection *bus,
1739 DBusMessage *m = NULL, *reply = NULL;
1748 assert(arg_no_block || s);
1750 if (!(m = dbus_message_new_method_call(
1751 "org.freedesktop.systemd1",
1752 "/org/freedesktop/systemd1",
1753 "org.freedesktop.systemd1.Manager",
1755 log_error("Could not allocate message.");
1760 if (!dbus_message_append_args(m,
1761 DBUS_TYPE_STRING, &name,
1762 DBUS_TYPE_STRING, &mode,
1763 DBUS_TYPE_INVALID)) {
1764 log_error("Could not append arguments to message.");
1769 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1771 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1772 /* There's always a fallback possible for
1773 * legacy actions. */
1778 log_error("Failed to issue method call: %s", bus_error_message(error));
1783 if (!dbus_message_get_args(reply, error,
1784 DBUS_TYPE_OBJECT_PATH, &path,
1785 DBUS_TYPE_INVALID)) {
1786 log_error("Failed to parse reply: %s", bus_error_message(error));
1791 if (need_daemon_reload(bus, name))
1792 log_warning("Warning: Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1793 arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
1795 if (!arg_no_block) {
1798 if (!(p = strdup(path))) {
1799 log_error("Failed to duplicate path.");
1804 if ((r = set_put(s, p)) < 0) {
1806 log_error("Failed to add path to set.");
1811 /* When stopping unit check if we have some listening sockets active */
1812 if (streq(method, "StopUnit") && !arg_quiet) {
1813 check_listening_sockets(bus, error, name);
1820 dbus_message_unref(m);
1823 dbus_message_unref(reply);
1828 static enum action verb_to_action(const char *verb) {
1829 if (streq(verb, "halt"))
1831 else if (streq(verb, "poweroff"))
1832 return ACTION_POWEROFF;
1833 else if (streq(verb, "reboot"))
1834 return ACTION_REBOOT;
1835 else if (streq(verb, "kexec"))
1836 return ACTION_KEXEC;
1837 else if (streq(verb, "rescue"))
1838 return ACTION_RESCUE;
1839 else if (streq(verb, "emergency"))
1840 return ACTION_EMERGENCY;
1841 else if (streq(verb, "default"))
1842 return ACTION_DEFAULT;
1843 else if (streq(verb, "exit"))
1845 else if (streq(verb, "suspend"))
1846 return ACTION_SUSPEND;
1847 else if (streq(verb, "hibernate"))
1848 return ACTION_HIBERNATE;
1850 return ACTION_INVALID;
1853 static int start_unit(DBusConnection *bus, char **args) {
1855 static const char * const table[_ACTION_MAX] = {
1856 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1857 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1858 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1859 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1860 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1861 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1862 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1863 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1864 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1865 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1866 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1867 [ACTION_EXIT] = SPECIAL_EXIT_TARGET,
1868 [ACTION_SUSPEND] = SPECIAL_SUSPEND_TARGET,
1869 [ACTION_HIBERNATE] = SPECIAL_HIBERNATE_TARGET
1873 const char *method, *mode, *one_name;
1878 dbus_error_init(&error);
1882 ask_password_agent_open_if_enabled();
1884 if (arg_action == ACTION_SYSTEMCTL) {
1886 streq(args[0], "stop") ||
1887 streq(args[0], "condstop") ? "StopUnit" :
1888 streq(args[0], "reload") ? "ReloadUnit" :
1889 streq(args[0], "restart") ? "RestartUnit" :
1891 streq(args[0], "try-restart") ||
1892 streq(args[0], "condrestart") ? "TryRestartUnit" :
1894 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1896 streq(args[0], "reload-or-try-restart") ||
1897 streq(args[0], "condreload") ||
1899 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1903 (streq(args[0], "isolate") ||
1904 streq(args[0], "rescue") ||
1905 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1907 one_name = table[verb_to_action(args[0])];
1910 assert(arg_action < ELEMENTSOF(table));
1911 assert(table[arg_action]);
1913 method = "StartUnit";
1915 mode = (arg_action == ACTION_EMERGENCY ||
1916 arg_action == ACTION_RESCUE ||
1917 arg_action == ACTION_RUNLEVEL2 ||
1918 arg_action == ACTION_RUNLEVEL3 ||
1919 arg_action == ACTION_RUNLEVEL4 ||
1920 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1922 one_name = table[arg_action];
1925 if (!arg_no_block) {
1926 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1927 log_error("Could not watch jobs: %s", strerror(-ret));
1931 if (!(s = set_new(string_hash_func, string_compare_func))) {
1932 log_error("Failed to allocate set.");
1939 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1942 STRV_FOREACH(name, args+1)
1943 if ((r = start_unit_one(bus, method, *name, mode, &error, s)) != 0) {
1944 ret = translate_bus_error_to_exit_status(r, &error);
1945 dbus_error_free(&error);
1950 if ((r = wait_for_jobs(bus, s)) < 0) {
1959 dbus_error_free(&error);
1964 /* Ask systemd-logind, which might grant access to unprivileged users
1965 * through PolicyKit */
1966 static int reboot_with_logind(DBusConnection *bus, enum action a) {
1969 DBusMessage *m = NULL, *reply = NULL;
1971 dbus_bool_t interactive = true;
1974 dbus_error_init(&error);
1976 polkit_agent_open_if_enabled();
1984 case ACTION_POWEROFF:
1985 method = "PowerOff";
1988 case ACTION_SUSPEND:
1992 case ACTION_HIBERNATE:
1993 method = "Hibernate";
2000 m = dbus_message_new_method_call(
2001 "org.freedesktop.login1",
2002 "/org/freedesktop/login1",
2003 "org.freedesktop.login1.Manager",
2006 log_error("Could not allocate message.");
2011 if (!dbus_message_append_args(m,
2012 DBUS_TYPE_BOOLEAN, &interactive,
2013 DBUS_TYPE_INVALID)) {
2014 log_error("Could not append arguments to message.");
2019 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
2021 if (error_is_no_service(&error)) {
2022 log_debug("Failed to issue method call: %s", bus_error_message(&error));
2027 if (dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2028 log_debug("Failed to issue method call: %s", bus_error_message(&error));
2033 log_info("Failed to issue method call: %s", bus_error_message(&error));
2042 dbus_message_unref(m);
2045 dbus_message_unref(reply);
2047 dbus_error_free(&error);
2055 static int start_special(DBusConnection *bus, char **args) {
2061 a = verb_to_action(args[0]);
2063 if (arg_force >= 2 && geteuid() != 0) {
2064 log_error("Must be root.");
2068 if (arg_force >= 2 &&
2069 (a == ACTION_HALT ||
2070 a == ACTION_POWEROFF ||
2071 a == ACTION_REBOOT))
2074 if (arg_force >= 1 &&
2075 (a == ACTION_HALT ||
2076 a == ACTION_POWEROFF ||
2077 a == ACTION_REBOOT ||
2078 a == ACTION_KEXEC ||
2080 return daemon_reload(bus, args);
2082 /* first try logind, to allow authentication with polkit */
2083 if (geteuid() != 0 &&
2084 (a == ACTION_POWEROFF ||
2085 a == ACTION_REBOOT ||
2086 a == ACTION_SUSPEND ||
2087 a == ACTION_HIBERNATE)) {
2088 r = reboot_with_logind(bus, a);
2093 r = start_unit(bus, args);
2100 static int check_unit(DBusConnection *bus, char **args) {
2101 DBusMessage *m = NULL, *reply = NULL;
2103 *interface = "org.freedesktop.systemd1.Unit",
2104 *property = "ActiveState";
2105 int r = 3; /* According to LSB: "program is not running" */
2112 dbus_error_init(&error);
2114 STRV_FOREACH(name, args+1) {
2115 const char *path = NULL;
2117 DBusMessageIter iter, sub;
2119 if (!(m = dbus_message_new_method_call(
2120 "org.freedesktop.systemd1",
2121 "/org/freedesktop/systemd1",
2122 "org.freedesktop.systemd1.Manager",
2124 log_error("Could not allocate message.");
2129 if (!dbus_message_append_args(m,
2130 DBUS_TYPE_STRING, name,
2131 DBUS_TYPE_INVALID)) {
2132 log_error("Could not append arguments to message.");
2137 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2139 /* Hmm, cannot figure out anything about this unit... */
2143 dbus_error_free(&error);
2144 dbus_message_unref(m);
2149 if (!dbus_message_get_args(reply, &error,
2150 DBUS_TYPE_OBJECT_PATH, &path,
2151 DBUS_TYPE_INVALID)) {
2152 log_error("Failed to parse reply: %s", bus_error_message(&error));
2157 dbus_message_unref(m);
2158 if (!(m = dbus_message_new_method_call(
2159 "org.freedesktop.systemd1",
2161 "org.freedesktop.DBus.Properties",
2163 log_error("Could not allocate message.");
2168 if (!dbus_message_append_args(m,
2169 DBUS_TYPE_STRING, &interface,
2170 DBUS_TYPE_STRING, &property,
2171 DBUS_TYPE_INVALID)) {
2172 log_error("Could not append arguments to message.");
2177 dbus_message_unref(reply);
2178 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2179 log_error("Failed to issue method call: %s", bus_error_message(&error));
2184 if (!dbus_message_iter_init(reply, &iter) ||
2185 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2186 log_error("Failed to parse reply.");
2191 dbus_message_iter_recurse(&iter, &sub);
2193 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2194 log_error("Failed to parse reply.");
2199 dbus_message_iter_get_basic(&sub, &state);
2204 if (streq(state, "active") || streq(state, "reloading"))
2207 dbus_message_unref(m);
2208 dbus_message_unref(reply);
2214 dbus_message_unref(m);
2217 dbus_message_unref(reply);
2219 dbus_error_free(&error);
2224 static int kill_unit(DBusConnection *bus, char **args) {
2225 DBusMessage *m = NULL;
2233 dbus_error_init(&error);
2236 arg_kill_who = "all";
2239 arg_kill_mode = streq(arg_kill_who, "all") ? "control-group" : "process";
2241 STRV_FOREACH(name, args+1) {
2244 if (!(m = dbus_message_new_method_call(
2245 "org.freedesktop.systemd1",
2246 "/org/freedesktop/systemd1",
2247 "org.freedesktop.systemd1.Manager",
2249 log_error("Could not allocate message.");
2254 if (!dbus_message_append_args(m,
2255 DBUS_TYPE_STRING, name,
2256 DBUS_TYPE_STRING, &arg_kill_who,
2257 DBUS_TYPE_STRING, &arg_kill_mode,
2258 DBUS_TYPE_INT32, &arg_signal,
2259 DBUS_TYPE_INVALID)) {
2260 log_error("Could not append arguments to message.");
2265 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2266 log_error("Failed to issue method call: %s", bus_error_message(&error));
2267 dbus_error_free(&error);
2271 dbus_message_unref(m);
2274 dbus_message_unref(reply);
2280 dbus_message_unref(m);
2282 dbus_error_free(&error);
2287 typedef struct ExecStatusInfo {
2295 usec_t start_timestamp;
2296 usec_t exit_timestamp;
2301 LIST_FIELDS(struct ExecStatusInfo, exec);
2304 static void exec_status_info_free(ExecStatusInfo *i) {
2313 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
2314 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
2315 DBusMessageIter sub2, sub3;
2319 int32_t code, status;
2325 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
2328 dbus_message_iter_recurse(sub, &sub2);
2330 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
2333 if (!(i->path = strdup(path)))
2336 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
2337 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
2341 dbus_message_iter_recurse(&sub2, &sub3);
2342 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
2343 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
2344 dbus_message_iter_next(&sub3);
2349 if (!(i->argv = new0(char*, n+1)))
2353 dbus_message_iter_recurse(&sub2, &sub3);
2354 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
2357 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
2358 dbus_message_iter_get_basic(&sub3, &s);
2359 dbus_message_iter_next(&sub3);
2361 if (!(i->argv[n++] = strdup(s)))
2365 if (!dbus_message_iter_next(&sub2) ||
2366 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
2367 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
2368 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
2369 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
2370 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
2371 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
2372 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
2373 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
2377 i->start_timestamp = (usec_t) start_timestamp;
2378 i->exit_timestamp = (usec_t) exit_timestamp;
2379 i->pid = (pid_t) pid;
2386 typedef struct UnitStatusInfo {
2388 const char *load_state;
2389 const char *active_state;
2390 const char *sub_state;
2391 const char *unit_file_state;
2393 const char *description;
2394 const char *following;
2396 char **documentation;
2398 const char *fragment_path;
2399 const char *source_path;
2400 const char *default_control_group;
2402 const char *load_error;
2405 usec_t inactive_exit_timestamp;
2406 usec_t inactive_exit_timestamp_monotonic;
2407 usec_t active_enter_timestamp;
2408 usec_t active_exit_timestamp;
2409 usec_t inactive_enter_timestamp;
2411 bool need_daemon_reload;
2416 const char *status_text;
2419 usec_t start_timestamp;
2420 usec_t exit_timestamp;
2422 int exit_code, exit_status;
2424 usec_t condition_timestamp;
2425 bool condition_result;
2428 unsigned n_accepted;
2429 unsigned n_connections;
2433 const char *sysfs_path;
2435 /* Mount, Automount */
2441 LIST_HEAD(ExecStatusInfo, exec);
2444 static void print_status_info(UnitStatusInfo *i) {
2446 const char *on, *off, *ss;
2448 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
2449 char since2[FORMAT_TIMESTAMP_MAX], *s2;
2454 /* This shows pretty information about a unit. See
2455 * print_property() for a low-level property printer */
2457 printf("%s", strna(i->id));
2459 if (i->description && !streq_ptr(i->id, i->description))
2460 printf(" - %s", i->description);
2465 printf("\t Follow: unit currently follows state of %s\n", i->following);
2467 if (streq_ptr(i->load_state, "error")) {
2468 on = ansi_highlight_red(true);
2469 off = ansi_highlight_red(false);
2473 path = i->source_path ? i->source_path : i->fragment_path;
2476 printf("\t Loaded: %s%s%s (Reason: %s)\n", on, strna(i->load_state), off, i->load_error);
2477 else if (path && i->unit_file_state)
2478 printf("\t Loaded: %s%s%s (%s; %s)\n", on, strna(i->load_state), off, path, i->unit_file_state);
2480 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, path);
2482 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
2484 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
2486 if (streq_ptr(i->active_state, "failed")) {
2487 on = ansi_highlight_red(true);
2488 off = ansi_highlight_red(false);
2489 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
2490 on = ansi_highlight_green(true);
2491 off = ansi_highlight_green(false);
2496 printf("\t Active: %s%s (%s)%s",
2498 strna(i->active_state),
2502 printf("\t Active: %s%s%s",
2504 strna(i->active_state),
2507 if (!isempty(i->result) && !streq(i->result, "success"))
2508 printf(" (Result: %s)", i->result);
2510 timestamp = (streq_ptr(i->active_state, "active") ||
2511 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
2512 (streq_ptr(i->active_state, "inactive") ||
2513 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
2514 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
2515 i->active_exit_timestamp;
2517 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
2518 s2 = format_timestamp(since2, sizeof(since2), timestamp);
2521 printf(" since %s; %s\n", s2, s1);
2523 printf(" since %s\n", s2);
2527 if (!i->condition_result && i->condition_timestamp > 0) {
2528 s1 = format_timestamp_pretty(since1, sizeof(since1), i->condition_timestamp);
2529 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
2532 printf("\t start condition failed at %s; %s\n", s2, s1);
2534 printf("\t start condition failed at %s\n", s2);
2538 printf("\t Device: %s\n", i->sysfs_path);
2540 printf("\t Where: %s\n", i->where);
2542 printf("\t What: %s\n", i->what);
2544 if (!strv_isempty(i->documentation)) {
2548 STRV_FOREACH(t, i->documentation) {
2550 printf("\t Docs: %s\n", *t);
2553 printf("\t %s\n", *t);
2558 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
2560 LIST_FOREACH(exec, p, i->exec) {
2564 /* Only show exited processes here */
2568 t = strv_join(p->argv, " ");
2569 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
2572 good = is_clean_exit_lsb(p->code, p->status);
2574 on = ansi_highlight_red(true);
2575 off = ansi_highlight_red(false);
2579 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
2581 if (p->code == CLD_EXITED) {
2584 printf("status=%i", p->status);
2586 c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD);
2591 printf("signal=%s", signal_to_string(p->status));
2593 printf(")%s\n", off);
2595 if (i->main_pid == p->pid &&
2596 i->start_timestamp == p->start_timestamp &&
2597 i->exit_timestamp == p->start_timestamp)
2598 /* Let's not show this twice */
2601 if (p->pid == i->control_pid)
2605 if (i->main_pid > 0 || i->control_pid > 0) {
2608 if (i->main_pid > 0) {
2609 printf("Main PID: %u", (unsigned) i->main_pid);
2613 get_process_comm(i->main_pid, &t);
2618 } else if (i->exit_code > 0) {
2619 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2621 if (i->exit_code == CLD_EXITED) {
2624 printf("status=%i", i->exit_status);
2626 c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD);
2631 printf("signal=%s", signal_to_string(i->exit_status));
2636 if (i->main_pid > 0 && i->control_pid > 0)
2639 if (i->control_pid > 0) {
2642 printf(" Control: %u", (unsigned) i->control_pid);
2644 get_process_comm(i->control_pid, &t);
2655 printf("\t Status: \"%s\"\n", i->status_text);
2657 if (i->default_control_group) {
2660 printf("\t CGroup: %s\n", i->default_control_group);
2662 if (arg_transport != TRANSPORT_SSH) {
2672 if (i->main_pid > 0)
2673 extra[k++] = i->main_pid;
2675 if (i->control_pid > 0)
2676 extra[k++] = i->control_pid;
2678 show_cgroup_and_extra_by_spec(i->default_control_group, "\t\t ", c, false, arg_all, extra, k);
2682 if (i->id && arg_transport != TRANSPORT_SSH) {
2684 show_journal_by_unit(i->id, arg_output, 0, i->inactive_exit_timestamp_monotonic, arg_lines, arg_all, arg_follow);
2687 if (i->need_daemon_reload)
2688 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2689 ansi_highlight_red(true),
2690 ansi_highlight_red(false),
2691 arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
2694 static void show_unit_help(UnitStatusInfo *i) {
2699 if (!i->documentation) {
2700 log_info("Documentation for %s not known.", i->id);
2704 STRV_FOREACH(p, i->documentation) {
2706 if (startswith(*p, "man:")) {
2709 char *page = NULL, *section = NULL;
2710 const char *args[4] = { "man", NULL, NULL, NULL };
2715 if ((*p)[k-1] == ')')
2716 e = strrchr(*p, '(');
2719 page = strndup((*p) + 4, e - *p - 4);
2721 log_error("Out of memory.");
2725 section = strndup(e + 1, *p + k - e - 2);
2728 log_error("Out of memory");
2739 log_error("Failed to fork: %m");
2747 execvp(args[0], (char**) args);
2748 log_error("Failed to execute man: %m");
2749 _exit(EXIT_FAILURE);
2755 wait_for_terminate(pid, NULL);
2757 log_info("Can't show %s.", *p);
2761 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2767 switch (dbus_message_iter_get_arg_type(iter)) {
2769 case DBUS_TYPE_STRING: {
2772 dbus_message_iter_get_basic(iter, &s);
2775 if (streq(name, "Id"))
2777 else if (streq(name, "LoadState"))
2779 else if (streq(name, "ActiveState"))
2780 i->active_state = s;
2781 else if (streq(name, "SubState"))
2783 else if (streq(name, "Description"))
2785 else if (streq(name, "FragmentPath"))
2786 i->fragment_path = s;
2787 else if (streq(name, "SourcePath"))
2789 else if (streq(name, "DefaultControlGroup"))
2790 i->default_control_group = s;
2791 else if (streq(name, "StatusText"))
2793 else if (streq(name, "SysFSPath"))
2795 else if (streq(name, "Where"))
2797 else if (streq(name, "What"))
2799 else if (streq(name, "Following"))
2801 else if (streq(name, "UnitFileState"))
2802 i->unit_file_state = s;
2803 else if (streq(name, "Result"))
2810 case DBUS_TYPE_BOOLEAN: {
2813 dbus_message_iter_get_basic(iter, &b);
2815 if (streq(name, "Accept"))
2817 else if (streq(name, "NeedDaemonReload"))
2818 i->need_daemon_reload = b;
2819 else if (streq(name, "ConditionResult"))
2820 i->condition_result = b;
2825 case DBUS_TYPE_UINT32: {
2828 dbus_message_iter_get_basic(iter, &u);
2830 if (streq(name, "MainPID")) {
2832 i->main_pid = (pid_t) u;
2835 } else if (streq(name, "ControlPID"))
2836 i->control_pid = (pid_t) u;
2837 else if (streq(name, "ExecMainPID")) {
2839 i->main_pid = (pid_t) u;
2840 } else if (streq(name, "NAccepted"))
2842 else if (streq(name, "NConnections"))
2843 i->n_connections = u;
2848 case DBUS_TYPE_INT32: {
2851 dbus_message_iter_get_basic(iter, &j);
2853 if (streq(name, "ExecMainCode"))
2854 i->exit_code = (int) j;
2855 else if (streq(name, "ExecMainStatus"))
2856 i->exit_status = (int) j;
2861 case DBUS_TYPE_UINT64: {
2864 dbus_message_iter_get_basic(iter, &u);
2866 if (streq(name, "ExecMainStartTimestamp"))
2867 i->start_timestamp = (usec_t) u;
2868 else if (streq(name, "ExecMainExitTimestamp"))
2869 i->exit_timestamp = (usec_t) u;
2870 else if (streq(name, "ActiveEnterTimestamp"))
2871 i->active_enter_timestamp = (usec_t) u;
2872 else if (streq(name, "InactiveEnterTimestamp"))
2873 i->inactive_enter_timestamp = (usec_t) u;
2874 else if (streq(name, "InactiveExitTimestamp"))
2875 i->inactive_exit_timestamp = (usec_t) u;
2876 else if (streq(name, "InactiveExitTimestampMonotonic"))
2877 i->inactive_exit_timestamp_monotonic = (usec_t) u;
2878 else if (streq(name, "ActiveExitTimestamp"))
2879 i->active_exit_timestamp = (usec_t) u;
2880 else if (streq(name, "ConditionTimestamp"))
2881 i->condition_timestamp = (usec_t) u;
2886 case DBUS_TYPE_ARRAY: {
2888 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2889 startswith(name, "Exec")) {
2890 DBusMessageIter sub;
2892 dbus_message_iter_recurse(iter, &sub);
2893 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2894 ExecStatusInfo *info;
2897 if (!(info = new0(ExecStatusInfo, 1)))
2900 if (!(info->name = strdup(name))) {
2905 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2910 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2912 dbus_message_iter_next(&sub);
2914 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING &&
2915 streq(name, "Documentation")) {
2917 DBusMessageIter sub;
2919 dbus_message_iter_recurse(iter, &sub);
2920 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING) {
2924 dbus_message_iter_get_basic(&sub, &s);
2926 l = strv_append(i->documentation, s);
2930 strv_free(i->documentation);
2931 i->documentation = l;
2933 dbus_message_iter_next(&sub);
2940 case DBUS_TYPE_STRUCT: {
2942 if (streq(name, "LoadError")) {
2943 DBusMessageIter sub;
2944 const char *n, *message;
2947 dbus_message_iter_recurse(iter, &sub);
2949 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &n, true);
2953 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &message, false);
2957 if (!isempty(message))
2958 i->load_error = message;
2968 static int print_property(const char *name, DBusMessageIter *iter) {
2972 /* This is a low-level property printer, see
2973 * print_status_info() for the nicer output */
2975 if (arg_property && !strv_find(arg_property, name))
2978 switch (dbus_message_iter_get_arg_type(iter)) {
2980 case DBUS_TYPE_STRUCT: {
2981 DBusMessageIter sub;
2982 dbus_message_iter_recurse(iter, &sub);
2984 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2987 dbus_message_iter_get_basic(&sub, &u);
2990 printf("%s=%u\n", name, (unsigned) u);
2992 printf("%s=\n", name);
2995 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2998 dbus_message_iter_get_basic(&sub, &s);
3000 if (arg_all || s[0])
3001 printf("%s=%s\n", name, s);
3004 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "LoadError")) {
3005 const char *a = NULL, *b = NULL;
3007 if (bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &a, true) >= 0)
3008 bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &b, false);
3010 if (arg_all || !isempty(a) || !isempty(b))
3011 printf("%s=%s \"%s\"\n", name, strempty(a), strempty(b));
3019 case DBUS_TYPE_ARRAY:
3021 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
3022 DBusMessageIter sub, sub2;
3024 dbus_message_iter_recurse(iter, &sub);
3025 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3029 dbus_message_iter_recurse(&sub, &sub2);
3031 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
3032 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
3033 printf("EnvironmentFile=%s (ignore_errors=%s)\n", path, yes_no(ignore));
3035 dbus_message_iter_next(&sub);
3040 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
3041 DBusMessageIter sub, sub2;
3043 dbus_message_iter_recurse(iter, &sub);
3044 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3045 const char *type, *path;
3047 dbus_message_iter_recurse(&sub, &sub2);
3049 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
3050 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
3051 printf("%s=%s\n", type, path);
3053 dbus_message_iter_next(&sub);
3058 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
3059 DBusMessageIter sub, sub2;
3061 dbus_message_iter_recurse(iter, &sub);
3062 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3064 uint64_t value, next_elapse;
3066 dbus_message_iter_recurse(&sub, &sub2);
3068 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
3069 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
3070 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
3071 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
3073 printf("%s={ value=%s ; next_elapse=%s }\n",
3075 format_timespan(timespan1, sizeof(timespan1), value),
3076 format_timespan(timespan2, sizeof(timespan2), next_elapse));
3079 dbus_message_iter_next(&sub);
3084 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "ControlGroupAttributes")) {
3085 DBusMessageIter sub, sub2;
3087 dbus_message_iter_recurse(iter, &sub);
3088 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3089 const char *controller, *attr, *value;
3091 dbus_message_iter_recurse(&sub, &sub2);
3093 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &controller, true) >= 0 &&
3094 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &attr, true) >= 0 &&
3095 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &value, false) >= 0) {
3097 printf("ControlGroupAttribute={ controller=%s ; attribute=%s ; value=\"%s\" }\n",
3103 dbus_message_iter_next(&sub);
3108 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
3109 DBusMessageIter sub;
3111 dbus_message_iter_recurse(iter, &sub);
3112 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3113 ExecStatusInfo info;
3116 if (exec_status_info_deserialize(&sub, &info) >= 0) {
3117 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
3120 t = strv_join(info.argv, " ");
3122 printf("%s={ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
3126 yes_no(info.ignore),
3127 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
3128 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
3129 (unsigned) info. pid,
3130 sigchld_code_to_string(info.code),
3132 info.code == CLD_EXITED ? "" : "/",
3133 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
3139 strv_free(info.argv);
3141 dbus_message_iter_next(&sub);
3150 if (generic_print_property(name, iter, arg_all) > 0)
3154 printf("%s=[unprintable]\n", name);
3159 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
3160 DBusMessage *m = NULL, *reply = NULL;
3161 const char *interface = "";
3164 DBusMessageIter iter, sub, sub2, sub3;
3165 UnitStatusInfo info;
3173 dbus_error_init(&error);
3175 if (!(m = dbus_message_new_method_call(
3176 "org.freedesktop.systemd1",
3178 "org.freedesktop.DBus.Properties",
3180 log_error("Could not allocate message.");
3185 if (!dbus_message_append_args(m,
3186 DBUS_TYPE_STRING, &interface,
3187 DBUS_TYPE_INVALID)) {
3188 log_error("Could not append arguments to message.");
3193 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3194 log_error("Failed to issue method call: %s", bus_error_message(&error));
3199 if (!dbus_message_iter_init(reply, &iter) ||
3200 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
3201 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
3202 log_error("Failed to parse reply.");
3207 dbus_message_iter_recurse(&iter, &sub);
3214 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
3217 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
3218 log_error("Failed to parse reply.");
3223 dbus_message_iter_recurse(&sub, &sub2);
3225 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
3226 log_error("Failed to parse reply.");
3231 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
3232 log_error("Failed to parse reply.");
3237 dbus_message_iter_recurse(&sub2, &sub3);
3239 if (show_properties)
3240 r = print_property(name, &sub3);
3242 r = status_property(name, &sub3, &info);
3245 log_error("Failed to parse reply.");
3250 dbus_message_iter_next(&sub);
3255 if (!show_properties) {
3256 if (streq(verb, "help"))
3257 show_unit_help(&info);
3259 print_status_info(&info);
3262 strv_free(info.documentation);
3264 if (!streq_ptr(info.active_state, "active") &&
3265 !streq_ptr(info.active_state, "reloading") &&
3266 streq(verb, "status"))
3267 /* According to LSB: "program not running" */
3270 while ((p = info.exec)) {
3271 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
3272 exec_status_info_free(p);
3277 dbus_message_unref(m);
3280 dbus_message_unref(reply);
3282 dbus_error_free(&error);
3287 static int show_one_by_pid(const char *verb, DBusConnection *bus, uint32_t pid, bool *new_line) {
3288 DBusMessage *m = NULL, *reply = NULL;
3289 const char *path = NULL;
3293 dbus_error_init(&error);
3295 m = dbus_message_new_method_call(
3296 "org.freedesktop.systemd1",
3297 "/org/freedesktop/systemd1",
3298 "org.freedesktop.systemd1.Manager",
3301 log_error("Could not allocate message.");
3306 if (!dbus_message_append_args(m,
3307 DBUS_TYPE_UINT32, &pid,
3308 DBUS_TYPE_INVALID)) {
3309 log_error("Could not append arguments to message.");
3314 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3316 log_error("Failed to issue method call: %s", bus_error_message(&error));
3321 if (!dbus_message_get_args(reply, &error,
3322 DBUS_TYPE_OBJECT_PATH, &path,
3323 DBUS_TYPE_INVALID)) {
3324 log_error("Failed to parse reply: %s", bus_error_message(&error));
3329 r = show_one(verb, bus, path, false, new_line);
3333 dbus_message_unref(m);
3336 dbus_message_unref(reply);
3338 dbus_error_free(&error);
3343 static int show(DBusConnection *bus, char **args) {
3345 bool show_properties, new_line = false;
3351 show_properties = streq(args[0], "show");
3353 if (show_properties)
3354 pager_open_if_enabled();
3356 if (show_properties && strv_length(args) <= 1) {
3357 /* If not argument is specified inspect the manager
3360 return show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
3363 STRV_FOREACH(name, args+1) {
3366 if (safe_atou32(*name, &id) < 0) {
3368 /* Interpret as unit name */
3371 e = bus_path_escape(*name);
3374 p = strappend("/org/freedesktop/systemd1/unit/", e);
3379 r = show_one(args[0], bus, p, show_properties, &new_line);
3385 } else if (show_properties) {
3387 /* Interpret as job id */
3390 if (asprintf(&p, "/org/freedesktop/systemd1/job/%u", id) < 0)
3393 r = show_one(args[0], bus, p, show_properties, &new_line);
3401 /* Interpret as PID */
3403 r = show_one_by_pid(args[0], bus, id, &new_line);
3412 static int dump(DBusConnection *bus, char **args) {
3413 DBusMessage *m = NULL, *reply = NULL;
3418 dbus_error_init(&error);
3420 pager_open_if_enabled();
3422 if (!(m = dbus_message_new_method_call(
3423 "org.freedesktop.systemd1",
3424 "/org/freedesktop/systemd1",
3425 "org.freedesktop.systemd1.Manager",
3427 log_error("Could not allocate message.");
3431 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3432 log_error("Failed to issue method call: %s", bus_error_message(&error));
3437 if (!dbus_message_get_args(reply, &error,
3438 DBUS_TYPE_STRING, &text,
3439 DBUS_TYPE_INVALID)) {
3440 log_error("Failed to parse reply: %s", bus_error_message(&error));
3445 fputs(text, stdout);
3451 dbus_message_unref(m);
3454 dbus_message_unref(reply);
3456 dbus_error_free(&error);
3461 static int snapshot(DBusConnection *bus, char **args) {
3462 DBusMessage *m = NULL, *reply = NULL;
3465 const char *name = "", *path, *id;
3466 dbus_bool_t cleanup = FALSE;
3467 DBusMessageIter iter, sub;
3469 *interface = "org.freedesktop.systemd1.Unit",
3472 dbus_error_init(&error);
3474 if (!(m = dbus_message_new_method_call(
3475 "org.freedesktop.systemd1",
3476 "/org/freedesktop/systemd1",
3477 "org.freedesktop.systemd1.Manager",
3478 "CreateSnapshot"))) {
3479 log_error("Could not allocate message.");
3483 if (strv_length(args) > 1)
3486 if (!dbus_message_append_args(m,
3487 DBUS_TYPE_STRING, &name,
3488 DBUS_TYPE_BOOLEAN, &cleanup,
3489 DBUS_TYPE_INVALID)) {
3490 log_error("Could not append arguments to message.");
3495 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3496 log_error("Failed to issue method call: %s", bus_error_message(&error));
3501 if (!dbus_message_get_args(reply, &error,
3502 DBUS_TYPE_OBJECT_PATH, &path,
3503 DBUS_TYPE_INVALID)) {
3504 log_error("Failed to parse reply: %s", bus_error_message(&error));
3509 dbus_message_unref(m);
3510 if (!(m = dbus_message_new_method_call(
3511 "org.freedesktop.systemd1",
3513 "org.freedesktop.DBus.Properties",
3515 log_error("Could not allocate message.");
3519 if (!dbus_message_append_args(m,
3520 DBUS_TYPE_STRING, &interface,
3521 DBUS_TYPE_STRING, &property,
3522 DBUS_TYPE_INVALID)) {
3523 log_error("Could not append arguments to message.");
3528 dbus_message_unref(reply);
3529 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3530 log_error("Failed to issue method call: %s", bus_error_message(&error));
3535 if (!dbus_message_iter_init(reply, &iter) ||
3536 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3537 log_error("Failed to parse reply.");
3542 dbus_message_iter_recurse(&iter, &sub);
3544 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3545 log_error("Failed to parse reply.");
3550 dbus_message_iter_get_basic(&sub, &id);
3558 dbus_message_unref(m);
3561 dbus_message_unref(reply);
3563 dbus_error_free(&error);
3568 static int delete_snapshot(DBusConnection *bus, char **args) {
3569 DBusMessage *m = NULL, *reply = NULL;
3577 dbus_error_init(&error);
3579 STRV_FOREACH(name, args+1) {
3580 const char *path = NULL;
3582 if (!(m = dbus_message_new_method_call(
3583 "org.freedesktop.systemd1",
3584 "/org/freedesktop/systemd1",
3585 "org.freedesktop.systemd1.Manager",
3587 log_error("Could not allocate message.");
3592 if (!dbus_message_append_args(m,
3593 DBUS_TYPE_STRING, name,
3594 DBUS_TYPE_INVALID)) {
3595 log_error("Could not append arguments to message.");
3600 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3601 log_error("Failed to issue method call: %s", bus_error_message(&error));
3606 if (!dbus_message_get_args(reply, &error,
3607 DBUS_TYPE_OBJECT_PATH, &path,
3608 DBUS_TYPE_INVALID)) {
3609 log_error("Failed to parse reply: %s", bus_error_message(&error));
3614 dbus_message_unref(m);
3615 if (!(m = dbus_message_new_method_call(
3616 "org.freedesktop.systemd1",
3618 "org.freedesktop.systemd1.Snapshot",
3620 log_error("Could not allocate message.");
3625 dbus_message_unref(reply);
3626 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3627 log_error("Failed to issue method call: %s", bus_error_message(&error));
3632 dbus_message_unref(m);
3633 dbus_message_unref(reply);
3641 dbus_message_unref(m);
3644 dbus_message_unref(reply);
3646 dbus_error_free(&error);
3651 static int daemon_reload(DBusConnection *bus, char **args) {
3652 DBusMessage *m = NULL, *reply = NULL;
3657 dbus_error_init(&error);
3659 if (arg_action == ACTION_RELOAD)
3661 else if (arg_action == ACTION_REEXEC)
3662 method = "Reexecute";
3664 assert(arg_action == ACTION_SYSTEMCTL);
3667 streq(args[0], "clear-jobs") ||
3668 streq(args[0], "cancel") ? "ClearJobs" :
3669 streq(args[0], "daemon-reexec") ? "Reexecute" :
3670 streq(args[0], "reset-failed") ? "ResetFailed" :
3671 streq(args[0], "halt") ? "Halt" :
3672 streq(args[0], "poweroff") ? "PowerOff" :
3673 streq(args[0], "reboot") ? "Reboot" :
3674 streq(args[0], "kexec") ? "KExec" :
3675 streq(args[0], "exit") ? "Exit" :
3676 /* "daemon-reload" */ "Reload";
3679 if (!(m = dbus_message_new_method_call(
3680 "org.freedesktop.systemd1",
3681 "/org/freedesktop/systemd1",
3682 "org.freedesktop.systemd1.Manager",
3684 log_error("Could not allocate message.");
3688 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3690 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3691 /* There's always a fallback possible for
3692 * legacy actions. */
3697 if (streq(method, "Reexecute") && dbus_error_has_name(&error, DBUS_ERROR_NO_REPLY)) {
3698 /* On reexecution, we expect a disconnect, not
3704 log_error("Failed to issue method call: %s", bus_error_message(&error));
3713 dbus_message_unref(m);
3716 dbus_message_unref(reply);
3718 dbus_error_free(&error);
3723 static int reset_failed(DBusConnection *bus, char **args) {
3724 DBusMessage *m = NULL;
3730 dbus_error_init(&error);
3732 if (strv_length(args) <= 1)
3733 return daemon_reload(bus, args);
3735 STRV_FOREACH(name, args+1) {
3738 if (!(m = dbus_message_new_method_call(
3739 "org.freedesktop.systemd1",
3740 "/org/freedesktop/systemd1",
3741 "org.freedesktop.systemd1.Manager",
3742 "ResetFailedUnit"))) {
3743 log_error("Could not allocate message.");
3748 if (!dbus_message_append_args(m,
3749 DBUS_TYPE_STRING, name,
3750 DBUS_TYPE_INVALID)) {
3751 log_error("Could not append arguments to message.");
3756 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3757 log_error("Failed to issue method call: %s", bus_error_message(&error));
3762 dbus_message_unref(m);
3763 dbus_message_unref(reply);
3771 dbus_message_unref(m);
3773 dbus_error_free(&error);
3778 static int show_enviroment(DBusConnection *bus, char **args) {
3779 DBusMessage *m = NULL, *reply = NULL;
3781 DBusMessageIter iter, sub, sub2;
3784 *interface = "org.freedesktop.systemd1.Manager",
3785 *property = "Environment";
3787 dbus_error_init(&error);
3789 pager_open_if_enabled();
3791 if (!(m = dbus_message_new_method_call(
3792 "org.freedesktop.systemd1",
3793 "/org/freedesktop/systemd1",
3794 "org.freedesktop.DBus.Properties",
3796 log_error("Could not allocate message.");
3800 if (!dbus_message_append_args(m,
3801 DBUS_TYPE_STRING, &interface,
3802 DBUS_TYPE_STRING, &property,
3803 DBUS_TYPE_INVALID)) {
3804 log_error("Could not append arguments to message.");
3809 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3810 log_error("Failed to issue method call: %s", bus_error_message(&error));
3815 if (!dbus_message_iter_init(reply, &iter) ||
3816 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3817 log_error("Failed to parse reply.");
3822 dbus_message_iter_recurse(&iter, &sub);
3824 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3825 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3826 log_error("Failed to parse reply.");
3831 dbus_message_iter_recurse(&sub, &sub2);
3833 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3836 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3837 log_error("Failed to parse reply.");
3842 dbus_message_iter_get_basic(&sub2, &text);
3843 printf("%s\n", text);
3845 dbus_message_iter_next(&sub2);
3852 dbus_message_unref(m);
3855 dbus_message_unref(reply);
3857 dbus_error_free(&error);
3862 static int switch_root(DBusConnection *bus, char **args) {
3863 DBusMessage *m = NULL, *reply = NULL;
3865 const char *root, *init;
3869 dbus_error_init(&error);
3871 l = strv_length(args);
3872 if (l < 2 || l > 3) {
3873 log_error("Wrong number of arguments.");
3878 init = l >= 3 ? args[2] : "";
3880 m = dbus_message_new_method_call(
3881 "org.freedesktop.systemd1",
3882 "/org/freedesktop/systemd1",
3883 "org.freedesktop.systemd1.Manager",
3886 log_error("Could not allocate message.");
3890 if (!dbus_message_append_args(
3892 DBUS_TYPE_STRING, &root,
3893 DBUS_TYPE_STRING, &init,
3894 DBUS_TYPE_INVALID)) {
3895 log_error("Could not append arguments to message.");
3900 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3902 log_error("Failed to issue method call: %s", bus_error_message(&error));
3911 dbus_message_unref(m);
3914 dbus_message_unref(reply);
3916 dbus_error_free(&error);
3921 static int set_environment(DBusConnection *bus, char **args) {
3922 DBusMessage *m = NULL, *reply = NULL;
3926 DBusMessageIter iter, sub;
3929 dbus_error_init(&error);
3931 method = streq(args[0], "set-environment")
3933 : "UnsetEnvironment";
3935 if (!(m = dbus_message_new_method_call(
3936 "org.freedesktop.systemd1",
3937 "/org/freedesktop/systemd1",
3938 "org.freedesktop.systemd1.Manager",
3941 log_error("Could not allocate message.");
3945 dbus_message_iter_init_append(m, &iter);
3947 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3948 log_error("Could not append arguments to message.");
3953 STRV_FOREACH(name, args+1)
3954 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, name)) {
3955 log_error("Could not append arguments to message.");
3960 if (!dbus_message_iter_close_container(&iter, &sub)) {
3961 log_error("Could not append arguments to message.");
3966 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3967 log_error("Failed to issue method call: %s", bus_error_message(&error));
3976 dbus_message_unref(m);
3979 dbus_message_unref(reply);
3981 dbus_error_free(&error);
3986 static int enable_sysv_units(char **args) {
3989 #if defined (HAVE_SYSV_COMPAT) && (defined(TARGET_FEDORA) || defined(TARGET_MANDRIVA) || defined(TARGET_SUSE) || defined(TARGET_MEEGO) || defined(TARGET_ALTLINUX) || defined(TARGET_MAGEIA))
3990 const char *verb = args[0];
3991 unsigned f = 1, t = 1;
3994 if (arg_scope != UNIT_FILE_SYSTEM)
3997 if (!streq(verb, "enable") &&
3998 !streq(verb, "disable") &&
3999 !streq(verb, "is-enabled"))
4002 /* Processes all SysV units, and reshuffles the array so that
4003 * afterwards only the native units remain */
4006 r = lookup_paths_init(&paths, MANAGER_SYSTEM, false, NULL, NULL, NULL);
4011 for (f = 1; args[f]; f++) {
4014 bool found_native = false, found_sysv;
4016 const char *argv[6] = { "/sbin/chkconfig", NULL, NULL, NULL, NULL };
4017 char **k, *l, *q = NULL;
4024 if (!endswith(name, ".service"))
4027 if (path_is_absolute(name))
4030 STRV_FOREACH(k, paths.unit_path) {
4033 if (!isempty(arg_root))
4034 asprintf(&p, "%s/%s/%s", arg_root, *k, name);
4036 asprintf(&p, "%s/%s", *k, name);
4039 log_error("No memory");
4044 found_native = access(p, F_OK) >= 0;
4055 if (!isempty(arg_root))
4056 asprintf(&p, "%s/" SYSTEM_SYSVINIT_PATH "/%s", arg_root, name);
4058 asprintf(&p, SYSTEM_SYSVINIT_PATH "/%s", name);
4060 log_error("No memory");
4065 p[strlen(p) - sizeof(".service") + 1] = 0;
4066 found_sysv = access(p, F_OK) >= 0;
4073 /* Mark this entry, so that we don't try enabling it as native unit */
4074 args[f] = (char*) "";
4076 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", name);
4078 if (!isempty(arg_root))
4079 argv[c++] = q = strappend("--root=", arg_root);
4081 argv[c++] = path_get_file_name(p);
4083 streq(verb, "enable") ? "on" :
4084 streq(verb, "disable") ? "off" : "--level=5";
4087 l = strv_join((char**)argv, " ");
4089 log_error("No memory.");
4096 log_info("Executing %s", l);
4101 log_error("Failed to fork: %m");
4106 } else if (pid == 0) {
4109 execv(argv[0], (char**) argv);
4110 _exit(EXIT_FAILURE);
4116 j = wait_for_terminate(pid, &status);
4118 log_error("Failed to wait for child: %s", strerror(-r));
4123 if (status.si_code == CLD_EXITED) {
4124 if (streq(verb, "is-enabled")) {
4125 if (status.si_status == 0) {
4134 } else if (status.si_status != 0) {
4145 lookup_paths_free(&paths);
4147 /* Drop all SysV units */
4148 for (f = 1, t = 1; args[f]; f++) {
4150 if (isempty(args[f]))
4153 args[t++] = args[f];
4162 static int enable_unit(DBusConnection *bus, char **args) {
4163 const char *verb = args[0];
4164 UnitFileChange *changes = NULL;
4165 unsigned n_changes = 0, i;
4166 int carries_install_info = -1;
4167 DBusMessage *m = NULL, *reply = NULL;
4171 r = enable_sysv_units(args);
4178 dbus_error_init(&error);
4180 if (!bus || avoid_bus()) {
4181 if (streq(verb, "enable")) {
4182 r = unit_file_enable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4183 carries_install_info = r;
4184 } else if (streq(verb, "disable"))
4185 r = unit_file_disable(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
4186 else if (streq(verb, "reenable")) {
4187 r = unit_file_reenable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4188 carries_install_info = r;
4189 } else if (streq(verb, "link"))
4190 r = unit_file_link(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4191 else if (streq(verb, "preset")) {
4192 r = unit_file_preset(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4193 carries_install_info = r;
4194 } else if (streq(verb, "mask"))
4195 r = unit_file_mask(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4196 else if (streq(verb, "unmask"))
4197 r = unit_file_unmask(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
4199 assert_not_reached("Unknown verb");
4202 log_error("Operation failed: %s", strerror(-r));
4207 for (i = 0; i < n_changes; i++) {
4208 if (changes[i].type == UNIT_FILE_SYMLINK)
4209 log_info("ln -s '%s' '%s'", changes[i].source, changes[i].path);
4211 log_info("rm '%s'", changes[i].path);
4217 bool send_force = true, expect_carries_install_info = false;
4219 DBusMessageIter iter, sub, sub2;
4221 if (streq(verb, "enable")) {
4222 method = "EnableUnitFiles";
4223 expect_carries_install_info = true;
4224 } else if (streq(verb, "disable")) {
4225 method = "DisableUnitFiles";
4227 } else if (streq(verb, "reenable")) {
4228 method = "ReenableUnitFiles";
4229 expect_carries_install_info = true;
4230 } else if (streq(verb, "link"))
4231 method = "LinkUnitFiles";
4232 else if (streq(verb, "preset")) {
4233 method = "PresetUnitFiles";
4234 expect_carries_install_info = true;
4235 } else if (streq(verb, "mask"))
4236 method = "MaskUnitFiles";
4237 else if (streq(verb, "unmask")) {
4238 method = "UnmaskUnitFiles";
4241 assert_not_reached("Unknown verb");
4243 m = dbus_message_new_method_call(
4244 "org.freedesktop.systemd1",
4245 "/org/freedesktop/systemd1",
4246 "org.freedesktop.systemd1.Manager",
4249 log_error("Out of memory");
4254 dbus_message_iter_init_append(m, &iter);
4256 r = bus_append_strv_iter(&iter, args+1);
4258 log_error("Failed to append unit files.");
4263 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &a)) {
4264 log_error("Failed to append runtime boolean.");
4272 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b)) {
4273 log_error("Failed to append force boolean.");
4279 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
4281 log_error("Failed to issue method call: %s", bus_error_message(&error));
4286 if (!dbus_message_iter_init(reply, &iter)) {
4287 log_error("Failed to initialize iterator.");
4291 if (expect_carries_install_info) {
4292 r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_BOOLEAN, &b, true);
4294 log_error("Failed to parse reply.");
4298 carries_install_info = b;
4301 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
4302 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
4303 log_error("Failed to parse reply.");
4308 dbus_message_iter_recurse(&iter, &sub);
4309 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
4310 const char *type, *path, *source;
4312 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
4313 log_error("Failed to parse reply.");
4318 dbus_message_iter_recurse(&sub, &sub2);
4320 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
4321 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0 ||
4322 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &source, false) < 0) {
4323 log_error("Failed to parse reply.");
4329 if (streq(type, "symlink"))
4330 log_info("ln -s '%s' '%s'", source, path);
4332 log_info("rm '%s'", path);
4335 dbus_message_iter_next(&sub);
4338 /* Try to reload if enabeld */
4340 r = daemon_reload(bus, args);
4343 if (carries_install_info == 0)
4344 log_warning("Warning: unit files do not carry install information. No operation executed.");
4348 dbus_message_unref(m);
4351 dbus_message_unref(reply);
4353 unit_file_changes_free(changes, n_changes);
4355 dbus_error_free(&error);
4359 static int unit_is_enabled(DBusConnection *bus, char **args) {
4362 DBusMessage *m = NULL, *reply = NULL;
4366 dbus_error_init(&error);
4368 r = enable_sysv_units(args);
4374 if (!bus || avoid_bus()) {
4376 STRV_FOREACH(name, args+1) {
4377 UnitFileState state;
4379 state = unit_file_get_state(arg_scope, arg_root, *name);
4385 if (state == UNIT_FILE_ENABLED ||
4386 state == UNIT_FILE_ENABLED_RUNTIME ||
4387 state == UNIT_FILE_STATIC)
4391 puts(unit_file_state_to_string(state));
4395 STRV_FOREACH(name, args+1) {
4398 m = dbus_message_new_method_call(
4399 "org.freedesktop.systemd1",
4400 "/org/freedesktop/systemd1",
4401 "org.freedesktop.systemd1.Manager",
4402 "GetUnitFileState");
4404 log_error("Out of memory");
4409 if (!dbus_message_append_args(m,
4410 DBUS_TYPE_STRING, name,
4411 DBUS_TYPE_INVALID)) {
4412 log_error("Could not append arguments to message.");
4417 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
4419 log_error("Failed to issue method call: %s", bus_error_message(&error));
4424 if (!dbus_message_get_args(reply, &error,
4425 DBUS_TYPE_STRING, &s,
4426 DBUS_TYPE_INVALID)) {
4427 log_error("Failed to parse reply: %s", bus_error_message(&error));
4432 dbus_message_unref(m);
4433 dbus_message_unref(reply);
4436 if (streq(s, "enabled") ||
4437 streq(s, "enabled-runtime") ||
4446 r = enabled ? 0 : 1;
4450 dbus_message_unref(m);
4453 dbus_message_unref(reply);
4455 dbus_error_free(&error);
4459 static int systemctl_help(void) {
4461 pager_open_if_enabled();
4463 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4464 "Query or send control commands to the systemd manager.\n\n"
4465 " -h --help Show this help\n"
4466 " --version Show package version\n"
4467 " -t --type=TYPE List only units of a particular type\n"
4468 " -p --property=NAME Show only properties by this name\n"
4469 " -a --all Show all units/properties, including dead/empty ones\n"
4470 " --failed Show only failed units\n"
4471 " --full Don't ellipsize unit names on output\n"
4472 " --fail When queueing a new job, fail if conflicting jobs are\n"
4474 " --ignore-dependencies\n"
4475 " When queueing a new job, ignore all its dependencies\n"
4476 " --kill-who=WHO Who to send signal to\n"
4477 " -s --signal=SIGNAL Which signal to send\n"
4478 " -H --host=[USER@]HOST\n"
4479 " Show information for remote host\n"
4480 " -P --privileged Acquire privileges before execution\n"
4481 " -q --quiet Suppress output\n"
4482 " --no-block Do not wait until operation finished\n"
4483 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4484 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4486 " --no-legend Do not print a legend (column headers and hints)\n"
4487 " --no-pager Do not pipe output into a pager\n"
4488 " --no-ask-password\n"
4489 " Do not ask for system passwords\n"
4490 " --order When generating graph for dot, show only order\n"
4491 " --require When generating graph for dot, show only requirement\n"
4492 " --system Connect to system manager\n"
4493 " --user Connect to user service manager\n"
4494 " --global Enable/disable unit files globally\n"
4495 " -f --force When enabling unit files, override existing symlinks\n"
4496 " When shutting down, execute action immediately\n"
4497 " --root=PATH Enable unit files in the specified root directory\n"
4498 " --runtime Enable unit files only temporarily until next reboot\n"
4499 " -n --lines=INTEGER Journal entries to show\n"
4500 " --follow Follow journal\n"
4501 " -o --output=STRING Change journal output mode (short, short-monotonic,\n"
4502 " verbose, export, json, cat)\n\n"
4504 " list-units List loaded units\n"
4505 " start [NAME...] Start (activate) one or more units\n"
4506 " stop [NAME...] Stop (deactivate) one or more units\n"
4507 " reload [NAME...] Reload one or more units\n"
4508 " restart [NAME...] Start or restart one or more units\n"
4509 " try-restart [NAME...] Restart one or more units if active\n"
4510 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4511 " otherwise start or restart\n"
4512 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4513 " otherwise restart if active\n"
4514 " isolate [NAME] Start one unit and stop all others\n"
4515 " kill [NAME...] Send signal to processes of a unit\n"
4516 " is-active [NAME...] Check whether units are active\n"
4517 " status [NAME...|PID...] Show runtime status of one or more units\n"
4518 " show [NAME...|JOB...] Show properties of one or more\n"
4519 " units/jobs or the manager\n"
4520 " help [NAME...|PID...] Show manual for one or more units\n"
4521 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4523 " load [NAME...] Load one or more units\n\n"
4524 "Unit File Commands:\n"
4525 " list-unit-files List installed unit files\n"
4526 " enable [NAME...] Enable one or more unit files\n"
4527 " disable [NAME...] Disable one or more unit files\n"
4528 " reenable [NAME...] Reenable one or more unit files\n"
4529 " preset [NAME...] Enable/disable one or more unit files\n"
4530 " based on preset configuration\n"
4531 " mask [NAME...] Mask one or more units\n"
4532 " unmask [NAME...] Unmask one or more units\n"
4533 " link [PATH...] Link one or more units files into\n"
4534 " the search path\n"
4535 " is-enabled [NAME...] Check whether unit files are enabled\n\n"
4537 " list-jobs List jobs\n"
4538 " cancel [JOB...] Cancel all, one, or more jobs\n\n"
4539 "Status Commands:\n"
4540 " dump Dump server status\n"
4541 " dot Dump dependency graph for dot(1)\n\n"
4542 "Snapshot Commands:\n"
4543 " snapshot [NAME] Create a snapshot\n"
4544 " delete [NAME...] Remove one or more snapshots\n\n"
4545 "Environment Commands:\n"
4546 " show-environment Dump environment\n"
4547 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4548 " unset-environment [NAME...] Unset one or more environment variables\n\n"
4549 "Manager Lifecycle Commands:\n"
4550 " daemon-reload Reload systemd manager configuration\n"
4551 " daemon-reexec Reexecute systemd manager\n\n"
4552 "System Commands:\n"
4553 " default Enter system default mode\n"
4554 " rescue Enter system rescue mode\n"
4555 " emergency Enter system emergency mode\n"
4556 " halt Shut down and halt the system\n"
4557 " poweroff Shut down and power-off the system\n"
4558 " reboot Shut down and reboot the system\n"
4559 " kexec Shut down and reboot the system with kexec\n"
4560 " exit Request user instance exit\n"
4561 " switch-root [ROOT] [INIT] Change to a different root file system\n"
4562 " suspend Suspend the system\n"
4563 " hibernate Hibernate the system\n",
4564 program_invocation_short_name);
4569 static int halt_help(void) {
4571 printf("%s [OPTIONS...]\n\n"
4572 "%s the system.\n\n"
4573 " --help Show this help\n"
4574 " --halt Halt the machine\n"
4575 " -p --poweroff Switch off the machine\n"
4576 " --reboot Reboot the machine\n"
4577 " -f --force Force immediate halt/power-off/reboot\n"
4578 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4579 " -d --no-wtmp Don't write wtmp record\n"
4580 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4581 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4582 program_invocation_short_name,
4583 arg_action == ACTION_REBOOT ? "Reboot" :
4584 arg_action == ACTION_POWEROFF ? "Power off" :
4590 static int shutdown_help(void) {
4592 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4593 "Shut down the system.\n\n"
4594 " --help Show this help\n"
4595 " -H --halt Halt the machine\n"
4596 " -P --poweroff Power-off the machine\n"
4597 " -r --reboot Reboot the machine\n"
4598 " -h Equivalent to --poweroff, overridden by --halt\n"
4599 " -k Don't halt/power-off/reboot, just send warnings\n"
4600 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4601 " -c Cancel a pending shutdown\n",
4602 program_invocation_short_name);
4607 static int telinit_help(void) {
4609 printf("%s [OPTIONS...] {COMMAND}\n\n"
4610 "Send control commands to the init daemon.\n\n"
4611 " --help Show this help\n"
4612 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4614 " 0 Power-off the machine\n"
4615 " 6 Reboot the machine\n"
4616 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4617 " 1, s, S Enter rescue mode\n"
4618 " q, Q Reload init daemon configuration\n"
4619 " u, U Reexecute init daemon\n",
4620 program_invocation_short_name);
4625 static int runlevel_help(void) {
4627 printf("%s [OPTIONS...]\n\n"
4628 "Prints the previous and current runlevel of the init system.\n\n"
4629 " --help Show this help\n",
4630 program_invocation_short_name);
4635 static int systemctl_parse_argv(int argc, char *argv[]) {
4639 ARG_IGNORE_DEPENDENCIES,
4655 ARG_NO_ASK_PASSWORD,
4662 static const struct option options[] = {
4663 { "help", no_argument, NULL, 'h' },
4664 { "version", no_argument, NULL, ARG_VERSION },
4665 { "type", required_argument, NULL, 't' },
4666 { "property", required_argument, NULL, 'p' },
4667 { "all", no_argument, NULL, 'a' },
4668 { "failed", no_argument, NULL, ARG_FAILED },
4669 { "full", no_argument, NULL, ARG_FULL },
4670 { "fail", no_argument, NULL, ARG_FAIL },
4671 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4672 { "user", no_argument, NULL, ARG_USER },
4673 { "system", no_argument, NULL, ARG_SYSTEM },
4674 { "global", no_argument, NULL, ARG_GLOBAL },
4675 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4676 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
4677 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4678 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4679 { "quiet", no_argument, NULL, 'q' },
4680 { "order", no_argument, NULL, ARG_ORDER },
4681 { "require", no_argument, NULL, ARG_REQUIRE },
4682 { "root", required_argument, NULL, ARG_ROOT },
4683 { "force", no_argument, NULL, ARG_FORCE },
4684 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4685 { "kill-mode", required_argument, NULL, ARG_KILL_MODE }, /* undocumented on purpose */
4686 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4687 { "signal", required_argument, NULL, 's' },
4688 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4689 { "host", required_argument, NULL, 'H' },
4690 { "privileged",no_argument, NULL, 'P' },
4691 { "runtime", no_argument, NULL, ARG_RUNTIME },
4692 { "lines", required_argument, NULL, 'n' },
4693 { "follow", no_argument, NULL, ARG_FOLLOW },
4694 { "output", required_argument, NULL, 'o' },
4695 { NULL, 0, NULL, 0 }
4703 while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:Pn:o:", options, NULL)) >= 0) {
4712 puts(PACKAGE_STRING);
4714 puts(SYSTEMD_FEATURES);
4724 if (!(l = strv_append(arg_property, optarg)))
4727 strv_free(arg_property);
4730 /* If the user asked for a particular
4731 * property, show it to him, even if it is
4742 arg_job_mode = "fail";
4745 case ARG_IGNORE_DEPENDENCIES:
4746 arg_job_mode = "ignore-dependencies";
4750 arg_scope = UNIT_FILE_USER;
4754 arg_scope = UNIT_FILE_SYSTEM;
4758 arg_scope = UNIT_FILE_GLOBAL;
4762 arg_no_block = true;
4766 arg_no_legend = true;
4770 arg_no_pager = true;
4778 arg_dot = DOT_ORDER;
4782 arg_dot = DOT_REQUIRE;
4810 /* -f is short for both --follow and --force! */
4816 arg_no_reload = true;
4820 arg_kill_who = optarg;
4824 arg_kill_mode = optarg;
4828 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4829 log_error("Failed to parse signal string %s.", optarg);
4834 case ARG_NO_ASK_PASSWORD:
4835 arg_ask_password = false;
4839 arg_transport = TRANSPORT_POLKIT;
4843 arg_transport = TRANSPORT_SSH;
4852 if (safe_atou(optarg, &arg_lines) < 0) {
4853 log_error("Failed to parse lines '%s'", optarg);
4859 arg_output = output_mode_from_string(optarg);
4860 if (arg_output < 0) {
4861 log_error("Unknown output '%s'.", optarg);
4870 log_error("Unknown option code %c", c);
4875 if (arg_transport != TRANSPORT_NORMAL && arg_scope != UNIT_FILE_SYSTEM) {
4876 log_error("Cannot access user instance remotely.");
4883 static int halt_parse_argv(int argc, char *argv[]) {
4892 static const struct option options[] = {
4893 { "help", no_argument, NULL, ARG_HELP },
4894 { "halt", no_argument, NULL, ARG_HALT },
4895 { "poweroff", no_argument, NULL, 'p' },
4896 { "reboot", no_argument, NULL, ARG_REBOOT },
4897 { "force", no_argument, NULL, 'f' },
4898 { "wtmp-only", no_argument, NULL, 'w' },
4899 { "no-wtmp", no_argument, NULL, 'd' },
4900 { "no-sync", no_argument, NULL, 'n' },
4901 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4902 { NULL, 0, NULL, 0 }
4910 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4911 if (runlevel == '0' || runlevel == '6')
4914 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4922 arg_action = ACTION_HALT;
4926 if (arg_action != ACTION_REBOOT)
4927 arg_action = ACTION_POWEROFF;
4931 arg_action = ACTION_REBOOT;
4956 /* Compatibility nops */
4963 log_error("Unknown option code %c", c);
4968 if (optind < argc) {
4969 log_error("Too many arguments.");
4976 static int parse_time_spec(const char *t, usec_t *_u) {
4980 if (streq(t, "now"))
4982 else if (!strchr(t, ':')) {
4985 if (safe_atou64(t, &u) < 0)
4988 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4997 hour = strtol(t, &e, 10);
4998 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
5001 minute = strtol(e+1, &e, 10);
5002 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
5005 n = now(CLOCK_REALTIME);
5006 s = (time_t) (n / USEC_PER_SEC);
5009 assert_se(localtime_r(&s, &tm));
5011 tm.tm_hour = (int) hour;
5012 tm.tm_min = (int) minute;
5015 assert_se(s = mktime(&tm));
5017 *_u = (usec_t) s * USEC_PER_SEC;
5020 *_u += USEC_PER_DAY;
5026 static int shutdown_parse_argv(int argc, char *argv[]) {
5033 static const struct option options[] = {
5034 { "help", no_argument, NULL, ARG_HELP },
5035 { "halt", no_argument, NULL, 'H' },
5036 { "poweroff", no_argument, NULL, 'P' },
5037 { "reboot", no_argument, NULL, 'r' },
5038 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
5039 { "no-wall", no_argument, NULL, ARG_NO_WALL },
5040 { NULL, 0, NULL, 0 }
5048 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
5056 arg_action = ACTION_HALT;
5060 arg_action = ACTION_POWEROFF;
5065 arg_action = ACTION_KEXEC;
5067 arg_action = ACTION_REBOOT;
5071 arg_action = ACTION_KEXEC;
5075 if (arg_action != ACTION_HALT)
5076 arg_action = ACTION_POWEROFF;
5089 /* Compatibility nops */
5093 arg_action = ACTION_CANCEL_SHUTDOWN;
5100 log_error("Unknown option code %c", c);
5105 if (argc > optind) {
5106 r = parse_time_spec(argv[optind], &arg_when);
5108 log_error("Failed to parse time specification: %s", argv[optind]);
5112 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
5114 /* We skip the time argument */
5115 if (argc > optind + 1)
5116 arg_wall = argv + optind + 1;
5123 static int telinit_parse_argv(int argc, char *argv[]) {
5130 static const struct option options[] = {
5131 { "help", no_argument, NULL, ARG_HELP },
5132 { "no-wall", no_argument, NULL, ARG_NO_WALL },
5133 { NULL, 0, NULL, 0 }
5136 static const struct {
5140 { '0', ACTION_POWEROFF },
5141 { '6', ACTION_REBOOT },
5142 { '1', ACTION_RESCUE },
5143 { '2', ACTION_RUNLEVEL2 },
5144 { '3', ACTION_RUNLEVEL3 },
5145 { '4', ACTION_RUNLEVEL4 },
5146 { '5', ACTION_RUNLEVEL5 },
5147 { 's', ACTION_RESCUE },
5148 { 'S', ACTION_RESCUE },
5149 { 'q', ACTION_RELOAD },
5150 { 'Q', ACTION_RELOAD },
5151 { 'u', ACTION_REEXEC },
5152 { 'U', ACTION_REEXEC }
5161 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5176 log_error("Unknown option code %c", c);
5181 if (optind >= argc) {
5186 if (optind + 1 < argc) {
5187 log_error("Too many arguments.");
5191 if (strlen(argv[optind]) != 1) {
5192 log_error("Expected single character argument.");
5196 for (i = 0; i < ELEMENTSOF(table); i++)
5197 if (table[i].from == argv[optind][0])
5200 if (i >= ELEMENTSOF(table)) {
5201 log_error("Unknown command %s.", argv[optind]);
5205 arg_action = table[i].to;
5212 static int runlevel_parse_argv(int argc, char *argv[]) {
5218 static const struct option options[] = {
5219 { "help", no_argument, NULL, ARG_HELP },
5220 { NULL, 0, NULL, 0 }
5228 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5239 log_error("Unknown option code %c", c);
5244 if (optind < argc) {
5245 log_error("Too many arguments.");
5252 static int parse_argv(int argc, char *argv[]) {
5256 if (program_invocation_short_name) {
5258 if (strstr(program_invocation_short_name, "halt")) {
5259 arg_action = ACTION_HALT;
5260 return halt_parse_argv(argc, argv);
5261 } else if (strstr(program_invocation_short_name, "poweroff")) {
5262 arg_action = ACTION_POWEROFF;
5263 return halt_parse_argv(argc, argv);
5264 } else if (strstr(program_invocation_short_name, "reboot")) {
5266 arg_action = ACTION_KEXEC;
5268 arg_action = ACTION_REBOOT;
5269 return halt_parse_argv(argc, argv);
5270 } else if (strstr(program_invocation_short_name, "shutdown")) {
5271 arg_action = ACTION_POWEROFF;
5272 return shutdown_parse_argv(argc, argv);
5273 } else if (strstr(program_invocation_short_name, "init")) {
5275 if (sd_booted() > 0) {
5276 arg_action = ACTION_INVALID;
5277 return telinit_parse_argv(argc, argv);
5279 /* Hmm, so some other init system is
5280 * running, we need to forward this
5281 * request to it. For now we simply
5282 * guess that it is Upstart. */
5284 execv("/lib/upstart/telinit", argv);
5286 log_error("Couldn't find an alternative telinit implementation to spawn.");
5290 } else if (strstr(program_invocation_short_name, "runlevel")) {
5291 arg_action = ACTION_RUNLEVEL;
5292 return runlevel_parse_argv(argc, argv);
5296 arg_action = ACTION_SYSTEMCTL;
5297 return systemctl_parse_argv(argc, argv);
5300 static int action_to_runlevel(void) {
5302 static const char table[_ACTION_MAX] = {
5303 [ACTION_HALT] = '0',
5304 [ACTION_POWEROFF] = '0',
5305 [ACTION_REBOOT] = '6',
5306 [ACTION_RUNLEVEL2] = '2',
5307 [ACTION_RUNLEVEL3] = '3',
5308 [ACTION_RUNLEVEL4] = '4',
5309 [ACTION_RUNLEVEL5] = '5',
5310 [ACTION_RESCUE] = '1'
5313 assert(arg_action < _ACTION_MAX);
5315 return table[arg_action];
5318 static int talk_upstart(void) {
5319 DBusMessage *m = NULL, *reply = NULL;
5321 int previous, rl, r;
5323 env1_buf[] = "RUNLEVEL=X",
5324 env2_buf[] = "PREVLEVEL=X";
5325 char *env1 = env1_buf, *env2 = env2_buf;
5326 const char *emit = "runlevel";
5327 dbus_bool_t b_false = FALSE;
5328 DBusMessageIter iter, sub;
5329 DBusConnection *bus;
5331 dbus_error_init(&error);
5333 if (!(rl = action_to_runlevel()))
5336 if (utmp_get_runlevel(&previous, NULL) < 0)
5339 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
5340 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
5345 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
5350 if ((r = bus_check_peercred(bus)) < 0) {
5351 log_error("Failed to verify owner of bus.");
5355 if (!(m = dbus_message_new_method_call(
5356 "com.ubuntu.Upstart",
5357 "/com/ubuntu/Upstart",
5358 "com.ubuntu.Upstart0_6",
5361 log_error("Could not allocate message.");
5366 dbus_message_iter_init_append(m, &iter);
5368 env1_buf[sizeof(env1_buf)-2] = rl;
5369 env2_buf[sizeof(env2_buf)-2] = previous;
5371 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5372 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5373 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5374 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5375 !dbus_message_iter_close_container(&iter, &sub) ||
5376 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5377 log_error("Could not append arguments to message.");
5382 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5384 if (error_is_no_service(&error)) {
5389 log_error("Failed to issue method call: %s", bus_error_message(&error));
5398 dbus_message_unref(m);
5401 dbus_message_unref(reply);
5404 dbus_connection_flush(bus);
5405 dbus_connection_close(bus);
5406 dbus_connection_unref(bus);
5409 dbus_error_free(&error);
5414 static int talk_initctl(void) {
5415 struct init_request request;
5419 if (!(rl = action_to_runlevel()))
5423 request.magic = INIT_MAGIC;
5424 request.sleeptime = 0;
5425 request.cmd = INIT_CMD_RUNLVL;
5426 request.runlevel = rl;
5428 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5430 if (errno == ENOENT)
5433 log_error("Failed to open "INIT_FIFO": %m");
5438 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5439 close_nointr_nofail(fd);
5442 log_error("Failed to write to "INIT_FIFO": %m");
5443 return errno ? -errno : -EIO;
5449 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5451 static const struct {
5459 int (* const dispatch)(DBusConnection *bus, char **args);
5461 { "list-units", LESS, 1, list_units },
5462 { "list-unit-files", EQUAL, 1, list_unit_files },
5463 { "list-jobs", EQUAL, 1, list_jobs },
5464 { "clear-jobs", EQUAL, 1, daemon_reload },
5465 { "load", MORE, 2, load_unit },
5466 { "cancel", MORE, 2, cancel_job },
5467 { "start", MORE, 2, start_unit },
5468 { "stop", MORE, 2, start_unit },
5469 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5470 { "reload", MORE, 2, start_unit },
5471 { "restart", MORE, 2, start_unit },
5472 { "try-restart", MORE, 2, start_unit },
5473 { "reload-or-restart", MORE, 2, start_unit },
5474 { "reload-or-try-restart", MORE, 2, start_unit },
5475 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5476 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5477 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5478 { "isolate", EQUAL, 2, start_unit },
5479 { "kill", MORE, 2, kill_unit },
5480 { "is-active", MORE, 2, check_unit },
5481 { "check", MORE, 2, check_unit },
5482 { "show", MORE, 1, show },
5483 { "status", MORE, 2, show },
5484 { "help", MORE, 2, show },
5485 { "dump", EQUAL, 1, dump },
5486 { "dot", EQUAL, 1, dot },
5487 { "snapshot", LESS, 2, snapshot },
5488 { "delete", MORE, 2, delete_snapshot },
5489 { "daemon-reload", EQUAL, 1, daemon_reload },
5490 { "daemon-reexec", EQUAL, 1, daemon_reload },
5491 { "show-environment", EQUAL, 1, show_enviroment },
5492 { "set-environment", MORE, 2, set_environment },
5493 { "unset-environment", MORE, 2, set_environment },
5494 { "halt", EQUAL, 1, start_special },
5495 { "poweroff", EQUAL, 1, start_special },
5496 { "reboot", EQUAL, 1, start_special },
5497 { "kexec", EQUAL, 1, start_special },
5498 { "suspend", EQUAL, 1, start_special },
5499 { "hibernate", EQUAL, 1, start_special },
5500 { "default", EQUAL, 1, start_special },
5501 { "rescue", EQUAL, 1, start_special },
5502 { "emergency", EQUAL, 1, start_special },
5503 { "exit", EQUAL, 1, start_special },
5504 { "reset-failed", MORE, 1, reset_failed },
5505 { "enable", MORE, 2, enable_unit },
5506 { "disable", MORE, 2, enable_unit },
5507 { "is-enabled", MORE, 2, unit_is_enabled },
5508 { "reenable", MORE, 2, enable_unit },
5509 { "preset", MORE, 2, enable_unit },
5510 { "mask", MORE, 2, enable_unit },
5511 { "unmask", MORE, 2, enable_unit },
5512 { "link", MORE, 2, enable_unit },
5513 { "switch-root", MORE, 2, switch_root },
5523 left = argc - optind;
5526 /* Special rule: no arguments means "list-units" */
5529 if (streq(argv[optind], "help") && !argv[optind+1]) {
5530 log_error("This command expects one or more "
5531 "unit names. Did you mean --help?");
5535 for (i = 0; i < ELEMENTSOF(verbs); i++)
5536 if (streq(argv[optind], verbs[i].verb))
5539 if (i >= ELEMENTSOF(verbs)) {
5540 log_error("Unknown operation %s", argv[optind]);
5545 switch (verbs[i].argc_cmp) {
5548 if (left != verbs[i].argc) {
5549 log_error("Invalid number of arguments.");
5556 if (left < verbs[i].argc) {
5557 log_error("Too few arguments.");
5564 if (left > verbs[i].argc) {
5565 log_error("Too many arguments.");
5572 assert_not_reached("Unknown comparison operator.");
5575 /* Require a bus connection for all operations but
5577 if (!streq(verbs[i].verb, "enable") &&
5578 !streq(verbs[i].verb, "disable") &&
5579 !streq(verbs[i].verb, "is-enabled") &&
5580 !streq(verbs[i].verb, "list-unit-files") &&
5581 !streq(verbs[i].verb, "reenable") &&
5582 !streq(verbs[i].verb, "preset") &&
5583 !streq(verbs[i].verb, "mask") &&
5584 !streq(verbs[i].verb, "unmask") &&
5585 !streq(verbs[i].verb, "link")) {
5587 if (running_in_chroot() > 0) {
5588 log_info("Running in chroot, ignoring request.");
5592 if (((!streq(verbs[i].verb, "reboot") &&
5593 !streq(verbs[i].verb, "halt") &&
5594 !streq(verbs[i].verb, "poweroff")) || arg_force <= 0) && !bus) {
5595 log_error("Failed to get D-Bus connection: %s",
5596 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5602 if (!bus && !avoid_bus()) {
5603 log_error("Failed to get D-Bus connection: %s",
5604 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5609 return verbs[i].dispatch(bus, argv + optind);
5612 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
5614 struct msghdr msghdr;
5615 struct iovec iovec[2];
5616 union sockaddr_union sockaddr;
5617 struct sd_shutdown_command c;
5619 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
5626 c.dry_run = dry_run;
5630 sockaddr.sa.sa_family = AF_UNIX;
5631 strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5634 msghdr.msg_name = &sockaddr;
5635 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5638 iovec[0].iov_base = (char*) &c;
5639 iovec[0].iov_len = offsetof(struct sd_shutdown_command, wall_message);
5641 if (isempty(message))
5642 msghdr.msg_iovlen = 1;
5644 iovec[1].iov_base = (char*) message;
5645 iovec[1].iov_len = strlen(message);
5646 msghdr.msg_iovlen = 2;
5648 msghdr.msg_iov = iovec;
5650 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5651 close_nointr_nofail(fd);
5655 close_nointr_nofail(fd);
5659 static int reload_with_fallback(DBusConnection *bus) {
5662 /* First, try systemd via D-Bus. */
5663 if (daemon_reload(bus, NULL) >= 0)
5667 /* Nothing else worked, so let's try signals */
5668 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5670 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5671 log_error("kill() failed: %m");
5678 static int start_with_fallback(DBusConnection *bus) {
5681 /* First, try systemd via D-Bus. */
5682 if (start_unit(bus, NULL) >= 0)
5686 /* Hmm, talking to systemd via D-Bus didn't work. Then
5687 * let's try to talk to Upstart via D-Bus. */
5688 if (talk_upstart() > 0)
5691 /* Nothing else worked, so let's try
5693 if (talk_initctl() > 0)
5696 log_error("Failed to talk to init daemon.");
5700 warn_wall(arg_action);
5704 static void halt_now(enum action a) {
5706 /* Make sure C-A-D is handled by the kernel from this
5708 reboot(RB_ENABLE_CAD);
5713 log_info("Halting.");
5714 reboot(RB_HALT_SYSTEM);
5717 case ACTION_POWEROFF:
5718 log_info("Powering off.");
5719 reboot(RB_POWER_OFF);
5723 log_info("Rebooting.");
5724 reboot(RB_AUTOBOOT);
5728 assert_not_reached("Unknown halt action.");
5731 assert_not_reached("Uh? This shouldn't happen.");
5734 static int halt_main(DBusConnection *bus) {
5737 if (geteuid() != 0) {
5738 /* Try logind if we are a normal user and no special
5739 * mode applies. Maybe PolicyKit allows us to shutdown
5742 if (arg_when <= 0 &&
5745 (arg_action == ACTION_POWEROFF ||
5746 arg_action == ACTION_REBOOT)) {
5747 r = reboot_with_logind(bus, arg_action);
5752 log_error("Must be root.");
5759 m = strv_join(arg_wall, " ");
5760 r = send_shutdownd(arg_when,
5761 arg_action == ACTION_HALT ? 'H' :
5762 arg_action == ACTION_POWEROFF ? 'P' :
5763 arg_action == ACTION_KEXEC ? 'K' :
5771 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5773 char date[FORMAT_TIMESTAMP_MAX];
5775 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5776 format_timestamp(date, sizeof(date), arg_when));
5781 if (!arg_dry && !arg_force)
5782 return start_with_fallback(bus);
5785 if (sd_booted() > 0)
5786 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5788 r = utmp_put_shutdown();
5790 log_warning("Failed to write utmp record: %s", strerror(-r));
5800 halt_now(arg_action);
5801 /* We should never reach this. */
5805 static int runlevel_main(void) {
5806 int r, runlevel, previous;
5808 r = utmp_get_runlevel(&runlevel, &previous);
5815 previous <= 0 ? 'N' : previous,
5816 runlevel <= 0 ? 'N' : runlevel);
5821 int main(int argc, char*argv[]) {
5822 int r, retval = EXIT_FAILURE;
5823 DBusConnection *bus = NULL;
5826 dbus_error_init(&error);
5828 log_parse_environment();
5831 r = parse_argv(argc, argv);
5835 retval = EXIT_SUCCESS;
5839 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5840 * let's shortcut this */
5841 if (arg_action == ACTION_RUNLEVEL) {
5842 r = runlevel_main();
5843 retval = r < 0 ? EXIT_FAILURE : r;
5847 if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5848 log_info("Running in chroot, ignoring request.");
5854 if (arg_transport == TRANSPORT_NORMAL)
5855 bus_connect(arg_scope == UNIT_FILE_SYSTEM ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, &bus, &private_bus, &error);
5856 else if (arg_transport == TRANSPORT_POLKIT) {
5857 bus_connect_system_polkit(&bus, &error);
5858 private_bus = false;
5859 } else if (arg_transport == TRANSPORT_SSH) {
5860 bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5861 private_bus = false;
5863 assert_not_reached("Uh, invalid transport...");
5866 switch (arg_action) {
5868 case ACTION_SYSTEMCTL:
5869 r = systemctl_main(bus, argc, argv, &error);
5873 case ACTION_POWEROFF:
5879 case ACTION_RUNLEVEL2:
5880 case ACTION_RUNLEVEL3:
5881 case ACTION_RUNLEVEL4:
5882 case ACTION_RUNLEVEL5:
5884 case ACTION_EMERGENCY:
5885 case ACTION_DEFAULT:
5886 r = start_with_fallback(bus);
5891 r = reload_with_fallback(bus);
5894 case ACTION_CANCEL_SHUTDOWN:
5895 r = send_shutdownd(0, 0, false, false, NULL);
5898 case ACTION_INVALID:
5899 case ACTION_RUNLEVEL:
5901 assert_not_reached("Unknown action");
5904 retval = r < 0 ? EXIT_FAILURE : r;
5908 dbus_connection_flush(bus);
5909 dbus_connection_close(bus);
5910 dbus_connection_unref(bus);
5913 dbus_error_free(&error);
5917 strv_free(arg_property);
5920 ask_password_agent_close();
5921 polkit_agent_close();