1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <sys/reboot.h>
28 #include <sys/ioctl.h>
32 #include <sys/socket.h>
35 #include <sys/prctl.h>
36 #include <dbus/dbus.h>
38 #include <systemd/sd-daemon.h>
39 #include <systemd/sd-shutdown.h>
45 #include "utmp-wtmp.h"
48 #include "path-util.h"
50 #include "dbus-common.h"
51 #include "cgroup-show.h"
52 #include "cgroup-util.h"
54 #include "path-lookup.h"
55 #include "conf-parser.h"
56 #include "exit-status.h"
57 #include "bus-errors.h"
59 #include "unit-name.h"
61 #include "spawn-ask-password-agent.h"
62 #include "spawn-polkit-agent.h"
64 #include "logs-show.h"
65 #include "path-util.h"
67 static const char *arg_type = NULL;
68 static const char *arg_load_state = NULL;
69 static char **arg_property = NULL;
70 static bool arg_all = false;
71 static const char *arg_job_mode = "replace";
72 static UnitFileScope arg_scope = UNIT_FILE_SYSTEM;
73 static bool arg_no_block = false;
74 static bool arg_no_legend = false;
75 static bool arg_no_pager = false;
76 static bool arg_no_wtmp = false;
77 static bool arg_no_sync = false;
78 static bool arg_no_wall = false;
79 static bool arg_no_reload = false;
80 static bool arg_dry = false;
81 static bool arg_quiet = false;
82 static bool arg_full = false;
83 static int arg_force = 0;
84 static bool arg_ask_password = true;
85 static bool arg_failed = false;
86 static bool arg_runtime = false;
87 static char **arg_wall = NULL;
88 static const char *arg_kill_who = NULL;
89 static int arg_signal = SIGTERM;
90 static const char *arg_root = NULL;
91 static usec_t arg_when = 0;
112 ACTION_CANCEL_SHUTDOWN,
114 } arg_action = ACTION_SYSTEMCTL;
120 static enum transport {
124 } arg_transport = TRANSPORT_NORMAL;
125 static const char *arg_host = NULL;
126 static bool arg_follow = false;
127 static unsigned arg_lines = 10;
128 static OutputMode arg_output = OUTPUT_SHORT;
130 static bool private_bus = false;
132 static int daemon_reload(DBusConnection *bus, char **args);
133 static void halt_now(enum action a);
135 static bool on_tty(void) {
138 /* Note that this is invoked relatively early, before we start
139 * the pager. That means the value we return reflects whether
140 * we originally were started on a tty, not if we currently
141 * are. But this is intended, since we want colour and so on
142 * when run in our own pager. */
144 if (_unlikely_(t < 0))
145 t = isatty(STDOUT_FILENO) > 0;
150 static void pager_open_if_enabled(void) {
152 /* Cache result before we open the pager */
161 static void ask_password_agent_open_if_enabled(void) {
163 /* Open the password agent as a child process if necessary */
165 if (!arg_ask_password)
168 if (arg_scope != UNIT_FILE_SYSTEM)
171 ask_password_agent_open();
175 static void polkit_agent_open_if_enabled(void) {
177 /* Open the polkit agent as a child process if necessary */
179 if (!arg_ask_password)
182 if (arg_scope != UNIT_FILE_SYSTEM)
189 static const char *ansi_highlight_red(bool b) {
194 return b ? ANSI_HIGHLIGHT_RED_ON : ANSI_HIGHLIGHT_OFF;
197 static const char *ansi_highlight_green(bool b) {
202 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
205 static bool error_is_no_service(const DBusError *error) {
208 if (!dbus_error_is_set(error))
211 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
214 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
217 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
220 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
223 if (!dbus_error_is_set(error))
226 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
227 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
228 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
229 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
230 return EXIT_NOPERMISSION;
232 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
233 return EXIT_NOTINSTALLED;
235 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
236 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
237 return EXIT_NOTIMPLEMENTED;
239 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
240 return EXIT_NOTCONFIGURED;
248 static void warn_wall(enum action a) {
249 static const char *table[_ACTION_MAX] = {
250 [ACTION_HALT] = "The system is going down for system halt NOW!",
251 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
252 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
253 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
254 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
255 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
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_load_state || streq(u->load_state, arg_load_state)) &&
341 (arg_all || !(streq(u->active_state, "inactive")
342 || u->following[0]) || u->job_id > 0);
345 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
346 unsigned id_len, max_id_len, active_len, sub_len, job_len, desc_len, n_shown = 0;
347 const struct unit_info *u;
349 max_id_len = sizeof("UNIT")-1;
350 active_len = sizeof("ACTIVE")-1;
351 sub_len = sizeof("SUB")-1;
352 job_len = sizeof("JOB")-1;
355 for (u = unit_infos; u < unit_infos + c; u++) {
356 if (!output_show_unit(u))
359 max_id_len = MAX(max_id_len, strlen(u->id));
360 active_len = MAX(active_len, strlen(u->active_state));
361 sub_len = MAX(sub_len, strlen(u->sub_state));
363 job_len = MAX(job_len, strlen(u->job_type));
368 id_len = MIN(max_id_len, 25);
369 basic_len = 5 + id_len + 6 + active_len + sub_len + job_len;
370 if (basic_len < (unsigned) columns()) {
371 unsigned extra_len, incr;
372 extra_len = columns() - basic_len;
373 /* Either UNIT already got 25, or is fully satisfied.
374 * Grant up to 25 to DESC now. */
375 incr = MIN(extra_len, 25);
378 /* split the remaining space between UNIT and DESC,
379 * but do not give UNIT more than it needs. */
381 incr = MIN(extra_len / 2, max_id_len - id_len);
383 desc_len += extra_len - incr;
389 if (!arg_no_legend) {
390 printf("%-*s %-6s %-*s %-*s %-*s ", id_len, "UNIT", "LOAD",
391 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
392 if (!arg_full && arg_no_pager)
393 printf("%.*s\n", desc_len, "DESCRIPTION");
395 printf("%s\n", "DESCRIPTION");
398 for (u = unit_infos; u < unit_infos + c; u++) {
400 const char *on_loaded, *off_loaded;
401 const char *on_active, *off_active;
403 if (!output_show_unit(u))
408 if (streq(u->load_state, "error")) {
409 on_loaded = ansi_highlight_red(true);
410 off_loaded = ansi_highlight_red(false);
412 on_loaded = off_loaded = "";
414 if (streq(u->active_state, "failed")) {
415 on_active = ansi_highlight_red(true);
416 off_active = ansi_highlight_red(false);
418 on_active = off_active = "";
420 e = arg_full ? NULL : ellipsize(u->id, id_len, 33);
422 printf("%-*s %s%-6s%s %s%-*s %-*s%s %-*s ",
423 id_len, e ? e : u->id,
424 on_loaded, u->load_state, off_loaded,
425 on_active, active_len, u->active_state,
426 sub_len, u->sub_state, off_active,
427 job_len, u->job_id ? u->job_type : "");
428 if (!arg_full && arg_no_pager)
429 printf("%.*s\n", desc_len, u->description);
431 printf("%s\n", u->description);
436 if (!arg_no_legend) {
437 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
438 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
439 "SUB = The low-level unit activation state, values depend on unit type.\n"
440 "JOB = Pending job for the unit.\n");
443 printf("\n%u units listed.\n", n_shown);
445 printf("\n%u units listed. Pass --all to see inactive units, too.\n", n_shown);
449 static int list_units(DBusConnection *bus, char **args) {
450 DBusMessage *m = NULL, *reply = NULL;
453 DBusMessageIter iter, sub, sub2;
454 unsigned c = 0, n_units = 0;
455 struct unit_info *unit_infos = NULL;
457 dbus_error_init(&error);
461 pager_open_if_enabled();
463 if (!(m = dbus_message_new_method_call(
464 "org.freedesktop.systemd1",
465 "/org/freedesktop/systemd1",
466 "org.freedesktop.systemd1.Manager",
468 log_error("Could not allocate message.");
472 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
473 log_error("Failed to issue method call: %s", bus_error_message(&error));
478 if (!dbus_message_iter_init(reply, &iter) ||
479 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
480 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
481 log_error("Failed to parse reply.");
486 dbus_message_iter_recurse(&iter, &sub);
488 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
491 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
492 log_error("Failed to parse reply.");
500 n_units = MAX(2*c, 16);
501 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
504 log_error("Failed to allocate unit array.");
514 dbus_message_iter_recurse(&sub, &sub2);
516 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
517 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
518 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
519 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
520 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
521 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
522 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
523 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
524 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
525 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
526 log_error("Failed to parse reply.");
531 dbus_message_iter_next(&sub);
536 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
537 output_units_list(unit_infos, c);
544 dbus_message_unref(m);
547 dbus_message_unref(reply);
551 dbus_error_free(&error);
556 static int compare_unit_file_list(const void *a, const void *b) {
558 const UnitFileList *u = a, *v = b;
560 d1 = strrchr(u->path, '.');
561 d2 = strrchr(v->path, '.');
566 r = strcasecmp(d1, d2);
571 return strcasecmp(path_get_file_name(u->path), path_get_file_name(v->path));
574 static bool output_show_unit_file(const UnitFileList *u) {
577 return !arg_type || ((dot = strrchr(u->path, '.')) && streq(dot+1, arg_type));
580 static void output_unit_file_list(const UnitFileList *units, unsigned c) {
581 unsigned max_id_len, id_cols, state_cols, n_shown = 0;
582 const UnitFileList *u;
584 max_id_len = sizeof("UNIT FILE")-1;
585 state_cols = sizeof("STATE")-1;
586 for (u = units; u < units + c; u++) {
587 if (!output_show_unit_file(u))
590 max_id_len = MAX(max_id_len, strlen(path_get_file_name(u->path)));
591 state_cols = MAX(state_cols, strlen(unit_file_state_to_string(u->state)));
596 id_cols = MIN(max_id_len, 25);
597 basic_cols = 1 + id_cols + state_cols;
598 if (basic_cols < (unsigned) columns())
599 id_cols += MIN(columns() - basic_cols, max_id_len - id_cols);
601 id_cols = max_id_len;
604 printf("%-*s %-*s\n", id_cols, "UNIT FILE", state_cols, "STATE");
606 for (u = units; u < units + c; u++) {
608 const char *on, *off;
611 if (!output_show_unit_file(u))
616 if (u->state == UNIT_FILE_MASKED ||
617 u->state == UNIT_FILE_MASKED_RUNTIME ||
618 u->state == UNIT_FILE_DISABLED) {
619 on = ansi_highlight_red(true);
620 off = ansi_highlight_red(false);
621 } else if (u->state == UNIT_FILE_ENABLED) {
622 on = ansi_highlight_green(true);
623 off = ansi_highlight_green(false);
627 id = path_get_file_name(u->path);
629 e = arg_full ? NULL : ellipsize(id, id_cols, 33);
631 printf("%-*s %s%-*s%s\n",
633 on, state_cols, unit_file_state_to_string(u->state), off);
639 printf("\n%u unit files listed.\n", n_shown);
642 static int list_unit_files(DBusConnection *bus, char **args) {
643 DBusMessage *m = NULL, *reply = NULL;
646 DBusMessageIter iter, sub, sub2;
647 unsigned c = 0, n_units = 0;
648 UnitFileList *units = NULL;
650 dbus_error_init(&error);
652 pager_open_if_enabled();
659 h = hashmap_new(string_hash_func, string_compare_func);
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);
677 HASHMAP_FOREACH(u, h, i) {
678 memcpy(units + c++, u, sizeof(UnitFileList));
686 m = dbus_message_new_method_call(
687 "org.freedesktop.systemd1",
688 "/org/freedesktop/systemd1",
689 "org.freedesktop.systemd1.Manager",
692 log_error("Could not allocate message.");
696 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
698 log_error("Failed to issue method call: %s", bus_error_message(&error));
703 if (!dbus_message_iter_init(reply, &iter) ||
704 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
705 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
706 log_error("Failed to parse reply.");
711 dbus_message_iter_recurse(&iter, &sub);
713 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
717 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
718 log_error("Failed to parse reply.");
726 n_units = MAX(2*c, 16);
727 w = realloc(units, sizeof(struct UnitFileList) * n_units);
730 log_error("Failed to allocate unit array.");
740 dbus_message_iter_recurse(&sub, &sub2);
742 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->path, true) < 0 ||
743 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, false) < 0) {
744 log_error("Failed to parse reply.");
749 u->state = unit_file_state_from_string(state);
751 dbus_message_iter_next(&sub);
757 qsort(units, c, sizeof(UnitFileList), compare_unit_file_list);
758 output_unit_file_list(units, c);
765 dbus_message_unref(m);
768 dbus_message_unref(reply);
772 dbus_error_free(&error);
777 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
778 static const char * const colors[] = {
779 "Requires", "[color=\"black\"]",
780 "RequiresOverridable", "[color=\"black\"]",
781 "Requisite", "[color=\"darkblue\"]",
782 "RequisiteOverridable", "[color=\"darkblue\"]",
783 "Wants", "[color=\"grey66\"]",
784 "Conflicts", "[color=\"red\"]",
785 "ConflictedBy", "[color=\"red\"]",
786 "After", "[color=\"green\"]"
789 const char *c = NULL;
796 for (i = 0; i < ELEMENTSOF(colors); i += 2)
797 if (streq(colors[i], prop)) {
805 if (arg_dot != DOT_ALL)
806 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
809 switch (dbus_message_iter_get_arg_type(iter)) {
811 case DBUS_TYPE_ARRAY:
813 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
816 dbus_message_iter_recurse(iter, &sub);
818 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
821 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
822 dbus_message_iter_get_basic(&sub, &s);
823 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
825 dbus_message_iter_next(&sub);
835 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
836 DBusMessage *m = NULL, *reply = NULL;
837 const char *interface = "org.freedesktop.systemd1.Unit";
840 DBusMessageIter iter, sub, sub2, sub3;
845 dbus_error_init(&error);
847 if (!(m = dbus_message_new_method_call(
848 "org.freedesktop.systemd1",
850 "org.freedesktop.DBus.Properties",
852 log_error("Could not allocate message.");
857 if (!dbus_message_append_args(m,
858 DBUS_TYPE_STRING, &interface,
859 DBUS_TYPE_INVALID)) {
860 log_error("Could not append arguments to message.");
865 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
866 log_error("Failed to issue method call: %s", bus_error_message(&error));
871 if (!dbus_message_iter_init(reply, &iter) ||
872 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
873 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
874 log_error("Failed to parse reply.");
879 dbus_message_iter_recurse(&iter, &sub);
881 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
884 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
885 log_error("Failed to parse reply.");
890 dbus_message_iter_recurse(&sub, &sub2);
892 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
893 log_error("Failed to parse reply.");
898 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
899 log_error("Failed to parse reply.");
904 dbus_message_iter_recurse(&sub2, &sub3);
906 if (dot_one_property(name, prop, &sub3)) {
907 log_error("Failed to parse reply.");
912 dbus_message_iter_next(&sub);
919 dbus_message_unref(m);
922 dbus_message_unref(reply);
924 dbus_error_free(&error);
929 static int dot(DBusConnection *bus, char **args) {
930 DBusMessage *m = NULL, *reply = NULL;
933 DBusMessageIter iter, sub, sub2;
935 dbus_error_init(&error);
939 if (!(m = dbus_message_new_method_call(
940 "org.freedesktop.systemd1",
941 "/org/freedesktop/systemd1",
942 "org.freedesktop.systemd1.Manager",
944 log_error("Could not allocate message.");
948 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
949 log_error("Failed to issue method call: %s", bus_error_message(&error));
954 if (!dbus_message_iter_init(reply, &iter) ||
955 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
956 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
957 log_error("Failed to parse reply.");
962 printf("digraph systemd {\n");
964 dbus_message_iter_recurse(&iter, &sub);
965 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
966 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
968 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
969 log_error("Failed to parse reply.");
974 dbus_message_iter_recurse(&sub, &sub2);
976 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
977 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
978 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
979 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
980 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
981 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
982 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
983 log_error("Failed to parse reply.");
988 if ((r = dot_one(bus, id, unit_path)) < 0)
991 /* printf("\t\"%s\";\n", id); */
992 dbus_message_iter_next(&sub);
997 log_info(" Color legend: black = Requires\n"
998 " dark blue = Requisite\n"
999 " dark grey = Wants\n"
1000 " red = Conflicts\n"
1001 " green = After\n");
1004 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
1005 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
1011 dbus_message_unref(m);
1014 dbus_message_unref(reply);
1016 dbus_error_free(&error);
1021 static int list_jobs(DBusConnection *bus, char **args) {
1022 DBusMessage *m = NULL, *reply = NULL;
1025 DBusMessageIter iter, sub, sub2;
1028 dbus_error_init(&error);
1032 pager_open_if_enabled();
1034 if (!(m = dbus_message_new_method_call(
1035 "org.freedesktop.systemd1",
1036 "/org/freedesktop/systemd1",
1037 "org.freedesktop.systemd1.Manager",
1039 log_error("Could not allocate message.");
1043 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1044 log_error("Failed to issue method call: %s", bus_error_message(&error));
1049 if (!dbus_message_iter_init(reply, &iter) ||
1050 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1051 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
1052 log_error("Failed to parse reply.");
1057 dbus_message_iter_recurse(&iter, &sub);
1060 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
1062 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1063 const char *name, *type, *state, *job_path, *unit_path;
1067 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
1068 log_error("Failed to parse reply.");
1073 dbus_message_iter_recurse(&sub, &sub2);
1075 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
1076 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
1077 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
1078 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
1079 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
1080 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
1081 log_error("Failed to parse reply.");
1086 e = arg_full ? NULL : ellipsize(name, 25, 33);
1087 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
1092 dbus_message_iter_next(&sub);
1096 printf("\n%u jobs listed.\n", k);
1102 dbus_message_unref(m);
1105 dbus_message_unref(reply);
1107 dbus_error_free(&error);
1112 static int load_unit(DBusConnection *bus, char **args) {
1113 DBusMessage *m = NULL;
1118 dbus_error_init(&error);
1123 STRV_FOREACH(name, args+1) {
1128 if (!(m = dbus_message_new_method_call(
1129 "org.freedesktop.systemd1",
1130 "/org/freedesktop/systemd1",
1131 "org.freedesktop.systemd1.Manager",
1133 log_error("Could not allocate message.");
1138 n = unit_name_mangle(*name);
1139 b = dbus_message_append_args(m,
1140 DBUS_TYPE_STRING, n ? &n : name,
1144 log_error("Could not append arguments to message.");
1149 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
1151 log_error("Failed to issue method call: %s", bus_error_message(&error));
1156 dbus_message_unref(m);
1157 dbus_message_unref(reply);
1166 dbus_message_unref(m);
1168 dbus_error_free(&error);
1173 static int cancel_job(DBusConnection *bus, char **args) {
1174 DBusMessage *m = NULL, *reply = NULL;
1179 dbus_error_init(&error);
1184 if (strv_length(args) <= 1)
1185 return daemon_reload(bus, args);
1187 STRV_FOREACH(name, args+1) {
1191 if (!(m = dbus_message_new_method_call(
1192 "org.freedesktop.systemd1",
1193 "/org/freedesktop/systemd1",
1194 "org.freedesktop.systemd1.Manager",
1196 log_error("Could not allocate message.");
1201 if ((r = safe_atou(*name, &id)) < 0) {
1202 log_error("Failed to parse job id: %s", strerror(-r));
1206 assert_cc(sizeof(uint32_t) == sizeof(id));
1207 if (!dbus_message_append_args(m,
1208 DBUS_TYPE_UINT32, &id,
1209 DBUS_TYPE_INVALID)) {
1210 log_error("Could not append arguments to message.");
1215 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1216 log_error("Failed to issue method call: %s", bus_error_message(&error));
1221 if (!dbus_message_get_args(reply, &error,
1222 DBUS_TYPE_OBJECT_PATH, &path,
1223 DBUS_TYPE_INVALID)) {
1224 log_error("Failed to parse reply: %s", bus_error_message(&error));
1229 dbus_message_unref(m);
1230 if (!(m = dbus_message_new_method_call(
1231 "org.freedesktop.systemd1",
1233 "org.freedesktop.systemd1.Job",
1235 log_error("Could not allocate message.");
1240 dbus_message_unref(reply);
1241 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1242 log_error("Failed to issue method call: %s", bus_error_message(&error));
1247 dbus_message_unref(m);
1248 dbus_message_unref(reply);
1256 dbus_message_unref(m);
1259 dbus_message_unref(reply);
1261 dbus_error_free(&error);
1266 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1267 DBusMessage *m = NULL, *reply = NULL;
1268 dbus_bool_t b = FALSE;
1269 DBusMessageIter iter, sub;
1271 *interface = "org.freedesktop.systemd1.Unit",
1272 *property = "NeedDaemonReload",
1277 /* We ignore all errors here, since this is used to show a warning only */
1279 m = dbus_message_new_method_call(
1280 "org.freedesktop.systemd1",
1281 "/org/freedesktop/systemd1",
1282 "org.freedesktop.systemd1.Manager",
1287 n = unit_name_mangle(unit);
1288 k = dbus_message_append_args(m,
1289 DBUS_TYPE_STRING, n ? (const char**) &n : &unit,
1295 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL);
1299 if (!dbus_message_get_args(reply, NULL,
1300 DBUS_TYPE_OBJECT_PATH, &path,
1304 dbus_message_unref(m);
1305 m = dbus_message_new_method_call(
1306 "org.freedesktop.systemd1",
1308 "org.freedesktop.DBus.Properties",
1313 if (!dbus_message_append_args(m,
1314 DBUS_TYPE_STRING, &interface,
1315 DBUS_TYPE_STRING, &property,
1316 DBUS_TYPE_INVALID)) {
1320 dbus_message_unref(reply);
1321 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL);
1325 if (!dbus_message_iter_init(reply, &iter) ||
1326 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1329 dbus_message_iter_recurse(&iter, &sub);
1331 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1334 dbus_message_iter_get_basic(&sub, &b);
1338 dbus_message_unref(m);
1341 dbus_message_unref(reply);
1346 typedef struct WaitData {
1351 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1359 dbus_error_init(&error);
1361 log_debug("Got D-Bus request: %s.%s() on %s",
1362 dbus_message_get_interface(message),
1363 dbus_message_get_member(message),
1364 dbus_message_get_path(message));
1366 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1367 log_error("Warning! D-Bus connection terminated.");
1368 dbus_connection_close(connection);
1370 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1372 const char *path, *result, *unit;
1373 dbus_bool_t success = true;
1375 if (dbus_message_get_args(message, &error,
1376 DBUS_TYPE_UINT32, &id,
1377 DBUS_TYPE_OBJECT_PATH, &path,
1378 DBUS_TYPE_STRING, &unit,
1379 DBUS_TYPE_STRING, &result,
1380 DBUS_TYPE_INVALID)) {
1383 p = set_remove(d->set, (char*) path);
1387 d->result = strdup(result);
1392 dbus_error_free(&error);
1393 if (dbus_message_get_args(message, &error,
1394 DBUS_TYPE_UINT32, &id,
1395 DBUS_TYPE_OBJECT_PATH, &path,
1396 DBUS_TYPE_STRING, &result,
1397 DBUS_TYPE_INVALID)) {
1400 /* Compatibility with older systemd versions <
1401 * 183 during upgrades. This should be dropped
1403 p = set_remove(d->set, (char*) path);
1407 d->result = strdup(result);
1412 dbus_error_free(&error);
1413 if (dbus_message_get_args(message, &error,
1414 DBUS_TYPE_UINT32, &id,
1415 DBUS_TYPE_OBJECT_PATH, &path,
1416 DBUS_TYPE_BOOLEAN, &success,
1417 DBUS_TYPE_INVALID)) {
1420 /* Compatibility with older systemd versions <
1421 * 19 during upgrades. This should be dropped
1424 p = set_remove(d->set, (char*) path);
1428 d->result = strdup("failed");
1434 log_error("Failed to parse message: %s", bus_error_message(&error));
1438 dbus_error_free(&error);
1439 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1442 static int enable_wait_for_jobs(DBusConnection *bus) {
1450 dbus_error_init(&error);
1451 dbus_bus_add_match(bus,
1453 "sender='org.freedesktop.systemd1',"
1454 "interface='org.freedesktop.systemd1.Manager',"
1455 "member='JobRemoved',"
1456 "path='/org/freedesktop/systemd1'",
1459 if (dbus_error_is_set(&error)) {
1460 log_error("Failed to add match: %s", bus_error_message(&error));
1461 dbus_error_free(&error);
1465 /* This is slightly dirty, since we don't undo the match registrations. */
1469 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1479 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1480 log_error("Failed to add filter.");
1485 while (!set_isempty(s) &&
1486 dbus_connection_read_write_dispatch(bus, -1))
1489 if (!arg_quiet && d.result) {
1490 if (streq(d.result, "timeout"))
1491 log_error("Job timed out.");
1492 else if (streq(d.result, "canceled"))
1493 log_error("Job canceled.");
1494 else if (streq(d.result, "dependency"))
1495 log_error("A dependency job failed. See system journal for details.");
1496 else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
1497 log_error("Job failed. See system journal and 'systemctl status' for details.");
1500 if (streq_ptr(d.result, "timeout"))
1502 else if (streq_ptr(d.result, "canceled"))
1504 else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
1512 /* This is slightly dirty, since we don't undo the filter registration. */
1517 static int check_one_unit(DBusConnection *bus, char *name, bool quiet) {
1518 DBusMessage *m = NULL, *reply = NULL;
1520 DBusMessageIter iter, sub;
1522 *interface = "org.freedesktop.systemd1.Unit",
1523 *property = "ActiveState";
1524 const char *path = NULL;
1526 int r = 3; /* According to LSB: "program is not running" */
1533 dbus_error_init(&error);
1535 m = dbus_message_new_method_call(
1536 "org.freedesktop.systemd1",
1537 "/org/freedesktop/systemd1",
1538 "org.freedesktop.systemd1.Manager",
1541 log_error("Could not allocate message.");
1546 n = unit_name_mangle(name);
1547 b = dbus_message_append_args(m,
1548 DBUS_TYPE_STRING, n ? &n : &name,
1552 log_error("Could not append arguments to message.");
1557 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
1559 /* Hmm, cannot figure out anything about this unit... */
1566 if (!dbus_message_get_args(reply, &error,
1567 DBUS_TYPE_OBJECT_PATH, &path,
1568 DBUS_TYPE_INVALID)) {
1569 log_error("Failed to parse reply: %s", bus_error_message(&error));
1574 dbus_message_unref(m);
1575 m = dbus_message_new_method_call(
1576 "org.freedesktop.systemd1",
1578 "org.freedesktop.DBus.Properties",
1581 log_error("Could not allocate message.");
1586 if (!dbus_message_append_args(m,
1587 DBUS_TYPE_STRING, &interface,
1588 DBUS_TYPE_STRING, &property,
1589 DBUS_TYPE_INVALID)) {
1590 log_error("Could not append arguments to message.");
1595 dbus_message_unref(reply);
1596 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
1598 log_error("Failed to issue method call: %s", bus_error_message(&error));
1603 if (!dbus_message_iter_init(reply, &iter) ||
1604 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1605 log_error("Failed to parse reply.");
1610 dbus_message_iter_recurse(&iter, &sub);
1612 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1613 log_error("Failed to parse reply.");
1618 dbus_message_iter_get_basic(&sub, &state);
1623 if (streq(state, "active") || streq(state, "reloading"))
1628 dbus_message_unref(m);
1631 dbus_message_unref(reply);
1633 dbus_error_free(&error);
1638 static void check_triggering_units(
1639 DBusConnection *bus,
1640 const char *unit_name) {
1643 DBusMessage *m = NULL, *reply = NULL;
1644 DBusMessageIter iter, sub;
1645 char *service_trigger = NULL;
1646 const char *interface = "org.freedesktop.systemd1.Unit",
1647 *triggered_by_property = "TriggeredBy";
1649 char *unit_path = NULL, *n = NULL;
1650 bool print_warning_label = true;
1652 dbus_error_init(&error);
1654 n = unit_name_mangle(unit_name);
1655 unit_path = unit_dbus_path_from_name(n ? n : unit_name);
1658 log_error("Could not allocate dbus path.");
1662 m = dbus_message_new_method_call("org.freedesktop.systemd1",
1664 "org.freedesktop.DBus.Properties",
1667 log_error("Could not allocate message.");
1671 if (!dbus_message_append_args(m,
1672 DBUS_TYPE_STRING, &interface,
1673 DBUS_TYPE_STRING, &triggered_by_property,
1674 DBUS_TYPE_INVALID)) {
1675 log_error("Could not append arguments to message.");
1679 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
1681 log_error("Failed to issue method call: %s", bus_error_message(&error));
1685 if (!dbus_message_iter_init(reply, &iter) ||
1686 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1687 log_error("Failed to parse reply: %s", bus_error_message(&error));
1692 dbus_message_iter_recurse(&iter, &sub);
1693 dbus_message_iter_recurse(&sub, &iter);
1696 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1699 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1700 log_error("Failed to parse reply: %s", bus_error_message(&error));
1704 dbus_message_iter_get_basic(&sub, &service_trigger);
1706 r = check_one_unit(bus, service_trigger, true);
1710 if (print_warning_label) {
1711 log_warning("Warning: Stopping %s, but it can still be activated by:", unit_name);
1712 print_warning_label = false;
1714 log_warning(" %s", service_trigger);
1717 dbus_message_iter_next(&sub);
1721 dbus_message_unref(m);
1724 dbus_message_unref(reply);
1726 dbus_error_free(&error);
1731 static int start_unit_one(
1732 DBusConnection *bus,
1739 DBusMessage *m = NULL, *reply = NULL;
1750 assert(arg_no_block || s);
1752 m = dbus_message_new_method_call(
1753 "org.freedesktop.systemd1",
1754 "/org/freedesktop/systemd1",
1755 "org.freedesktop.systemd1.Manager",
1758 log_error("Could not allocate message.");
1763 n = unit_name_mangle(name);
1764 b = dbus_message_append_args(m,
1765 DBUS_TYPE_STRING, n ? (const char **) &n : &name,
1766 DBUS_TYPE_STRING, &mode,
1770 log_error("Could not append arguments to message.");
1775 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error);
1778 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1779 /* There's always a fallback possible for
1780 * legacy actions. */
1785 log_error("Failed to issue method call: %s", bus_error_message(error));
1790 if (!dbus_message_get_args(reply, error,
1791 DBUS_TYPE_OBJECT_PATH, &path,
1792 DBUS_TYPE_INVALID)) {
1793 log_error("Failed to parse reply: %s", bus_error_message(error));
1798 if (need_daemon_reload(bus, name))
1799 log_warning("Warning: Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1800 arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
1802 if (!arg_no_block) {
1805 if (!(p = strdup(path))) {
1806 log_error("Failed to duplicate path.");
1811 if ((r = set_put(s, p)) < 0) {
1813 log_error("Failed to add path to set.");
1818 /* When stopping a unit warn if it can still be triggered by
1819 * another active unit (socket, path, timer) */
1820 if (!arg_quiet && streq(method, "StopUnit"))
1821 check_triggering_units(bus, name);
1827 dbus_message_unref(m);
1830 dbus_message_unref(reply);
1835 static enum action verb_to_action(const char *verb) {
1836 if (streq(verb, "halt"))
1838 else if (streq(verb, "poweroff"))
1839 return ACTION_POWEROFF;
1840 else if (streq(verb, "reboot"))
1841 return ACTION_REBOOT;
1842 else if (streq(verb, "kexec"))
1843 return ACTION_KEXEC;
1844 else if (streq(verb, "rescue"))
1845 return ACTION_RESCUE;
1846 else if (streq(verb, "emergency"))
1847 return ACTION_EMERGENCY;
1848 else if (streq(verb, "default"))
1849 return ACTION_DEFAULT;
1850 else if (streq(verb, "exit"))
1852 else if (streq(verb, "suspend"))
1853 return ACTION_SUSPEND;
1854 else if (streq(verb, "hibernate"))
1855 return ACTION_HIBERNATE;
1857 return ACTION_INVALID;
1860 static int start_unit(DBusConnection *bus, char **args) {
1862 static const char * const table[_ACTION_MAX] = {
1863 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1864 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1865 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1866 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1867 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1868 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1869 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1870 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1871 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1872 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1873 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1874 [ACTION_EXIT] = SPECIAL_EXIT_TARGET,
1875 [ACTION_SUSPEND] = SPECIAL_SUSPEND_TARGET,
1876 [ACTION_HIBERNATE] = SPECIAL_HIBERNATE_TARGET
1880 const char *method, *mode, *one_name;
1885 dbus_error_init(&error);
1889 ask_password_agent_open_if_enabled();
1891 if (arg_action == ACTION_SYSTEMCTL) {
1893 streq(args[0], "stop") ||
1894 streq(args[0], "condstop") ? "StopUnit" :
1895 streq(args[0], "reload") ? "ReloadUnit" :
1896 streq(args[0], "restart") ? "RestartUnit" :
1898 streq(args[0], "try-restart") ||
1899 streq(args[0], "condrestart") ? "TryRestartUnit" :
1901 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1903 streq(args[0], "reload-or-try-restart") ||
1904 streq(args[0], "condreload") ||
1906 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1910 (streq(args[0], "isolate") ||
1911 streq(args[0], "rescue") ||
1912 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1914 one_name = table[verb_to_action(args[0])];
1917 assert(arg_action < ELEMENTSOF(table));
1918 assert(table[arg_action]);
1920 method = "StartUnit";
1922 mode = (arg_action == ACTION_EMERGENCY ||
1923 arg_action == ACTION_RESCUE ||
1924 arg_action == ACTION_RUNLEVEL2 ||
1925 arg_action == ACTION_RUNLEVEL3 ||
1926 arg_action == ACTION_RUNLEVEL4 ||
1927 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1929 one_name = table[arg_action];
1932 if (!arg_no_block) {
1933 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1934 log_error("Could not watch jobs: %s", strerror(-ret));
1938 if (!(s = set_new(string_hash_func, string_compare_func))) {
1939 log_error("Failed to allocate set.");
1946 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1949 STRV_FOREACH(name, args+1)
1950 if ((r = start_unit_one(bus, method, *name, mode, &error, s)) != 0) {
1951 ret = translate_bus_error_to_exit_status(r, &error);
1952 dbus_error_free(&error);
1957 if ((r = wait_for_jobs(bus, s)) < 0) {
1966 dbus_error_free(&error);
1971 /* Ask systemd-logind, which might grant access to unprivileged users
1972 * through PolicyKit */
1973 static int reboot_with_logind(DBusConnection *bus, enum action a) {
1976 DBusMessage *m = NULL, *reply = NULL;
1978 dbus_bool_t interactive = true;
1981 dbus_error_init(&error);
1983 polkit_agent_open_if_enabled();
1991 case ACTION_POWEROFF:
1992 method = "PowerOff";
1995 case ACTION_SUSPEND:
1999 case ACTION_HIBERNATE:
2000 method = "Hibernate";
2007 m = dbus_message_new_method_call(
2008 "org.freedesktop.login1",
2009 "/org/freedesktop/login1",
2010 "org.freedesktop.login1.Manager",
2013 log_error("Could not allocate message.");
2018 if (!dbus_message_append_args(m,
2019 DBUS_TYPE_BOOLEAN, &interactive,
2020 DBUS_TYPE_INVALID)) {
2021 log_error("Could not append arguments to message.");
2026 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
2028 if (error_is_no_service(&error)) {
2029 log_debug("Failed to issue method call: %s", bus_error_message(&error));
2034 if (dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2035 log_debug("Failed to issue method call: %s", bus_error_message(&error));
2040 log_info("Failed to issue method call: %s", bus_error_message(&error));
2049 dbus_message_unref(m);
2052 dbus_message_unref(reply);
2054 dbus_error_free(&error);
2062 static int start_special(DBusConnection *bus, char **args) {
2068 a = verb_to_action(args[0]);
2070 if (arg_force >= 2 && geteuid() != 0) {
2071 log_error("Must be root.");
2075 if (arg_force >= 2 &&
2076 (a == ACTION_HALT ||
2077 a == ACTION_POWEROFF ||
2078 a == ACTION_REBOOT))
2081 if (arg_force >= 1 &&
2082 (a == ACTION_HALT ||
2083 a == ACTION_POWEROFF ||
2084 a == ACTION_REBOOT ||
2085 a == ACTION_KEXEC ||
2087 return daemon_reload(bus, args);
2089 /* first try logind, to allow authentication with polkit */
2090 if (geteuid() != 0 &&
2091 (a == ACTION_POWEROFF ||
2092 a == ACTION_REBOOT ||
2093 a == ACTION_SUSPEND ||
2094 a == ACTION_HIBERNATE)) {
2095 r = reboot_with_logind(bus, a);
2100 r = start_unit(bus, args);
2107 static int check_unit(DBusConnection *bus, char **args) {
2109 int r = 3; /* According to LSB: "program is not running" */
2114 STRV_FOREACH(name, args+1) {
2115 int state = check_one_unit(bus, *name, arg_quiet);
2125 static int kill_unit(DBusConnection *bus, char **args) {
2126 DBusMessage *m = NULL;
2134 dbus_error_init(&error);
2137 arg_kill_who = "all";
2139 STRV_FOREACH(name, args+1) {
2144 m = dbus_message_new_method_call(
2145 "org.freedesktop.systemd1",
2146 "/org/freedesktop/systemd1",
2147 "org.freedesktop.systemd1.Manager",
2150 log_error("Could not allocate message.");
2155 n = unit_name_mangle(*name);
2156 b = dbus_message_append_args(m,
2157 DBUS_TYPE_STRING, n ? &n : name,
2158 DBUS_TYPE_STRING, &arg_kill_who,
2159 DBUS_TYPE_INT32, &arg_signal,
2163 log_error("Could not append arguments to message.");
2168 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
2170 log_error("Failed to issue method call: %s", bus_error_message(&error));
2171 dbus_error_free(&error);
2175 dbus_message_unref(m);
2178 dbus_message_unref(reply);
2184 dbus_message_unref(m);
2186 dbus_error_free(&error);
2191 typedef struct ExecStatusInfo {
2199 usec_t start_timestamp;
2200 usec_t exit_timestamp;
2205 LIST_FIELDS(struct ExecStatusInfo, exec);
2208 static void exec_status_info_free(ExecStatusInfo *i) {
2217 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
2218 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
2219 DBusMessageIter sub2, sub3;
2223 int32_t code, status;
2229 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
2232 dbus_message_iter_recurse(sub, &sub2);
2234 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
2237 if (!(i->path = strdup(path)))
2240 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
2241 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
2245 dbus_message_iter_recurse(&sub2, &sub3);
2246 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
2247 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
2248 dbus_message_iter_next(&sub3);
2253 if (!(i->argv = new0(char*, n+1)))
2257 dbus_message_iter_recurse(&sub2, &sub3);
2258 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
2261 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
2262 dbus_message_iter_get_basic(&sub3, &s);
2263 dbus_message_iter_next(&sub3);
2265 if (!(i->argv[n++] = strdup(s)))
2269 if (!dbus_message_iter_next(&sub2) ||
2270 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
2271 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
2272 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
2273 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
2274 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
2275 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
2276 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
2277 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
2281 i->start_timestamp = (usec_t) start_timestamp;
2282 i->exit_timestamp = (usec_t) exit_timestamp;
2283 i->pid = (pid_t) pid;
2290 typedef struct UnitStatusInfo {
2292 const char *load_state;
2293 const char *active_state;
2294 const char *sub_state;
2295 const char *unit_file_state;
2297 const char *description;
2298 const char *following;
2300 char **documentation;
2302 const char *fragment_path;
2303 const char *source_path;
2304 const char *default_control_group;
2306 const char *load_error;
2309 usec_t inactive_exit_timestamp;
2310 usec_t inactive_exit_timestamp_monotonic;
2311 usec_t active_enter_timestamp;
2312 usec_t active_exit_timestamp;
2313 usec_t inactive_enter_timestamp;
2315 bool need_daemon_reload;
2320 const char *status_text;
2323 usec_t start_timestamp;
2324 usec_t exit_timestamp;
2326 int exit_code, exit_status;
2328 usec_t condition_timestamp;
2329 bool condition_result;
2332 unsigned n_accepted;
2333 unsigned n_connections;
2337 const char *sysfs_path;
2339 /* Mount, Automount */
2345 LIST_HEAD(ExecStatusInfo, exec);
2348 static void print_status_info(UnitStatusInfo *i) {
2350 const char *on, *off, *ss;
2352 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
2353 char since2[FORMAT_TIMESTAMP_MAX], *s2;
2358 /* This shows pretty information about a unit. See
2359 * print_property() for a low-level property printer */
2361 printf("%s", strna(i->id));
2363 if (i->description && !streq_ptr(i->id, i->description))
2364 printf(" - %s", i->description);
2369 printf("\t Follow: unit currently follows state of %s\n", i->following);
2371 if (streq_ptr(i->load_state, "error")) {
2372 on = ansi_highlight_red(true);
2373 off = ansi_highlight_red(false);
2377 path = i->source_path ? i->source_path : i->fragment_path;
2380 printf("\t Loaded: %s%s%s (Reason: %s)\n", on, strna(i->load_state), off, i->load_error);
2381 else if (path && i->unit_file_state)
2382 printf("\t Loaded: %s%s%s (%s; %s)\n", on, strna(i->load_state), off, path, i->unit_file_state);
2384 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, path);
2386 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
2388 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
2390 if (streq_ptr(i->active_state, "failed")) {
2391 on = ansi_highlight_red(true);
2392 off = ansi_highlight_red(false);
2393 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
2394 on = ansi_highlight_green(true);
2395 off = ansi_highlight_green(false);
2400 printf("\t Active: %s%s (%s)%s",
2402 strna(i->active_state),
2406 printf("\t Active: %s%s%s",
2408 strna(i->active_state),
2411 if (!isempty(i->result) && !streq(i->result, "success"))
2412 printf(" (Result: %s)", i->result);
2414 timestamp = (streq_ptr(i->active_state, "active") ||
2415 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
2416 (streq_ptr(i->active_state, "inactive") ||
2417 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
2418 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
2419 i->active_exit_timestamp;
2421 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
2422 s2 = format_timestamp(since2, sizeof(since2), timestamp);
2425 printf(" since %s; %s\n", s2, s1);
2427 printf(" since %s\n", s2);
2431 if (!i->condition_result && i->condition_timestamp > 0) {
2432 s1 = format_timestamp_pretty(since1, sizeof(since1), i->condition_timestamp);
2433 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
2436 printf("\t start condition failed at %s; %s\n", s2, s1);
2438 printf("\t start condition failed at %s\n", s2);
2442 printf("\t Device: %s\n", i->sysfs_path);
2444 printf("\t Where: %s\n", i->where);
2446 printf("\t What: %s\n", i->what);
2448 if (!strv_isempty(i->documentation)) {
2452 STRV_FOREACH(t, i->documentation) {
2454 printf("\t Docs: %s\n", *t);
2457 printf("\t %s\n", *t);
2462 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
2464 LIST_FOREACH(exec, p, i->exec) {
2468 /* Only show exited processes here */
2472 t = strv_join(p->argv, " ");
2473 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
2476 good = is_clean_exit_lsb(p->code, p->status);
2478 on = ansi_highlight_red(true);
2479 off = ansi_highlight_red(false);
2483 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
2485 if (p->code == CLD_EXITED) {
2488 printf("status=%i", p->status);
2490 c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD);
2495 printf("signal=%s", signal_to_string(p->status));
2497 printf(")%s\n", off);
2499 if (i->main_pid == p->pid &&
2500 i->start_timestamp == p->start_timestamp &&
2501 i->exit_timestamp == p->start_timestamp)
2502 /* Let's not show this twice */
2505 if (p->pid == i->control_pid)
2509 if (i->main_pid > 0 || i->control_pid > 0) {
2512 if (i->main_pid > 0) {
2513 printf("Main PID: %u", (unsigned) i->main_pid);
2517 get_process_comm(i->main_pid, &t);
2522 } else if (i->exit_code > 0) {
2523 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2525 if (i->exit_code == CLD_EXITED) {
2528 printf("status=%i", i->exit_status);
2530 c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD);
2535 printf("signal=%s", signal_to_string(i->exit_status));
2540 if (i->main_pid > 0 && i->control_pid > 0)
2543 if (i->control_pid > 0) {
2546 printf(" Control: %u", (unsigned) i->control_pid);
2548 get_process_comm(i->control_pid, &t);
2559 printf("\t Status: \"%s\"\n", i->status_text);
2561 if (i->default_control_group) {
2564 printf("\t CGroup: %s\n", i->default_control_group);
2566 if (arg_transport != TRANSPORT_SSH) {
2576 if (i->main_pid > 0)
2577 extra[k++] = i->main_pid;
2579 if (i->control_pid > 0)
2580 extra[k++] = i->control_pid;
2582 show_cgroup_and_extra_by_spec(i->default_control_group, "\t\t ", c, false, arg_all, extra, k);
2586 if (i->id && arg_transport != TRANSPORT_SSH) {
2587 int flags = (arg_lines*OUTPUT_SHOW_ALL |
2588 arg_follow*OUTPUT_FOLLOW |
2589 !arg_quiet*OUTPUT_WARN_CUTOFF);
2591 show_journal_by_unit(i->id, arg_output, 0,
2592 i->inactive_exit_timestamp_monotonic,
2596 if (i->need_daemon_reload)
2597 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2598 ansi_highlight_red(true),
2599 ansi_highlight_red(false),
2600 arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
2603 static void show_unit_help(UnitStatusInfo *i) {
2608 if (!i->documentation) {
2609 log_info("Documentation for %s not known.", i->id);
2613 STRV_FOREACH(p, i->documentation) {
2615 if (startswith(*p, "man:")) {
2618 char *page = NULL, *section = NULL;
2619 const char *args[4] = { "man", NULL, NULL, NULL };
2624 if ((*p)[k-1] == ')')
2625 e = strrchr(*p, '(');
2628 page = strndup((*p) + 4, e - *p - 4);
2634 section = strndup(e + 1, *p + k - e - 2);
2648 log_error("Failed to fork: %m");
2656 execvp(args[0], (char**) args);
2657 log_error("Failed to execute man: %m");
2658 _exit(EXIT_FAILURE);
2664 wait_for_terminate(pid, NULL);
2666 log_info("Can't show: %s", *p);
2670 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2676 switch (dbus_message_iter_get_arg_type(iter)) {
2678 case DBUS_TYPE_STRING: {
2681 dbus_message_iter_get_basic(iter, &s);
2684 if (streq(name, "Id"))
2686 else if (streq(name, "LoadState"))
2688 else if (streq(name, "ActiveState"))
2689 i->active_state = s;
2690 else if (streq(name, "SubState"))
2692 else if (streq(name, "Description"))
2694 else if (streq(name, "FragmentPath"))
2695 i->fragment_path = s;
2696 else if (streq(name, "SourcePath"))
2698 else if (streq(name, "DefaultControlGroup"))
2699 i->default_control_group = s;
2700 else if (streq(name, "StatusText"))
2702 else if (streq(name, "SysFSPath"))
2704 else if (streq(name, "Where"))
2706 else if (streq(name, "What"))
2708 else if (streq(name, "Following"))
2710 else if (streq(name, "UnitFileState"))
2711 i->unit_file_state = s;
2712 else if (streq(name, "Result"))
2719 case DBUS_TYPE_BOOLEAN: {
2722 dbus_message_iter_get_basic(iter, &b);
2724 if (streq(name, "Accept"))
2726 else if (streq(name, "NeedDaemonReload"))
2727 i->need_daemon_reload = b;
2728 else if (streq(name, "ConditionResult"))
2729 i->condition_result = b;
2734 case DBUS_TYPE_UINT32: {
2737 dbus_message_iter_get_basic(iter, &u);
2739 if (streq(name, "MainPID")) {
2741 i->main_pid = (pid_t) u;
2744 } else if (streq(name, "ControlPID"))
2745 i->control_pid = (pid_t) u;
2746 else if (streq(name, "ExecMainPID")) {
2748 i->main_pid = (pid_t) u;
2749 } else if (streq(name, "NAccepted"))
2751 else if (streq(name, "NConnections"))
2752 i->n_connections = u;
2757 case DBUS_TYPE_INT32: {
2760 dbus_message_iter_get_basic(iter, &j);
2762 if (streq(name, "ExecMainCode"))
2763 i->exit_code = (int) j;
2764 else if (streq(name, "ExecMainStatus"))
2765 i->exit_status = (int) j;
2770 case DBUS_TYPE_UINT64: {
2773 dbus_message_iter_get_basic(iter, &u);
2775 if (streq(name, "ExecMainStartTimestamp"))
2776 i->start_timestamp = (usec_t) u;
2777 else if (streq(name, "ExecMainExitTimestamp"))
2778 i->exit_timestamp = (usec_t) u;
2779 else if (streq(name, "ActiveEnterTimestamp"))
2780 i->active_enter_timestamp = (usec_t) u;
2781 else if (streq(name, "InactiveEnterTimestamp"))
2782 i->inactive_enter_timestamp = (usec_t) u;
2783 else if (streq(name, "InactiveExitTimestamp"))
2784 i->inactive_exit_timestamp = (usec_t) u;
2785 else if (streq(name, "InactiveExitTimestampMonotonic"))
2786 i->inactive_exit_timestamp_monotonic = (usec_t) u;
2787 else if (streq(name, "ActiveExitTimestamp"))
2788 i->active_exit_timestamp = (usec_t) u;
2789 else if (streq(name, "ConditionTimestamp"))
2790 i->condition_timestamp = (usec_t) u;
2795 case DBUS_TYPE_ARRAY: {
2797 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2798 startswith(name, "Exec")) {
2799 DBusMessageIter sub;
2801 dbus_message_iter_recurse(iter, &sub);
2802 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2803 ExecStatusInfo *info;
2806 if (!(info = new0(ExecStatusInfo, 1)))
2809 if (!(info->name = strdup(name))) {
2814 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2819 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2821 dbus_message_iter_next(&sub);
2823 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING &&
2824 streq(name, "Documentation")) {
2826 DBusMessageIter sub;
2828 dbus_message_iter_recurse(iter, &sub);
2829 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING) {
2833 dbus_message_iter_get_basic(&sub, &s);
2835 l = strv_append(i->documentation, s);
2839 strv_free(i->documentation);
2840 i->documentation = l;
2842 dbus_message_iter_next(&sub);
2849 case DBUS_TYPE_STRUCT: {
2851 if (streq(name, "LoadError")) {
2852 DBusMessageIter sub;
2853 const char *n, *message;
2856 dbus_message_iter_recurse(iter, &sub);
2858 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &n, true);
2862 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &message, false);
2866 if (!isempty(message))
2867 i->load_error = message;
2877 static int print_property(const char *name, DBusMessageIter *iter) {
2881 /* This is a low-level property printer, see
2882 * print_status_info() for the nicer output */
2884 if (arg_property && !strv_find(arg_property, name))
2887 switch (dbus_message_iter_get_arg_type(iter)) {
2889 case DBUS_TYPE_STRUCT: {
2890 DBusMessageIter sub;
2891 dbus_message_iter_recurse(iter, &sub);
2893 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2896 dbus_message_iter_get_basic(&sub, &u);
2899 printf("%s=%u\n", name, (unsigned) u);
2901 printf("%s=\n", name);
2904 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2907 dbus_message_iter_get_basic(&sub, &s);
2909 if (arg_all || s[0])
2910 printf("%s=%s\n", name, s);
2913 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "LoadError")) {
2914 const char *a = NULL, *b = NULL;
2916 if (bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &a, true) >= 0)
2917 bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &b, false);
2919 if (arg_all || !isempty(a) || !isempty(b))
2920 printf("%s=%s \"%s\"\n", name, strempty(a), strempty(b));
2928 case DBUS_TYPE_ARRAY:
2930 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
2931 DBusMessageIter sub, sub2;
2933 dbus_message_iter_recurse(iter, &sub);
2934 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2938 dbus_message_iter_recurse(&sub, &sub2);
2940 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
2941 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
2942 printf("EnvironmentFile=%s (ignore_errors=%s)\n", path, yes_no(ignore));
2944 dbus_message_iter_next(&sub);
2949 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2950 DBusMessageIter sub, sub2;
2952 dbus_message_iter_recurse(iter, &sub);
2953 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2954 const char *type, *path;
2956 dbus_message_iter_recurse(&sub, &sub2);
2958 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2959 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2960 printf("%s=%s\n", type, path);
2962 dbus_message_iter_next(&sub);
2967 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2968 DBusMessageIter sub, sub2;
2970 dbus_message_iter_recurse(iter, &sub);
2971 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2973 uint64_t value, next_elapse;
2975 dbus_message_iter_recurse(&sub, &sub2);
2977 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2978 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2979 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2980 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2982 printf("%s={ value=%s ; next_elapse=%s }\n",
2984 format_timespan(timespan1, sizeof(timespan1), value),
2985 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2988 dbus_message_iter_next(&sub);
2993 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "ControlGroupAttributes")) {
2994 DBusMessageIter sub, sub2;
2996 dbus_message_iter_recurse(iter, &sub);
2997 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2998 const char *controller, *attr, *value;
3000 dbus_message_iter_recurse(&sub, &sub2);
3002 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &controller, true) >= 0 &&
3003 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &attr, true) >= 0 &&
3004 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &value, false) >= 0) {
3006 printf("ControlGroupAttribute={ controller=%s ; attribute=%s ; value=\"%s\" }\n",
3012 dbus_message_iter_next(&sub);
3017 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
3018 DBusMessageIter sub;
3020 dbus_message_iter_recurse(iter, &sub);
3021 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3022 ExecStatusInfo info;
3025 if (exec_status_info_deserialize(&sub, &info) >= 0) {
3026 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
3029 t = strv_join(info.argv, " ");
3031 printf("%s={ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
3035 yes_no(info.ignore),
3036 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
3037 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
3038 (unsigned) info. pid,
3039 sigchld_code_to_string(info.code),
3041 info.code == CLD_EXITED ? "" : "/",
3042 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
3048 strv_free(info.argv);
3050 dbus_message_iter_next(&sub);
3059 if (generic_print_property(name, iter, arg_all) > 0)
3063 printf("%s=[unprintable]\n", name);
3068 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
3069 DBusMessage *m = NULL, *reply = NULL;
3070 const char *interface = "";
3073 DBusMessageIter iter, sub, sub2, sub3;
3074 UnitStatusInfo info;
3082 dbus_error_init(&error);
3084 if (!(m = dbus_message_new_method_call(
3085 "org.freedesktop.systemd1",
3087 "org.freedesktop.DBus.Properties",
3089 log_error("Could not allocate message.");
3094 if (!dbus_message_append_args(m,
3095 DBUS_TYPE_STRING, &interface,
3096 DBUS_TYPE_INVALID)) {
3097 log_error("Could not append arguments to message.");
3102 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3103 log_error("Failed to issue method call: %s", bus_error_message(&error));
3108 if (!dbus_message_iter_init(reply, &iter) ||
3109 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
3110 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
3111 log_error("Failed to parse reply.");
3116 dbus_message_iter_recurse(&iter, &sub);
3123 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
3126 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
3127 log_error("Failed to parse reply.");
3132 dbus_message_iter_recurse(&sub, &sub2);
3134 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
3135 log_error("Failed to parse reply.");
3140 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
3141 log_error("Failed to parse reply.");
3146 dbus_message_iter_recurse(&sub2, &sub3);
3148 if (show_properties)
3149 r = print_property(name, &sub3);
3151 r = status_property(name, &sub3, &info);
3154 log_error("Failed to parse reply.");
3159 dbus_message_iter_next(&sub);
3164 if (!show_properties) {
3165 if (streq(verb, "help"))
3166 show_unit_help(&info);
3168 print_status_info(&info);
3171 strv_free(info.documentation);
3173 if (!streq_ptr(info.active_state, "active") &&
3174 !streq_ptr(info.active_state, "reloading") &&
3175 streq(verb, "status"))
3176 /* According to LSB: "program not running" */
3179 while ((p = info.exec)) {
3180 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
3181 exec_status_info_free(p);
3186 dbus_message_unref(m);
3189 dbus_message_unref(reply);
3191 dbus_error_free(&error);
3196 static int show_one_by_pid(const char *verb, DBusConnection *bus, uint32_t pid, bool *new_line) {
3197 DBusMessage *m = NULL, *reply = NULL;
3198 const char *path = NULL;
3202 dbus_error_init(&error);
3204 m = dbus_message_new_method_call(
3205 "org.freedesktop.systemd1",
3206 "/org/freedesktop/systemd1",
3207 "org.freedesktop.systemd1.Manager",
3210 log_error("Could not allocate message.");
3215 if (!dbus_message_append_args(m,
3216 DBUS_TYPE_UINT32, &pid,
3217 DBUS_TYPE_INVALID)) {
3218 log_error("Could not append arguments to message.");
3223 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3225 log_error("Failed to issue method call: %s", bus_error_message(&error));
3230 if (!dbus_message_get_args(reply, &error,
3231 DBUS_TYPE_OBJECT_PATH, &path,
3232 DBUS_TYPE_INVALID)) {
3233 log_error("Failed to parse reply: %s", bus_error_message(&error));
3238 r = show_one(verb, bus, path, false, new_line);
3242 dbus_message_unref(m);
3245 dbus_message_unref(reply);
3247 dbus_error_free(&error);
3252 static int show(DBusConnection *bus, char **args) {
3254 bool show_properties, new_line = false;
3260 show_properties = streq(args[0], "show");
3262 if (show_properties)
3263 pager_open_if_enabled();
3265 if (show_properties && strv_length(args) <= 1) {
3266 /* If not argument is specified inspect the manager
3269 return show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
3272 STRV_FOREACH(name, args+1) {
3275 if (safe_atou32(*name, &id) < 0) {
3277 /* Interpret as unit name */
3279 n = unit_name_mangle(*name);
3280 p = unit_dbus_path_from_name(n ? n : *name);
3285 r = show_one(args[0], bus, p, show_properties, &new_line);
3291 } else if (show_properties) {
3293 /* Interpret as job id */
3296 if (asprintf(&p, "/org/freedesktop/systemd1/job/%u", id) < 0)
3299 r = show_one(args[0], bus, p, show_properties, &new_line);
3307 /* Interpret as PID */
3309 r = show_one_by_pid(args[0], bus, id, &new_line);
3318 static int dump(DBusConnection *bus, char **args) {
3319 DBusMessage *m = NULL, *reply = NULL;
3324 dbus_error_init(&error);
3326 pager_open_if_enabled();
3328 if (!(m = dbus_message_new_method_call(
3329 "org.freedesktop.systemd1",
3330 "/org/freedesktop/systemd1",
3331 "org.freedesktop.systemd1.Manager",
3333 log_error("Could not allocate message.");
3337 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3338 log_error("Failed to issue method call: %s", bus_error_message(&error));
3343 if (!dbus_message_get_args(reply, &error,
3344 DBUS_TYPE_STRING, &text,
3345 DBUS_TYPE_INVALID)) {
3346 log_error("Failed to parse reply: %s", bus_error_message(&error));
3351 fputs(text, stdout);
3357 dbus_message_unref(m);
3360 dbus_message_unref(reply);
3362 dbus_error_free(&error);
3367 static int snapshot(DBusConnection *bus, char **args) {
3368 DBusMessage *m = NULL, *reply = NULL;
3371 const char *name = "", *path, *id;
3372 dbus_bool_t cleanup = FALSE;
3373 DBusMessageIter iter, sub;
3375 *interface = "org.freedesktop.systemd1.Unit",
3380 dbus_error_init(&error);
3382 m = dbus_message_new_method_call(
3383 "org.freedesktop.systemd1",
3384 "/org/freedesktop/systemd1",
3385 "org.freedesktop.systemd1.Manager",
3388 log_error("Could not allocate message.");
3392 if (strv_length(args) > 1)
3395 n = unit_name_mangle(name);
3396 b = dbus_message_append_args(m,
3397 DBUS_TYPE_STRING, n ? (const char**) &n : &name,
3398 DBUS_TYPE_BOOLEAN, &cleanup,
3402 log_error("Could not append arguments to message.");
3407 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3409 log_error("Failed to issue method call: %s", bus_error_message(&error));
3414 if (!dbus_message_get_args(reply, &error,
3415 DBUS_TYPE_OBJECT_PATH, &path,
3416 DBUS_TYPE_INVALID)) {
3417 log_error("Failed to parse reply: %s", bus_error_message(&error));
3422 dbus_message_unref(m);
3423 m = dbus_message_new_method_call(
3424 "org.freedesktop.systemd1",
3426 "org.freedesktop.DBus.Properties",
3429 log_error("Could not allocate message.");
3433 if (!dbus_message_append_args(m,
3434 DBUS_TYPE_STRING, &interface,
3435 DBUS_TYPE_STRING, &property,
3436 DBUS_TYPE_INVALID)) {
3437 log_error("Could not append arguments to message.");
3442 dbus_message_unref(reply);
3443 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3445 log_error("Failed to issue method call: %s", bus_error_message(&error));
3450 if (!dbus_message_iter_init(reply, &iter) ||
3451 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3452 log_error("Failed to parse reply.");
3457 dbus_message_iter_recurse(&iter, &sub);
3459 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3460 log_error("Failed to parse reply.");
3465 dbus_message_iter_get_basic(&sub, &id);
3473 dbus_message_unref(m);
3476 dbus_message_unref(reply);
3478 dbus_error_free(&error);
3483 static int delete_snapshot(DBusConnection *bus, char **args) {
3484 DBusMessage *m = NULL, *reply = NULL;
3492 dbus_error_init(&error);
3494 STRV_FOREACH(name, args+1) {
3495 const char *path = NULL;
3499 m = dbus_message_new_method_call(
3500 "org.freedesktop.systemd1",
3501 "/org/freedesktop/systemd1",
3502 "org.freedesktop.systemd1.Manager",
3505 log_error("Could not allocate message.");
3510 n = unit_name_mangle(*name);
3511 b = dbus_message_append_args(m,
3512 DBUS_TYPE_STRING, n ? &n : name,
3516 log_error("Could not append arguments to message.");
3521 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3523 log_error("Failed to issue method call: %s", bus_error_message(&error));
3528 if (!dbus_message_get_args(reply, &error,
3529 DBUS_TYPE_OBJECT_PATH, &path,
3530 DBUS_TYPE_INVALID)) {
3531 log_error("Failed to parse reply: %s", bus_error_message(&error));
3536 dbus_message_unref(m);
3537 m = dbus_message_new_method_call(
3538 "org.freedesktop.systemd1",
3540 "org.freedesktop.systemd1.Snapshot",
3543 log_error("Could not allocate message.");
3548 dbus_message_unref(reply);
3549 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3551 log_error("Failed to issue method call: %s", bus_error_message(&error));
3556 dbus_message_unref(m);
3557 dbus_message_unref(reply);
3565 dbus_message_unref(m);
3568 dbus_message_unref(reply);
3570 dbus_error_free(&error);
3575 static int daemon_reload(DBusConnection *bus, char **args) {
3576 DBusMessage *m = NULL, *reply = NULL;
3581 dbus_error_init(&error);
3583 if (arg_action == ACTION_RELOAD)
3585 else if (arg_action == ACTION_REEXEC)
3586 method = "Reexecute";
3588 assert(arg_action == ACTION_SYSTEMCTL);
3591 streq(args[0], "clear-jobs") ||
3592 streq(args[0], "cancel") ? "ClearJobs" :
3593 streq(args[0], "daemon-reexec") ? "Reexecute" :
3594 streq(args[0], "reset-failed") ? "ResetFailed" :
3595 streq(args[0], "halt") ? "Halt" :
3596 streq(args[0], "poweroff") ? "PowerOff" :
3597 streq(args[0], "reboot") ? "Reboot" :
3598 streq(args[0], "kexec") ? "KExec" :
3599 streq(args[0], "exit") ? "Exit" :
3600 /* "daemon-reload" */ "Reload";
3603 if (!(m = dbus_message_new_method_call(
3604 "org.freedesktop.systemd1",
3605 "/org/freedesktop/systemd1",
3606 "org.freedesktop.systemd1.Manager",
3608 log_error("Could not allocate message.");
3612 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3614 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3615 /* There's always a fallback possible for
3616 * legacy actions. */
3621 if (streq(method, "Reexecute") && dbus_error_has_name(&error, DBUS_ERROR_NO_REPLY)) {
3622 /* On reexecution, we expect a disconnect, not
3628 log_error("Failed to issue method call: %s", bus_error_message(&error));
3637 dbus_message_unref(m);
3640 dbus_message_unref(reply);
3642 dbus_error_free(&error);
3647 static int reset_failed(DBusConnection *bus, char **args) {
3648 DBusMessage *m = NULL;
3654 dbus_error_init(&error);
3656 if (strv_length(args) <= 1)
3657 return daemon_reload(bus, args);
3659 STRV_FOREACH(name, args+1) {
3664 m = dbus_message_new_method_call(
3665 "org.freedesktop.systemd1",
3666 "/org/freedesktop/systemd1",
3667 "org.freedesktop.systemd1.Manager",
3670 log_error("Could not allocate message.");
3675 n = unit_name_mangle(*name);
3676 b = dbus_message_append_args(m,
3677 DBUS_TYPE_STRING, n ? &n : name,
3681 log_error("Could not append arguments to message.");
3686 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3688 log_error("Failed to issue method call: %s", bus_error_message(&error));
3693 dbus_message_unref(m);
3694 dbus_message_unref(reply);
3702 dbus_message_unref(m);
3704 dbus_error_free(&error);
3709 static int show_enviroment(DBusConnection *bus, char **args) {
3710 DBusMessage *m = NULL, *reply = NULL;
3712 DBusMessageIter iter, sub, sub2;
3715 *interface = "org.freedesktop.systemd1.Manager",
3716 *property = "Environment";
3718 dbus_error_init(&error);
3720 pager_open_if_enabled();
3722 if (!(m = dbus_message_new_method_call(
3723 "org.freedesktop.systemd1",
3724 "/org/freedesktop/systemd1",
3725 "org.freedesktop.DBus.Properties",
3727 log_error("Could not allocate message.");
3731 if (!dbus_message_append_args(m,
3732 DBUS_TYPE_STRING, &interface,
3733 DBUS_TYPE_STRING, &property,
3734 DBUS_TYPE_INVALID)) {
3735 log_error("Could not append arguments to message.");
3740 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3741 log_error("Failed to issue method call: %s", bus_error_message(&error));
3746 if (!dbus_message_iter_init(reply, &iter) ||
3747 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3748 log_error("Failed to parse reply.");
3753 dbus_message_iter_recurse(&iter, &sub);
3755 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3756 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3757 log_error("Failed to parse reply.");
3762 dbus_message_iter_recurse(&sub, &sub2);
3764 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3767 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3768 log_error("Failed to parse reply.");
3773 dbus_message_iter_get_basic(&sub2, &text);
3774 printf("%s\n", text);
3776 dbus_message_iter_next(&sub2);
3783 dbus_message_unref(m);
3786 dbus_message_unref(reply);
3788 dbus_error_free(&error);
3793 static int switch_root(DBusConnection *bus, char **args) {
3794 DBusMessage *m = NULL, *reply = NULL;
3796 const char *root, *init;
3800 dbus_error_init(&error);
3802 l = strv_length(args);
3803 if (l < 2 || l > 3) {
3804 log_error("Wrong number of arguments.");
3809 init = l >= 3 ? args[2] : "";
3811 m = dbus_message_new_method_call(
3812 "org.freedesktop.systemd1",
3813 "/org/freedesktop/systemd1",
3814 "org.freedesktop.systemd1.Manager",
3817 log_error("Could not allocate message.");
3821 if (!dbus_message_append_args(
3823 DBUS_TYPE_STRING, &root,
3824 DBUS_TYPE_STRING, &init,
3825 DBUS_TYPE_INVALID)) {
3826 log_error("Could not append arguments to message.");
3831 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3833 log_error("Failed to issue method call: %s", bus_error_message(&error));
3842 dbus_message_unref(m);
3845 dbus_message_unref(reply);
3847 dbus_error_free(&error);
3852 static int set_environment(DBusConnection *bus, char **args) {
3853 DBusMessage *m = NULL, *reply = NULL;
3857 DBusMessageIter iter, sub;
3860 dbus_error_init(&error);
3862 method = streq(args[0], "set-environment")
3864 : "UnsetEnvironment";
3866 if (!(m = dbus_message_new_method_call(
3867 "org.freedesktop.systemd1",
3868 "/org/freedesktop/systemd1",
3869 "org.freedesktop.systemd1.Manager",
3872 log_error("Could not allocate message.");
3876 dbus_message_iter_init_append(m, &iter);
3878 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3879 log_error("Could not append arguments to message.");
3884 STRV_FOREACH(name, args+1)
3885 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, name)) {
3886 log_error("Could not append arguments to message.");
3891 if (!dbus_message_iter_close_container(&iter, &sub)) {
3892 log_error("Could not append arguments to message.");
3897 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3898 log_error("Failed to issue method call: %s", bus_error_message(&error));
3907 dbus_message_unref(m);
3910 dbus_message_unref(reply);
3912 dbus_error_free(&error);
3917 static int enable_sysv_units(char **args) {
3920 #if defined (HAVE_SYSV_COMPAT) && (defined(TARGET_FEDORA) || defined(TARGET_MANDRIVA) || defined(TARGET_SUSE) || defined(TARGET_ALTLINUX) || defined(TARGET_MAGEIA))
3921 const char *verb = args[0];
3922 unsigned f = 1, t = 1;
3925 if (arg_scope != UNIT_FILE_SYSTEM)
3928 if (!streq(verb, "enable") &&
3929 !streq(verb, "disable") &&
3930 !streq(verb, "is-enabled"))
3933 /* Processes all SysV units, and reshuffles the array so that
3934 * afterwards only the native units remain */
3937 r = lookup_paths_init(&paths, MANAGER_SYSTEM, false, NULL, NULL, NULL);
3942 for (f = 1; args[f]; f++) {
3945 bool found_native = false, found_sysv;
3947 const char *argv[6] = { "/sbin/chkconfig", NULL, NULL, NULL, NULL };
3948 char **k, *l, *q = NULL;
3955 if (!endswith(name, ".service"))
3958 if (path_is_absolute(name))
3961 STRV_FOREACH(k, paths.unit_path) {
3964 if (!isempty(arg_root))
3965 asprintf(&p, "%s/%s/%s", arg_root, *k, name);
3967 asprintf(&p, "%s/%s", *k, name);
3974 found_native = access(p, F_OK) >= 0;
3985 if (!isempty(arg_root))
3986 asprintf(&p, "%s/" SYSTEM_SYSVINIT_PATH "/%s", arg_root, name);
3988 asprintf(&p, SYSTEM_SYSVINIT_PATH "/%s", name);
3994 p[strlen(p) - sizeof(".service") + 1] = 0;
3995 found_sysv = access(p, F_OK) >= 0;
4002 /* Mark this entry, so that we don't try enabling it as native unit */
4003 args[f] = (char*) "";
4005 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", name);
4007 if (!isempty(arg_root))
4008 argv[c++] = q = strappend("--root=", arg_root);
4010 argv[c++] = path_get_file_name(p);
4012 streq(verb, "enable") ? "on" :
4013 streq(verb, "disable") ? "off" : "--level=5";
4016 l = strv_join((char**)argv, " ");
4024 log_info("Executing %s", l);
4029 log_error("Failed to fork: %m");
4034 } else if (pid == 0) {
4037 execv(argv[0], (char**) argv);
4038 _exit(EXIT_FAILURE);
4044 j = wait_for_terminate(pid, &status);
4046 log_error("Failed to wait for child: %s", strerror(-r));
4051 if (status.si_code == CLD_EXITED) {
4052 if (streq(verb, "is-enabled")) {
4053 if (status.si_status == 0) {
4062 } else if (status.si_status != 0) {
4073 lookup_paths_free(&paths);
4075 /* Drop all SysV units */
4076 for (f = 1, t = 1; args[f]; f++) {
4078 if (isempty(args[f]))
4081 args[t++] = args[f];
4090 static int enable_unit(DBusConnection *bus, char **args) {
4091 const char *verb = args[0];
4092 UnitFileChange *changes = NULL;
4093 unsigned n_changes = 0, i;
4094 int carries_install_info = -1;
4095 DBusMessage *m = NULL, *reply = NULL;
4099 r = enable_sysv_units(args);
4106 dbus_error_init(&error);
4108 if (!bus || avoid_bus()) {
4109 if (streq(verb, "enable")) {
4110 r = unit_file_enable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4111 carries_install_info = r;
4112 } else if (streq(verb, "disable"))
4113 r = unit_file_disable(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
4114 else if (streq(verb, "reenable")) {
4115 r = unit_file_reenable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4116 carries_install_info = r;
4117 } else if (streq(verb, "link"))
4118 r = unit_file_link(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4119 else if (streq(verb, "preset")) {
4120 r = unit_file_preset(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4121 carries_install_info = r;
4122 } else if (streq(verb, "mask"))
4123 r = unit_file_mask(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4124 else if (streq(verb, "unmask"))
4125 r = unit_file_unmask(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
4127 assert_not_reached("Unknown verb");
4130 log_error("Operation failed: %s", strerror(-r));
4135 for (i = 0; i < n_changes; i++) {
4136 if (changes[i].type == UNIT_FILE_SYMLINK)
4137 log_info("ln -s '%s' '%s'", changes[i].source, changes[i].path);
4139 log_info("rm '%s'", changes[i].path);
4145 bool send_force = true, expect_carries_install_info = false;
4147 DBusMessageIter iter, sub, sub2;
4149 if (streq(verb, "enable")) {
4150 method = "EnableUnitFiles";
4151 expect_carries_install_info = true;
4152 } else if (streq(verb, "disable")) {
4153 method = "DisableUnitFiles";
4155 } else if (streq(verb, "reenable")) {
4156 method = "ReenableUnitFiles";
4157 expect_carries_install_info = true;
4158 } else if (streq(verb, "link"))
4159 method = "LinkUnitFiles";
4160 else if (streq(verb, "preset")) {
4161 method = "PresetUnitFiles";
4162 expect_carries_install_info = true;
4163 } else if (streq(verb, "mask"))
4164 method = "MaskUnitFiles";
4165 else if (streq(verb, "unmask")) {
4166 method = "UnmaskUnitFiles";
4169 assert_not_reached("Unknown verb");
4171 m = dbus_message_new_method_call(
4172 "org.freedesktop.systemd1",
4173 "/org/freedesktop/systemd1",
4174 "org.freedesktop.systemd1.Manager",
4181 dbus_message_iter_init_append(m, &iter);
4183 r = bus_append_strv_iter(&iter, args+1);
4185 log_error("Failed to append unit files.");
4190 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &a)) {
4191 log_error("Failed to append runtime boolean.");
4199 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b)) {
4200 log_error("Failed to append force boolean.");
4206 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
4208 log_error("Failed to issue method call: %s", bus_error_message(&error));
4213 if (!dbus_message_iter_init(reply, &iter)) {
4214 log_error("Failed to initialize iterator.");
4218 if (expect_carries_install_info) {
4219 r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_BOOLEAN, &b, true);
4221 log_error("Failed to parse reply.");
4225 carries_install_info = b;
4228 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
4229 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
4230 log_error("Failed to parse reply.");
4235 dbus_message_iter_recurse(&iter, &sub);
4236 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
4237 const char *type, *path, *source;
4239 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
4240 log_error("Failed to parse reply.");
4245 dbus_message_iter_recurse(&sub, &sub2);
4247 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
4248 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0 ||
4249 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &source, false) < 0) {
4250 log_error("Failed to parse reply.");
4256 if (streq(type, "symlink"))
4257 log_info("ln -s '%s' '%s'", source, path);
4259 log_info("rm '%s'", path);
4262 dbus_message_iter_next(&sub);
4265 /* Try to reload if enabeld */
4267 r = daemon_reload(bus, args);
4270 if (carries_install_info == 0)
4271 log_warning("The unit files have no [Install] section. They are not meant to be enabled using systemctl.");
4275 dbus_message_unref(m);
4278 dbus_message_unref(reply);
4280 unit_file_changes_free(changes, n_changes);
4282 dbus_error_free(&error);
4286 static int unit_is_enabled(DBusConnection *bus, char **args) {
4289 DBusMessage *m = NULL, *reply = NULL;
4293 dbus_error_init(&error);
4295 r = enable_sysv_units(args);
4301 if (!bus || avoid_bus()) {
4303 STRV_FOREACH(name, args+1) {
4304 UnitFileState state;
4306 state = unit_file_get_state(arg_scope, arg_root, *name);
4312 if (state == UNIT_FILE_ENABLED ||
4313 state == UNIT_FILE_ENABLED_RUNTIME ||
4314 state == UNIT_FILE_STATIC)
4318 puts(unit_file_state_to_string(state));
4322 STRV_FOREACH(name, args+1) {
4325 m = dbus_message_new_method_call(
4326 "org.freedesktop.systemd1",
4327 "/org/freedesktop/systemd1",
4328 "org.freedesktop.systemd1.Manager",
4329 "GetUnitFileState");
4335 if (!dbus_message_append_args(m,
4336 DBUS_TYPE_STRING, name,
4337 DBUS_TYPE_INVALID)) {
4338 log_error("Could not append arguments to message.");
4343 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
4345 log_error("Failed to issue method call: %s", bus_error_message(&error));
4350 if (!dbus_message_get_args(reply, &error,
4351 DBUS_TYPE_STRING, &s,
4352 DBUS_TYPE_INVALID)) {
4353 log_error("Failed to parse reply: %s", bus_error_message(&error));
4358 dbus_message_unref(m);
4359 dbus_message_unref(reply);
4362 if (streq(s, "enabled") ||
4363 streq(s, "enabled-runtime") ||
4372 r = enabled ? 0 : 1;
4376 dbus_message_unref(m);
4379 dbus_message_unref(reply);
4381 dbus_error_free(&error);
4385 static int systemctl_help(void) {
4387 pager_open_if_enabled();
4389 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4390 "Query or send control commands to the systemd manager.\n\n"
4391 " -h --help Show this help\n"
4392 " --version Show package version\n"
4393 " -t --type=TYPE List only units of a particular type\n"
4394 " -p --property=NAME Show only properties by this name\n"
4395 " -a --all Show all units/properties, including dead/empty ones\n"
4396 " --failed Show only failed units\n"
4397 " --full Don't ellipsize unit names on output\n"
4398 " --fail When queueing a new job, fail if conflicting jobs are\n"
4400 " --ignore-dependencies\n"
4401 " When queueing a new job, ignore all its dependencies\n"
4402 " --kill-who=WHO Who to send signal to\n"
4403 " -s --signal=SIGNAL Which signal to send\n"
4404 " -H --host=[USER@]HOST\n"
4405 " Show information for remote host\n"
4406 " -P --privileged Acquire privileges before execution\n"
4407 " -q --quiet Suppress output\n"
4408 " --no-block Do not wait until operation finished\n"
4409 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4410 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4412 " --no-legend Do not print a legend (column headers and hints)\n"
4413 " --no-pager Do not pipe output into a pager\n"
4414 " --no-ask-password\n"
4415 " Do not ask for system passwords\n"
4416 " --order When generating graph for dot, show only order\n"
4417 " --require When generating graph for dot, show only requirement\n"
4418 " --system Connect to system manager\n"
4419 " --user Connect to user service manager\n"
4420 " --global Enable/disable unit files globally\n"
4421 " -f --force When enabling unit files, override existing symlinks\n"
4422 " When shutting down, execute action immediately\n"
4423 " --root=PATH Enable unit files in the specified root directory\n"
4424 " --runtime Enable unit files only temporarily until next reboot\n"
4425 " -n --lines=INTEGER Journal entries to show\n"
4426 " --follow Follow journal\n"
4427 " -o --output=STRING Change journal output mode (short, short-monotonic,\n"
4428 " verbose, export, json, cat)\n\n"
4430 " list-units List loaded units\n"
4431 " start [NAME...] Start (activate) one or more units\n"
4432 " stop [NAME...] Stop (deactivate) one or more units\n"
4433 " reload [NAME...] Reload one or more units\n"
4434 " restart [NAME...] Start or restart one or more units\n"
4435 " try-restart [NAME...] Restart one or more units if active\n"
4436 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4437 " otherwise start or restart\n"
4438 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4439 " otherwise restart if active\n"
4440 " isolate [NAME] Start one unit and stop all others\n"
4441 " kill [NAME...] Send signal to processes of a unit\n"
4442 " is-active [NAME...] Check whether units are active\n"
4443 " status [NAME...|PID...] Show runtime status of one or more units\n"
4444 " show [NAME...|JOB...] Show properties of one or more\n"
4445 " units/jobs or the manager\n"
4446 " help [NAME...|PID...] Show manual for one or more units\n"
4447 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4449 " load [NAME...] Load one or more units\n\n"
4450 "Unit File Commands:\n"
4451 " list-unit-files List installed unit files\n"
4452 " enable [NAME...] Enable one or more unit files\n"
4453 " disable [NAME...] Disable one or more unit files\n"
4454 " reenable [NAME...] Reenable one or more unit files\n"
4455 " preset [NAME...] Enable/disable one or more unit files\n"
4456 " based on preset configuration\n"
4457 " mask [NAME...] Mask one or more units\n"
4458 " unmask [NAME...] Unmask one or more units\n"
4459 " link [PATH...] Link one or more units files into\n"
4460 " the search path\n"
4461 " is-enabled [NAME...] Check whether unit files are enabled\n\n"
4463 " list-jobs List jobs\n"
4464 " cancel [JOB...] Cancel all, one, or more jobs\n\n"
4465 "Status Commands:\n"
4466 " dump Dump server status\n"
4467 " dot Dump dependency graph for dot(1)\n\n"
4468 "Snapshot Commands:\n"
4469 " snapshot [NAME] Create a snapshot\n"
4470 " delete [NAME...] Remove one or more snapshots\n\n"
4471 "Environment Commands:\n"
4472 " show-environment Dump environment\n"
4473 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4474 " unset-environment [NAME...] Unset one or more environment variables\n\n"
4475 "Manager Lifecycle Commands:\n"
4476 " daemon-reload Reload systemd manager configuration\n"
4477 " daemon-reexec Reexecute systemd manager\n\n"
4478 "System Commands:\n"
4479 " default Enter system default mode\n"
4480 " rescue Enter system rescue mode\n"
4481 " emergency Enter system emergency mode\n"
4482 " halt Shut down and halt the system\n"
4483 " poweroff Shut down and power-off the system\n"
4484 " reboot Shut down and reboot the system\n"
4485 " kexec Shut down and reboot the system with kexec\n"
4486 " exit Request user instance exit\n"
4487 " switch-root [ROOT] [INIT] Change to a different root file system\n"
4488 " suspend Suspend the system\n"
4489 " hibernate Hibernate the system\n",
4490 program_invocation_short_name);
4495 static int halt_help(void) {
4497 printf("%s [OPTIONS...]\n\n"
4498 "%s the system.\n\n"
4499 " --help Show this help\n"
4500 " --halt Halt the machine\n"
4501 " -p --poweroff Switch off the machine\n"
4502 " --reboot Reboot the machine\n"
4503 " -f --force Force immediate halt/power-off/reboot\n"
4504 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4505 " -d --no-wtmp Don't write wtmp record\n"
4506 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4507 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4508 program_invocation_short_name,
4509 arg_action == ACTION_REBOOT ? "Reboot" :
4510 arg_action == ACTION_POWEROFF ? "Power off" :
4516 static int shutdown_help(void) {
4518 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4519 "Shut down the system.\n\n"
4520 " --help Show this help\n"
4521 " -H --halt Halt the machine\n"
4522 " -P --poweroff Power-off the machine\n"
4523 " -r --reboot Reboot the machine\n"
4524 " -h Equivalent to --poweroff, overridden by --halt\n"
4525 " -k Don't halt/power-off/reboot, just send warnings\n"
4526 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4527 " -c Cancel a pending shutdown\n",
4528 program_invocation_short_name);
4533 static int telinit_help(void) {
4535 printf("%s [OPTIONS...] {COMMAND}\n\n"
4536 "Send control commands to the init daemon.\n\n"
4537 " --help Show this help\n"
4538 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4540 " 0 Power-off the machine\n"
4541 " 6 Reboot the machine\n"
4542 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4543 " 1, s, S Enter rescue mode\n"
4544 " q, Q Reload init daemon configuration\n"
4545 " u, U Reexecute init daemon\n",
4546 program_invocation_short_name);
4551 static int runlevel_help(void) {
4553 printf("%s [OPTIONS...]\n\n"
4554 "Prints the previous and current runlevel of the init system.\n\n"
4555 " --help Show this help\n",
4556 program_invocation_short_name);
4561 static int systemctl_parse_argv(int argc, char *argv[]) {
4565 ARG_IGNORE_DEPENDENCIES,
4580 ARG_NO_ASK_PASSWORD,
4587 static const struct option options[] = {
4588 { "help", no_argument, NULL, 'h' },
4589 { "version", no_argument, NULL, ARG_VERSION },
4590 { "type", required_argument, NULL, 't' },
4591 { "property", required_argument, NULL, 'p' },
4592 { "all", no_argument, NULL, 'a' },
4593 { "failed", no_argument, NULL, ARG_FAILED },
4594 { "full", no_argument, NULL, ARG_FULL },
4595 { "fail", no_argument, NULL, ARG_FAIL },
4596 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4597 { "user", no_argument, NULL, ARG_USER },
4598 { "system", no_argument, NULL, ARG_SYSTEM },
4599 { "global", no_argument, NULL, ARG_GLOBAL },
4600 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4601 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
4602 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4603 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4604 { "quiet", no_argument, NULL, 'q' },
4605 { "order", no_argument, NULL, ARG_ORDER },
4606 { "require", no_argument, NULL, ARG_REQUIRE },
4607 { "root", required_argument, NULL, ARG_ROOT },
4608 { "force", no_argument, NULL, ARG_FORCE },
4609 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4610 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4611 { "signal", required_argument, NULL, 's' },
4612 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4613 { "host", required_argument, NULL, 'H' },
4614 { "privileged",no_argument, NULL, 'P' },
4615 { "runtime", no_argument, NULL, ARG_RUNTIME },
4616 { "lines", required_argument, NULL, 'n' },
4617 { "follow", no_argument, NULL, ARG_FOLLOW },
4618 { "output", required_argument, NULL, 'o' },
4619 { NULL, 0, NULL, 0 }
4627 while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:Pn:o:", options, NULL)) >= 0) {
4636 puts(PACKAGE_STRING);
4638 puts(SYSTEMD_FEATURES);
4642 if (unit_type_from_string(optarg) >= 0) {
4646 if (unit_load_state_from_string(optarg) >= 0) {
4647 arg_load_state = optarg;
4650 log_error("Unkown unit type or load state '%s'.",
4656 if (!(l = strv_append(arg_property, optarg)))
4659 strv_free(arg_property);
4662 /* If the user asked for a particular
4663 * property, show it to him, even if it is
4674 arg_job_mode = "fail";
4677 case ARG_IGNORE_DEPENDENCIES:
4678 arg_job_mode = "ignore-dependencies";
4682 arg_scope = UNIT_FILE_USER;
4686 arg_scope = UNIT_FILE_SYSTEM;
4690 arg_scope = UNIT_FILE_GLOBAL;
4694 arg_no_block = true;
4698 arg_no_legend = true;
4702 arg_no_pager = true;
4710 arg_dot = DOT_ORDER;
4714 arg_dot = DOT_REQUIRE;
4742 /* -f is short for both --follow and --force! */
4748 arg_no_reload = true;
4752 arg_kill_who = optarg;
4756 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4757 log_error("Failed to parse signal string %s.", optarg);
4762 case ARG_NO_ASK_PASSWORD:
4763 arg_ask_password = false;
4767 arg_transport = TRANSPORT_POLKIT;
4771 arg_transport = TRANSPORT_SSH;
4780 if (safe_atou(optarg, &arg_lines) < 0) {
4781 log_error("Failed to parse lines '%s'", optarg);
4787 arg_output = output_mode_from_string(optarg);
4788 if (arg_output < 0) {
4789 log_error("Unknown output '%s'.", optarg);
4798 log_error("Unknown option code '%c'.", c);
4803 if (arg_transport != TRANSPORT_NORMAL && arg_scope != UNIT_FILE_SYSTEM) {
4804 log_error("Cannot access user instance remotely.");
4811 static int halt_parse_argv(int argc, char *argv[]) {
4820 static const struct option options[] = {
4821 { "help", no_argument, NULL, ARG_HELP },
4822 { "halt", no_argument, NULL, ARG_HALT },
4823 { "poweroff", no_argument, NULL, 'p' },
4824 { "reboot", no_argument, NULL, ARG_REBOOT },
4825 { "force", no_argument, NULL, 'f' },
4826 { "wtmp-only", no_argument, NULL, 'w' },
4827 { "no-wtmp", no_argument, NULL, 'd' },
4828 { "no-sync", no_argument, NULL, 'n' },
4829 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4830 { NULL, 0, NULL, 0 }
4838 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4839 if (runlevel == '0' || runlevel == '6')
4842 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4850 arg_action = ACTION_HALT;
4854 if (arg_action != ACTION_REBOOT)
4855 arg_action = ACTION_POWEROFF;
4859 arg_action = ACTION_REBOOT;
4884 /* Compatibility nops */
4891 log_error("Unknown option code '%c'.", c);
4896 if (optind < argc) {
4897 log_error("Too many arguments.");
4904 static int parse_time_spec(const char *t, usec_t *_u) {
4908 if (streq(t, "now"))
4910 else if (!strchr(t, ':')) {
4913 if (safe_atou64(t, &u) < 0)
4916 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4925 hour = strtol(t, &e, 10);
4926 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4929 minute = strtol(e+1, &e, 10);
4930 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4933 n = now(CLOCK_REALTIME);
4934 s = (time_t) (n / USEC_PER_SEC);
4937 assert_se(localtime_r(&s, &tm));
4939 tm.tm_hour = (int) hour;
4940 tm.tm_min = (int) minute;
4943 assert_se(s = mktime(&tm));
4945 *_u = (usec_t) s * USEC_PER_SEC;
4948 *_u += USEC_PER_DAY;
4954 static int shutdown_parse_argv(int argc, char *argv[]) {
4961 static const struct option options[] = {
4962 { "help", no_argument, NULL, ARG_HELP },
4963 { "halt", no_argument, NULL, 'H' },
4964 { "poweroff", no_argument, NULL, 'P' },
4965 { "reboot", no_argument, NULL, 'r' },
4966 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
4967 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4968 { NULL, 0, NULL, 0 }
4976 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4984 arg_action = ACTION_HALT;
4988 arg_action = ACTION_POWEROFF;
4993 arg_action = ACTION_KEXEC;
4995 arg_action = ACTION_REBOOT;
4999 arg_action = ACTION_KEXEC;
5003 if (arg_action != ACTION_HALT)
5004 arg_action = ACTION_POWEROFF;
5017 /* Compatibility nops */
5021 arg_action = ACTION_CANCEL_SHUTDOWN;
5028 log_error("Unknown option code '%c'.", c);
5033 if (argc > optind) {
5034 r = parse_time_spec(argv[optind], &arg_when);
5036 log_error("Failed to parse time specification: %s", argv[optind]);
5040 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
5042 /* We skip the time argument */
5043 if (argc > optind + 1)
5044 arg_wall = argv + optind + 1;
5051 static int telinit_parse_argv(int argc, char *argv[]) {
5058 static const struct option options[] = {
5059 { "help", no_argument, NULL, ARG_HELP },
5060 { "no-wall", no_argument, NULL, ARG_NO_WALL },
5061 { NULL, 0, NULL, 0 }
5064 static const struct {
5068 { '0', ACTION_POWEROFF },
5069 { '6', ACTION_REBOOT },
5070 { '1', ACTION_RESCUE },
5071 { '2', ACTION_RUNLEVEL2 },
5072 { '3', ACTION_RUNLEVEL3 },
5073 { '4', ACTION_RUNLEVEL4 },
5074 { '5', ACTION_RUNLEVEL5 },
5075 { 's', ACTION_RESCUE },
5076 { 'S', ACTION_RESCUE },
5077 { 'q', ACTION_RELOAD },
5078 { 'Q', ACTION_RELOAD },
5079 { 'u', ACTION_REEXEC },
5080 { 'U', ACTION_REEXEC }
5089 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5104 log_error("Unknown option code '%c'.", c);
5109 if (optind >= argc) {
5114 if (optind + 1 < argc) {
5115 log_error("Too many arguments.");
5119 if (strlen(argv[optind]) != 1) {
5120 log_error("Expected single character argument.");
5124 for (i = 0; i < ELEMENTSOF(table); i++)
5125 if (table[i].from == argv[optind][0])
5128 if (i >= ELEMENTSOF(table)) {
5129 log_error("Unknown command '%s'.", argv[optind]);
5133 arg_action = table[i].to;
5140 static int runlevel_parse_argv(int argc, char *argv[]) {
5146 static const struct option options[] = {
5147 { "help", no_argument, NULL, ARG_HELP },
5148 { NULL, 0, NULL, 0 }
5156 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5167 log_error("Unknown option code '%c'.", c);
5172 if (optind < argc) {
5173 log_error("Too many arguments.");
5180 static int parse_argv(int argc, char *argv[]) {
5184 if (program_invocation_short_name) {
5186 if (strstr(program_invocation_short_name, "halt")) {
5187 arg_action = ACTION_HALT;
5188 return halt_parse_argv(argc, argv);
5189 } else if (strstr(program_invocation_short_name, "poweroff")) {
5190 arg_action = ACTION_POWEROFF;
5191 return halt_parse_argv(argc, argv);
5192 } else if (strstr(program_invocation_short_name, "reboot")) {
5194 arg_action = ACTION_KEXEC;
5196 arg_action = ACTION_REBOOT;
5197 return halt_parse_argv(argc, argv);
5198 } else if (strstr(program_invocation_short_name, "shutdown")) {
5199 arg_action = ACTION_POWEROFF;
5200 return shutdown_parse_argv(argc, argv);
5201 } else if (strstr(program_invocation_short_name, "init")) {
5203 if (sd_booted() > 0) {
5204 arg_action = ACTION_INVALID;
5205 return telinit_parse_argv(argc, argv);
5207 /* Hmm, so some other init system is
5208 * running, we need to forward this
5209 * request to it. For now we simply
5210 * guess that it is Upstart. */
5212 execv("/lib/upstart/telinit", argv);
5214 log_error("Couldn't find an alternative telinit implementation to spawn.");
5218 } else if (strstr(program_invocation_short_name, "runlevel")) {
5219 arg_action = ACTION_RUNLEVEL;
5220 return runlevel_parse_argv(argc, argv);
5224 arg_action = ACTION_SYSTEMCTL;
5225 return systemctl_parse_argv(argc, argv);
5228 static int action_to_runlevel(void) {
5230 static const char table[_ACTION_MAX] = {
5231 [ACTION_HALT] = '0',
5232 [ACTION_POWEROFF] = '0',
5233 [ACTION_REBOOT] = '6',
5234 [ACTION_RUNLEVEL2] = '2',
5235 [ACTION_RUNLEVEL3] = '3',
5236 [ACTION_RUNLEVEL4] = '4',
5237 [ACTION_RUNLEVEL5] = '5',
5238 [ACTION_RESCUE] = '1'
5241 assert(arg_action < _ACTION_MAX);
5243 return table[arg_action];
5246 static int talk_upstart(void) {
5247 DBusMessage *m = NULL, *reply = NULL;
5249 int previous, rl, r;
5251 env1_buf[] = "RUNLEVEL=X",
5252 env2_buf[] = "PREVLEVEL=X";
5253 char *env1 = env1_buf, *env2 = env2_buf;
5254 const char *emit = "runlevel";
5255 dbus_bool_t b_false = FALSE;
5256 DBusMessageIter iter, sub;
5257 DBusConnection *bus;
5259 dbus_error_init(&error);
5261 if (!(rl = action_to_runlevel()))
5264 if (utmp_get_runlevel(&previous, NULL) < 0)
5267 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
5268 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
5273 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
5278 if ((r = bus_check_peercred(bus)) < 0) {
5279 log_error("Failed to verify owner of bus.");
5283 if (!(m = dbus_message_new_method_call(
5284 "com.ubuntu.Upstart",
5285 "/com/ubuntu/Upstart",
5286 "com.ubuntu.Upstart0_6",
5289 log_error("Could not allocate message.");
5294 dbus_message_iter_init_append(m, &iter);
5296 env1_buf[sizeof(env1_buf)-2] = rl;
5297 env2_buf[sizeof(env2_buf)-2] = previous;
5299 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5300 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5301 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5302 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5303 !dbus_message_iter_close_container(&iter, &sub) ||
5304 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5305 log_error("Could not append arguments to message.");
5310 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5312 if (error_is_no_service(&error)) {
5317 log_error("Failed to issue method call: %s", bus_error_message(&error));
5326 dbus_message_unref(m);
5329 dbus_message_unref(reply);
5332 dbus_connection_flush(bus);
5333 dbus_connection_close(bus);
5334 dbus_connection_unref(bus);
5337 dbus_error_free(&error);
5342 static int talk_initctl(void) {
5343 struct init_request request;
5347 if (!(rl = action_to_runlevel()))
5351 request.magic = INIT_MAGIC;
5352 request.sleeptime = 0;
5353 request.cmd = INIT_CMD_RUNLVL;
5354 request.runlevel = rl;
5356 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5358 if (errno == ENOENT)
5361 log_error("Failed to open "INIT_FIFO": %m");
5366 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5367 close_nointr_nofail(fd);
5370 log_error("Failed to write to "INIT_FIFO": %m");
5371 return errno ? -errno : -EIO;
5377 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5379 static const struct {
5387 int (* const dispatch)(DBusConnection *bus, char **args);
5389 { "list-units", LESS, 1, list_units },
5390 { "list-unit-files", EQUAL, 1, list_unit_files },
5391 { "list-jobs", EQUAL, 1, list_jobs },
5392 { "clear-jobs", EQUAL, 1, daemon_reload },
5393 { "load", MORE, 2, load_unit },
5394 { "cancel", MORE, 2, cancel_job },
5395 { "start", MORE, 2, start_unit },
5396 { "stop", MORE, 2, start_unit },
5397 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5398 { "reload", MORE, 2, start_unit },
5399 { "restart", MORE, 2, start_unit },
5400 { "try-restart", MORE, 2, start_unit },
5401 { "reload-or-restart", MORE, 2, start_unit },
5402 { "reload-or-try-restart", MORE, 2, start_unit },
5403 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5404 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5405 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5406 { "isolate", EQUAL, 2, start_unit },
5407 { "kill", MORE, 2, kill_unit },
5408 { "is-active", MORE, 2, check_unit },
5409 { "check", MORE, 2, check_unit },
5410 { "show", MORE, 1, show },
5411 { "status", MORE, 2, show },
5412 { "help", MORE, 2, show },
5413 { "dump", EQUAL, 1, dump },
5414 { "dot", EQUAL, 1, dot },
5415 { "snapshot", LESS, 2, snapshot },
5416 { "delete", MORE, 2, delete_snapshot },
5417 { "daemon-reload", EQUAL, 1, daemon_reload },
5418 { "daemon-reexec", EQUAL, 1, daemon_reload },
5419 { "show-environment", EQUAL, 1, show_enviroment },
5420 { "set-environment", MORE, 2, set_environment },
5421 { "unset-environment", MORE, 2, set_environment },
5422 { "halt", EQUAL, 1, start_special },
5423 { "poweroff", EQUAL, 1, start_special },
5424 { "reboot", EQUAL, 1, start_special },
5425 { "kexec", EQUAL, 1, start_special },
5426 { "suspend", EQUAL, 1, start_special },
5427 { "hibernate", EQUAL, 1, start_special },
5428 { "default", EQUAL, 1, start_special },
5429 { "rescue", EQUAL, 1, start_special },
5430 { "emergency", EQUAL, 1, start_special },
5431 { "exit", EQUAL, 1, start_special },
5432 { "reset-failed", MORE, 1, reset_failed },
5433 { "enable", MORE, 2, enable_unit },
5434 { "disable", MORE, 2, enable_unit },
5435 { "is-enabled", MORE, 2, unit_is_enabled },
5436 { "reenable", MORE, 2, enable_unit },
5437 { "preset", MORE, 2, enable_unit },
5438 { "mask", MORE, 2, enable_unit },
5439 { "unmask", MORE, 2, enable_unit },
5440 { "link", MORE, 2, enable_unit },
5441 { "switch-root", MORE, 2, switch_root },
5451 left = argc - optind;
5454 /* Special rule: no arguments means "list-units" */
5457 if (streq(argv[optind], "help") && !argv[optind+1]) {
5458 log_error("This command expects one or more "
5459 "unit names. Did you mean --help?");
5463 for (i = 0; i < ELEMENTSOF(verbs); i++)
5464 if (streq(argv[optind], verbs[i].verb))
5467 if (i >= ELEMENTSOF(verbs)) {
5468 log_error("Unknown operation '%s'.", argv[optind]);
5473 switch (verbs[i].argc_cmp) {
5476 if (left != verbs[i].argc) {
5477 log_error("Invalid number of arguments.");
5484 if (left < verbs[i].argc) {
5485 log_error("Too few arguments.");
5492 if (left > verbs[i].argc) {
5493 log_error("Too many arguments.");
5500 assert_not_reached("Unknown comparison operator.");
5503 /* Require a bus connection for all operations but
5505 if (!streq(verbs[i].verb, "enable") &&
5506 !streq(verbs[i].verb, "disable") &&
5507 !streq(verbs[i].verb, "is-enabled") &&
5508 !streq(verbs[i].verb, "list-unit-files") &&
5509 !streq(verbs[i].verb, "reenable") &&
5510 !streq(verbs[i].verb, "preset") &&
5511 !streq(verbs[i].verb, "mask") &&
5512 !streq(verbs[i].verb, "unmask") &&
5513 !streq(verbs[i].verb, "link")) {
5515 if (running_in_chroot() > 0) {
5516 log_info("Running in chroot, ignoring request.");
5520 if (((!streq(verbs[i].verb, "reboot") &&
5521 !streq(verbs[i].verb, "halt") &&
5522 !streq(verbs[i].verb, "poweroff")) || arg_force <= 0) && !bus) {
5523 log_error("Failed to get D-Bus connection: %s",
5524 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5530 if (!bus && !avoid_bus()) {
5531 log_error("Failed to get D-Bus connection: %s",
5532 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5537 return verbs[i].dispatch(bus, argv + optind);
5540 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
5542 struct msghdr msghdr;
5543 struct iovec iovec[2];
5544 union sockaddr_union sockaddr;
5545 struct sd_shutdown_command c;
5547 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
5554 c.dry_run = dry_run;
5558 sockaddr.sa.sa_family = AF_UNIX;
5559 strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5562 msghdr.msg_name = &sockaddr;
5563 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5566 iovec[0].iov_base = (char*) &c;
5567 iovec[0].iov_len = offsetof(struct sd_shutdown_command, wall_message);
5569 if (isempty(message))
5570 msghdr.msg_iovlen = 1;
5572 iovec[1].iov_base = (char*) message;
5573 iovec[1].iov_len = strlen(message);
5574 msghdr.msg_iovlen = 2;
5576 msghdr.msg_iov = iovec;
5578 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5579 close_nointr_nofail(fd);
5583 close_nointr_nofail(fd);
5587 static int reload_with_fallback(DBusConnection *bus) {
5590 /* First, try systemd via D-Bus. */
5591 if (daemon_reload(bus, NULL) >= 0)
5595 /* Nothing else worked, so let's try signals */
5596 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5598 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5599 log_error("kill() failed: %m");
5606 static int start_with_fallback(DBusConnection *bus) {
5609 /* First, try systemd via D-Bus. */
5610 if (start_unit(bus, NULL) >= 0)
5614 /* Hmm, talking to systemd via D-Bus didn't work. Then
5615 * let's try to talk to Upstart via D-Bus. */
5616 if (talk_upstart() > 0)
5619 /* Nothing else worked, so let's try
5621 if (talk_initctl() > 0)
5624 log_error("Failed to talk to init daemon.");
5628 warn_wall(arg_action);
5632 static _noreturn_ void halt_now(enum action a) {
5634 /* Make sure C-A-D is handled by the kernel from this
5636 reboot(RB_ENABLE_CAD);
5641 log_info("Halting.");
5642 reboot(RB_HALT_SYSTEM);
5645 case ACTION_POWEROFF:
5646 log_info("Powering off.");
5647 reboot(RB_POWER_OFF);
5651 log_info("Rebooting.");
5652 reboot(RB_AUTOBOOT);
5656 assert_not_reached("Unknown halt action.");
5659 assert_not_reached("Uh? This shouldn't happen.");
5662 static int halt_main(DBusConnection *bus) {
5665 if (geteuid() != 0) {
5666 /* Try logind if we are a normal user and no special
5667 * mode applies. Maybe PolicyKit allows us to shutdown
5670 if (arg_when <= 0 &&
5673 (arg_action == ACTION_POWEROFF ||
5674 arg_action == ACTION_REBOOT)) {
5675 r = reboot_with_logind(bus, arg_action);
5680 log_error("Must be root.");
5687 m = strv_join(arg_wall, " ");
5688 r = send_shutdownd(arg_when,
5689 arg_action == ACTION_HALT ? 'H' :
5690 arg_action == ACTION_POWEROFF ? 'P' :
5691 arg_action == ACTION_KEXEC ? 'K' :
5699 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5701 char date[FORMAT_TIMESTAMP_MAX];
5703 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5704 format_timestamp(date, sizeof(date), arg_when));
5709 if (!arg_dry && !arg_force)
5710 return start_with_fallback(bus);
5713 if (sd_booted() > 0)
5714 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5716 r = utmp_put_shutdown();
5718 log_warning("Failed to write utmp record: %s", strerror(-r));
5728 halt_now(arg_action);
5729 /* We should never reach this. */
5733 static int runlevel_main(void) {
5734 int r, runlevel, previous;
5736 r = utmp_get_runlevel(&runlevel, &previous);
5743 previous <= 0 ? 'N' : previous,
5744 runlevel <= 0 ? 'N' : runlevel);
5749 int main(int argc, char*argv[]) {
5750 int r, retval = EXIT_FAILURE;
5751 DBusConnection *bus = NULL;
5754 dbus_error_init(&error);
5756 log_parse_environment();
5759 r = parse_argv(argc, argv);
5763 retval = EXIT_SUCCESS;
5767 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5768 * let's shortcut this */
5769 if (arg_action == ACTION_RUNLEVEL) {
5770 r = runlevel_main();
5771 retval = r < 0 ? EXIT_FAILURE : r;
5775 if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5776 log_info("Running in chroot, ignoring request.");
5782 if (arg_transport == TRANSPORT_NORMAL)
5783 bus_connect(arg_scope == UNIT_FILE_SYSTEM ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, &bus, &private_bus, &error);
5784 else if (arg_transport == TRANSPORT_POLKIT) {
5785 bus_connect_system_polkit(&bus, &error);
5786 private_bus = false;
5787 } else if (arg_transport == TRANSPORT_SSH) {
5788 bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5789 private_bus = false;
5791 assert_not_reached("Uh, invalid transport...");
5794 switch (arg_action) {
5796 case ACTION_SYSTEMCTL:
5797 r = systemctl_main(bus, argc, argv, &error);
5801 case ACTION_POWEROFF:
5807 case ACTION_RUNLEVEL2:
5808 case ACTION_RUNLEVEL3:
5809 case ACTION_RUNLEVEL4:
5810 case ACTION_RUNLEVEL5:
5812 case ACTION_EMERGENCY:
5813 case ACTION_DEFAULT:
5814 r = start_with_fallback(bus);
5819 r = reload_with_fallback(bus);
5822 case ACTION_CANCEL_SHUTDOWN:
5823 r = send_shutdownd(0, 0, false, false, NULL);
5826 case ACTION_INVALID:
5827 case ACTION_RUNLEVEL:
5829 assert_not_reached("Unknown action");
5832 retval = r < 0 ? EXIT_FAILURE : r;
5836 dbus_connection_flush(bus);
5837 dbus_connection_close(bus);
5838 dbus_connection_unref(bus);
5841 dbus_error_free(&error);
5845 strv_free(arg_property);
5848 ask_password_agent_close();
5849 polkit_agent_close();