1 /* SPDX-License-Identifier: LGPL-2.1+ */
10 #include <sys/prctl.h>
11 #include <sys/reboot.h>
15 #include "sd-daemon.h"
19 #include "alloc-util.h"
21 #include "bus-common-errors.h"
22 #include "bus-error.h"
23 #include "bus-message.h"
24 #include "bus-unit-procs.h"
25 #include "bus-unit-util.h"
27 #include "bus-wait-for-jobs.h"
28 #include "bus-wait-for-units.h"
29 #include "cgroup-show.h"
30 #include "cgroup-util.h"
32 #include "cpu-set-util.h"
33 #include "dirent-util.h"
35 #include "efi-loader.h"
39 #include "exec-util.h"
40 #include "exit-status.h"
42 #include "format-table.h"
43 #include "format-util.h"
45 #include "glob-util.h"
46 #include "hexdecoct.h"
47 #include "hostname-util.h"
48 #include "in-addr-util.h"
52 #include "journal-util.h"
54 #include "locale-util.h"
56 #include "logs-show.h"
58 #include "main-func.h"
59 #include "memory-util.h"
61 #include "numa-util.h"
63 #include "parse-util.h"
64 #include "path-lookup.h"
65 #include "path-util.h"
66 #include "pretty-print.h"
67 #include "proc-cmdline.h"
68 #include "process-util.h"
69 #include "reboot-util.h"
70 #include "rlimit-util.h"
73 #include "signal-util.h"
74 #include "socket-util.h"
75 #include "sort-util.h"
76 #include "spawn-ask-password-agent.h"
77 #include "spawn-polkit-agent.h"
79 #include "stat-util.h"
80 #include "string-table.h"
82 #include "sysv-compat.h"
83 #include "terminal-util.h"
84 #include "tmpfile-util.h"
86 #include "unit-file.h"
87 #include "unit-name.h"
88 #include "user-util.h"
90 #include "utmp-wtmp.h"
94 static char **arg_types
= NULL
;
95 static char **arg_states
= NULL
;
96 static char **arg_properties
= NULL
;
97 static bool arg_all
= false;
98 static enum dependency
{
104 } arg_dependency
= DEPENDENCY_FORWARD
;
105 static const char *arg_job_mode
= "replace";
106 static UnitFileScope arg_scope
= UNIT_FILE_SYSTEM
;
107 static bool arg_wait
= false;
108 static bool arg_no_block
= false;
109 static bool arg_no_legend
= false;
110 static PagerFlags arg_pager_flags
= 0;
111 static bool arg_no_wtmp
= false;
112 static bool arg_no_sync
= false;
113 static bool arg_no_wall
= false;
114 static bool arg_no_reload
= false;
115 static bool arg_value
= false;
116 static bool arg_show_types
= false;
117 static bool arg_ignore_inhibitors
= false;
118 static bool arg_dry_run
= false;
119 static bool arg_quiet
= false;
120 static bool arg_full
= false;
121 static bool arg_recursive
= false;
122 static bool arg_with_dependencies
= false;
123 static bool arg_show_transaction
= false;
124 static int arg_force
= 0;
125 static bool arg_ask_password
= false;
126 static bool arg_runtime
= false;
127 static UnitFilePresetMode arg_preset_mode
= UNIT_FILE_PRESET_FULL
;
128 static char **arg_wall
= NULL
;
129 static const char *arg_kill_who
= NULL
;
130 static int arg_signal
= SIGTERM
;
131 static char *arg_root
= NULL
;
132 static usec_t arg_when
= 0;
143 ACTION_SUSPEND_THEN_HIBERNATE
,
154 ACTION_CANCEL_SHUTDOWN
,
157 } arg_action
= ACTION_SYSTEMCTL
;
158 static BusTransport arg_transport
= BUS_TRANSPORT_LOCAL
;
159 static const char *arg_host
= NULL
;
160 static unsigned arg_lines
= 10;
161 static OutputMode arg_output
= OUTPUT_SHORT
;
162 static bool arg_plain
= false;
163 static bool arg_firmware_setup
= false;
164 static usec_t arg_boot_loader_menu
= USEC_INFINITY
;
165 static const char *arg_boot_loader_entry
= NULL
;
166 static bool arg_now
= false;
167 static bool arg_jobs_before
= false;
168 static bool arg_jobs_after
= false;
169 static char **arg_clean_what
= NULL
;
171 /* This is a global cache that will be constructed on first use. */
172 static Hashmap
*cached_id_map
= NULL
;
173 static Hashmap
*cached_name_map
= NULL
;
175 STATIC_DESTRUCTOR_REGISTER(arg_wall
, strv_freep
);
176 STATIC_DESTRUCTOR_REGISTER(arg_root
, freep
);
177 STATIC_DESTRUCTOR_REGISTER(arg_types
, strv_freep
);
178 STATIC_DESTRUCTOR_REGISTER(arg_states
, strv_freep
);
179 STATIC_DESTRUCTOR_REGISTER(arg_properties
, strv_freep
);
180 STATIC_DESTRUCTOR_REGISTER(arg_clean_what
, strv_freep
);
181 STATIC_DESTRUCTOR_REGISTER(cached_id_map
, hashmap_freep
);
182 STATIC_DESTRUCTOR_REGISTER(cached_name_map
, hashmap_freep
);
184 static int daemon_reload(int argc
, char *argv
[], void* userdata
);
185 static int trivial_method(int argc
, char *argv
[], void *userdata
);
186 static int halt_now(enum action a
);
187 static int get_state_one_unit(sd_bus
*bus
, const char *name
, UnitActiveState
*active_state
);
189 static bool original_stdout_is_tty
;
191 typedef enum BusFocus
{
192 BUS_FULL
, /* The full bus indicated via --system or --user */
193 BUS_MANAGER
, /* The manager itself, possibly directly, possibly via the bus */
197 static sd_bus
*buses
[_BUS_FOCUS_MAX
] = {};
199 static UnitFileFlags
args_to_flags(void) {
200 return (arg_runtime
? UNIT_FILE_RUNTIME
: 0) |
201 (arg_force
? UNIT_FILE_FORCE
: 0);
204 static int acquire_bus(BusFocus focus
, sd_bus
**ret
) {
207 assert(focus
< _BUS_FOCUS_MAX
);
210 /* We only go directly to the manager, if we are using a local transport */
211 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
214 if (getenv_bool("SYSTEMCTL_FORCE_BUS") > 0)
220 user
= arg_scope
!= UNIT_FILE_SYSTEM
;
222 if (focus
== BUS_MANAGER
)
223 r
= bus_connect_transport_systemd(arg_transport
, arg_host
, user
, &buses
[focus
]);
225 r
= bus_connect_transport(arg_transport
, arg_host
, user
, &buses
[focus
]);
227 return log_error_errno(r
, "Failed to connect to bus: %m");
229 (void) sd_bus_set_allow_interactive_authorization(buses
[focus
], arg_ask_password
);
236 static void release_busses(void) {
239 for (w
= 0; w
< _BUS_FOCUS_MAX
; w
++)
240 buses
[w
] = sd_bus_flush_close_unref(buses
[w
]);
243 static void ask_password_agent_open_maybe(void) {
244 /* Open the password agent as a child process if necessary */
249 if (arg_scope
!= UNIT_FILE_SYSTEM
)
252 ask_password_agent_open_if_enabled(arg_transport
, arg_ask_password
);
255 static void polkit_agent_open_maybe(void) {
256 /* Open the polkit agent as a child process if necessary */
258 if (arg_scope
!= UNIT_FILE_SYSTEM
)
261 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
264 static OutputFlags
get_output_flags(void) {
266 arg_all
* OUTPUT_SHOW_ALL
|
267 (arg_full
|| !on_tty() || pager_have()) * OUTPUT_FULL_WIDTH
|
268 colors_enabled() * OUTPUT_COLOR
|
269 !arg_quiet
* OUTPUT_WARN_CUTOFF
;
272 static int translate_bus_error_to_exit_status(int r
, const sd_bus_error
*error
) {
275 if (!sd_bus_error_is_set(error
))
278 if (sd_bus_error_has_name(error
, SD_BUS_ERROR_ACCESS_DENIED
) ||
279 sd_bus_error_has_name(error
, BUS_ERROR_ONLY_BY_DEPENDENCY
) ||
280 sd_bus_error_has_name(error
, BUS_ERROR_NO_ISOLATION
) ||
281 sd_bus_error_has_name(error
, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE
))
282 return EXIT_NOPERMISSION
;
284 if (sd_bus_error_has_name(error
, BUS_ERROR_NO_SUCH_UNIT
))
285 return EXIT_NOTINSTALLED
;
287 if (sd_bus_error_has_name(error
, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE
) ||
288 sd_bus_error_has_name(error
, SD_BUS_ERROR_NOT_SUPPORTED
))
289 return EXIT_NOTIMPLEMENTED
;
291 if (sd_bus_error_has_name(error
, BUS_ERROR_LOAD_FAILED
))
292 return EXIT_NOTCONFIGURED
;
300 static bool install_client_side(void) {
301 /* Decides when to execute enable/disable/... operations
302 * client-side rather than server-side. */
304 if (running_in_chroot_or_offline())
307 if (sd_booted() <= 0)
310 if (!isempty(arg_root
))
313 if (arg_scope
== UNIT_FILE_GLOBAL
)
316 /* Unsupported environment variable, mostly for debugging purposes */
317 if (getenv_bool("SYSTEMCTL_INSTALL_CLIENT_SIDE") > 0)
323 static int compare_unit_info(const UnitInfo
*a
, const UnitInfo
*b
) {
327 /* First, order by machine */
328 if (!a
->machine
&& b
->machine
)
330 if (a
->machine
&& !b
->machine
)
332 if (a
->machine
&& b
->machine
) {
333 r
= strcasecmp(a
->machine
, b
->machine
);
338 /* Second, order by unit type */
339 d1
= strrchr(a
->id
, '.');
340 d2
= strrchr(b
->id
, '.');
342 r
= strcasecmp(d1
, d2
);
347 /* Third, order by name */
348 return strcasecmp(a
->id
, b
->id
);
351 static const char* unit_type_suffix(const char *name
) {
354 dot
= strrchr(name
, '.');
361 static bool output_show_unit(const UnitInfo
*u
, char **patterns
) {
364 if (!strv_fnmatch_or_empty(patterns
, u
->id
, FNM_NOESCAPE
))
367 if (arg_types
&& !strv_find(arg_types
, unit_type_suffix(u
->id
)))
373 /* Note that '--all' is not purely a state filter, but also a
374 * filter that hides units that "follow" other units (which is
375 * used for device units that appear under different names). */
376 if (!isempty(u
->following
))
379 if (!strv_isempty(arg_states
))
382 /* By default show all units except the ones in inactive
383 * state and with no pending job */
387 if (streq(u
->active_state
, "inactive"))
393 static int output_table(Table
*table
) {
398 if (OUTPUT_MODE_IS_JSON(arg_output
))
399 r
= table_print_json(table
, NULL
, output_mode_to_json_format_flags(arg_output
) | JSON_FORMAT_COLOR_AUTO
);
401 r
= table_print(table
, NULL
);
403 return log_error_errno(r
, "Failed to show table: %m");
408 static int output_units_list(const UnitInfo
*unit_infos
, unsigned c
) {
409 _cleanup_(table_unrefp
) Table
*table
= NULL
;
414 table
= table_new("", "unit", "load", "active", "sub", "job", "description");
418 table_set_header(table
, !arg_no_legend
);
420 /* Hide the 'glyph' column when --plain is requested */
421 r
= table_hide_column_from_display(table
, 0);
423 return log_error_errno(r
, "Failed to hide column: %m");
426 table_set_width(table
, 0);
428 (void) table_set_empty_string(table
, "-");
430 for (u
= unit_infos
; unit_infos
&& u
< unit_infos
+ c
; u
++) {
431 _cleanup_free_
char *j
= NULL
;
432 const char *on_underline
= "", *on_loaded
= "", *on_active
= "";
433 const char *on_circle
= "", *id
;
434 bool circle
= false, underline
= false;
436 if (u
+ 1 < unit_infos
+ c
&&
437 !streq(unit_type_suffix(u
->id
), unit_type_suffix((u
+ 1)->id
))) {
438 on_underline
= ansi_underline();
442 if (STR_IN_SET(u
->load_state
, "error", "not-found", "bad-setting", "masked") && !arg_plain
) {
443 on_circle
= underline
? ansi_highlight_yellow_underline() : ansi_highlight_yellow();
445 on_loaded
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
446 } else if (streq(u
->active_state
, "failed") && !arg_plain
) {
447 on_circle
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
449 on_active
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
451 on_circle
= on_underline
;
452 on_active
= on_underline
;
453 on_loaded
= on_underline
;
457 j
= strjoin(u
->machine
, ":", u
->id
);
465 r
= table_add_many(table
,
466 TABLE_STRING
, circle
? special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
) : " ",
467 TABLE_SET_BOTH_COLORS
, on_circle
,
469 TABLE_SET_BOTH_COLORS
, on_active
,
470 TABLE_STRING
, u
->load_state
,
471 TABLE_SET_BOTH_COLORS
, on_loaded
,
472 TABLE_STRING
, u
->active_state
,
473 TABLE_SET_BOTH_COLORS
, on_active
,
474 TABLE_STRING
, u
->sub_state
,
475 TABLE_SET_BOTH_COLORS
, on_active
,
476 TABLE_STRING
, u
->job_id
? u
->job_type
: "",
477 TABLE_SET_BOTH_COLORS
, u
->job_id
? on_underline
: "",
478 TABLE_STRING
, u
->description
,
479 TABLE_SET_BOTH_COLORS
, on_underline
);
481 return table_log_add_error(r
);
487 if (job_count
== 0) {
488 /* There's no data in the JOB column, so let's hide it */
489 r
= table_hide_column_from_display(table
, 5);
491 return log_error_errno(r
, "Failed to hide column: %m");
494 r
= output_table(table
);
498 if (!arg_no_legend
) {
499 const char *on
, *off
;
500 size_t records
= table_get_rows(table
) - 1;
504 "LOAD = Reflects whether the unit definition was properly loaded.\n"
505 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
506 "SUB = The low-level unit activation state, values depend on unit type.");
507 puts(job_count
? "JOB = Pending job for the unit.\n" : "");
508 on
= ansi_highlight();
511 on
= ansi_highlight_red();
515 if (arg_all
|| strv_contains(arg_states
, "inactive"))
516 printf("%s%zu loaded units listed.%s\n"
517 "To show all installed unit files use 'systemctl list-unit-files'.\n",
519 else if (!arg_states
)
520 printf("%s%zu loaded units listed.%s Pass --all to see loaded but inactive units, too.\n"
521 "To show all installed unit files use 'systemctl list-unit-files'.\n",
524 printf("%zu loaded units listed.\n", records
);
530 static int get_unit_list(
534 UnitInfo
**unit_infos
,
536 sd_bus_message
**_reply
) {
538 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
539 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
540 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
544 bool fallback
= false;
550 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "ListUnitsByPatterns");
552 return bus_log_create_error(r
);
554 r
= sd_bus_message_append_strv(m
, arg_states
);
556 return bus_log_create_error(r
);
558 r
= sd_bus_message_append_strv(m
, patterns
);
560 return bus_log_create_error(r
);
562 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
563 if (r
< 0 && (sd_bus_error_has_name(&error
, SD_BUS_ERROR_UNKNOWN_METHOD
) ||
564 sd_bus_error_has_name(&error
, SD_BUS_ERROR_ACCESS_DENIED
))) {
565 /* Fallback to legacy ListUnitsFiltered method */
567 log_debug_errno(r
, "Failed to list units: %s Falling back to ListUnitsFiltered method.", bus_error_message(&error
, r
));
568 m
= sd_bus_message_unref(m
);
569 sd_bus_error_free(&error
);
571 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "ListUnitsFiltered");
573 return bus_log_create_error(r
);
575 r
= sd_bus_message_append_strv(m
, arg_states
);
577 return bus_log_create_error(r
);
579 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
582 return log_error_errno(r
, "Failed to list units: %s", bus_error_message(&error
, r
));
584 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssssouso)");
586 return bus_log_parse_error(r
);
588 while ((r
= bus_parse_unit_info(reply
, &u
)) > 0) {
591 if (!output_show_unit(&u
, fallback
? patterns
: NULL
))
594 if (!GREEDY_REALLOC(*unit_infos
, size
, c
+1))
597 (*unit_infos
)[c
++] = u
;
600 return bus_log_parse_error(r
);
602 r
= sd_bus_message_exit_container(reply
);
604 return bus_log_parse_error(r
);
606 *_reply
= TAKE_PTR(reply
);
611 static void message_set_freep(Set
**set
) {
612 set_free_with_destructor(*set
, sd_bus_message_unref
);
615 static int get_unit_list_recursive(
618 UnitInfo
**_unit_infos
,
622 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
623 _cleanup_(message_set_freep
) Set
*replies
;
624 sd_bus_message
*reply
;
632 replies
= set_new(NULL
);
636 c
= get_unit_list(bus
, NULL
, patterns
, &unit_infos
, 0, &reply
);
640 r
= set_put(replies
, reply
);
642 sd_bus_message_unref(reply
);
647 _cleanup_strv_free_
char **machines
= NULL
;
650 r
= sd_get_machine_names(&machines
);
652 return log_error_errno(r
, "Failed to get machine names: %m");
654 STRV_FOREACH(i
, machines
) {
655 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*container
= NULL
;
658 r
= sd_bus_open_system_machine(&container
, *i
);
660 log_warning_errno(r
, "Failed to connect to container %s, ignoring: %m", *i
);
664 k
= get_unit_list(container
, *i
, patterns
, &unit_infos
, c
, &reply
);
670 r
= set_put(replies
, reply
);
672 sd_bus_message_unref(reply
);
677 *_machines
= TAKE_PTR(machines
);
681 *_unit_infos
= TAKE_PTR(unit_infos
);
682 *_replies
= TAKE_PTR(replies
);
687 static int expand_names(sd_bus
*bus
, char **names
, const char* suffix
, char ***ret
, bool *ret_expanded
) {
688 _cleanup_strv_free_
char **mangled
= NULL
, **globs
= NULL
;
695 STRV_FOREACH(name
, names
) {
697 UnitNameMangle options
= UNIT_NAME_MANGLE_GLOB
| (arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
);
699 r
= unit_name_mangle_with_suffix(*name
, NULL
, options
, suffix
?: ".service", &t
);
701 return log_error_errno(r
, "Failed to mangle name: %m");
703 if (string_is_glob(t
))
704 r
= strv_consume(&globs
, t
);
706 r
= strv_consume(&mangled
, t
);
711 /* Query the manager only if any of the names are a glob, since
712 * this is fairly expensive */
713 bool expanded
= !strv_isempty(globs
);
715 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
716 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
719 r
= get_unit_list(bus
, NULL
, globs
, &unit_infos
, 0, &reply
);
723 n
= strv_length(mangled
);
726 for (i
= 0; i
< r
; i
++) {
727 if (!GREEDY_REALLOC(mangled
, allocated
, n
+2))
730 mangled
[n
] = strdup(unit_infos
[i
].id
);
739 *ret_expanded
= expanded
;
741 *ret
= TAKE_PTR(mangled
);
745 static int list_dependencies_get_dependencies(sd_bus
*bus
, const char *name
, char ***ret
) {
746 _cleanup_strv_free_
char **deps
= NULL
;
748 static const struct bus_properties_map map
[_DEPENDENCY_MAX
][6] = {
749 [DEPENDENCY_FORWARD
] = {
750 { "Requires", "as", NULL
, 0 },
751 { "Requisite", "as", NULL
, 0 },
752 { "Wants", "as", NULL
, 0 },
753 { "ConsistsOf", "as", NULL
, 0 },
754 { "BindsTo", "as", NULL
, 0 },
757 [DEPENDENCY_REVERSE
] = {
758 { "RequiredBy", "as", NULL
, 0 },
759 { "RequisiteOf", "as", NULL
, 0 },
760 { "WantedBy", "as", NULL
, 0 },
761 { "PartOf", "as", NULL
, 0 },
762 { "BoundBy", "as", NULL
, 0 },
765 [DEPENDENCY_AFTER
] = {
766 { "After", "as", NULL
, 0 },
769 [DEPENDENCY_BEFORE
] = {
770 { "Before", "as", NULL
, 0 },
775 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
776 _cleanup_free_
char *dbus_path
= NULL
;
783 dbus_path
= unit_dbus_path_from_name(name
);
787 r
= bus_map_all_properties(bus
,
788 "org.freedesktop.systemd1",
796 return log_error_errno(r
, "Failed to get properties of %s: %s", name
, bus_error_message(&error
, r
));
798 strv_uniq(deps
); /* Sometimes a unit might have multiple deps on the other unit,
799 * but we still want to show it just once. */
800 *ret
= TAKE_PTR(deps
);
805 static int append_unit_dependencies(sd_bus
*bus
, char **names
, char ***ret
) {
806 _cleanup_strv_free_
char **with_deps
= NULL
;
812 STRV_FOREACH(name
, names
) {
813 _cleanup_strv_free_
char **deps
= NULL
;
815 if (strv_extend(&with_deps
, *name
) < 0)
818 (void) list_dependencies_get_dependencies(bus
, *name
, &deps
);
820 if (strv_extend_strv(&with_deps
, deps
, true) < 0)
824 *ret
= TAKE_PTR(with_deps
);
829 static int maybe_extend_with_unit_dependencies(sd_bus
*bus
, char ***list
) {
833 if (arg_with_dependencies
) {
835 _cleanup_strv_free_
char **list_with_deps
= NULL
;
837 r
= append_unit_dependencies(bus
, *list
, &list_with_deps
);
839 return log_error_errno(r
, "Failed to append unit dependencies: %m");
842 *list
= TAKE_PTR(list_with_deps
);
848 static int list_units(int argc
, char *argv
[], void *userdata
) {
849 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
850 _cleanup_(message_set_freep
) Set
*replies
= NULL
;
851 _cleanup_strv_free_
char **machines
= NULL
;
855 r
= acquire_bus(BUS_MANAGER
, &bus
);
859 (void) pager_open(arg_pager_flags
);
861 if (arg_with_dependencies
) {
862 _cleanup_strv_free_
char **names
= NULL
;
864 r
= append_unit_dependencies(bus
, strv_skip(argv
, 1), &names
);
868 r
= get_unit_list_recursive(bus
, names
, &unit_infos
, &replies
, &machines
);
872 r
= get_unit_list_recursive(bus
, strv_skip(argv
, 1), &unit_infos
, &replies
, &machines
);
877 typesafe_qsort(unit_infos
, r
, compare_unit_info
);
878 return output_units_list(unit_infos
, r
);
881 static int get_triggered_units(
886 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
893 r
= sd_bus_get_property_strv(
895 "org.freedesktop.systemd1",
897 "org.freedesktop.systemd1.Unit",
902 return log_error_errno(r
, "Failed to determine triggers: %s", bus_error_message(&error
, r
));
907 static int get_listening(
909 const char* unit_path
,
912 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
913 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
914 const char *type
, *path
;
917 r
= sd_bus_get_property(
919 "org.freedesktop.systemd1",
921 "org.freedesktop.systemd1.Socket",
927 return log_error_errno(r
, "Failed to get list of listening sockets: %s", bus_error_message(&error
, r
));
929 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ss)");
931 return bus_log_parse_error(r
);
933 while ((r
= sd_bus_message_read(reply
, "(ss)", &type
, &path
)) > 0) {
935 r
= strv_extend(listening
, type
);
939 r
= strv_extend(listening
, path
);
946 return bus_log_parse_error(r
);
948 r
= sd_bus_message_exit_container(reply
);
950 return bus_log_parse_error(r
);
962 /* Note: triggered is a list here, although it almost certainly
963 * will always be one unit. Nevertheless, dbus API allows for multiple
964 * values, so let's follow that. */
967 /* The strv above is shared. free is set only in the first one. */
971 static int socket_info_compare(const struct socket_info
*a
, const struct socket_info
*b
) {
977 if (!a
->machine
&& b
->machine
)
979 if (a
->machine
&& !b
->machine
)
981 if (a
->machine
&& b
->machine
) {
982 r
= strcasecmp(a
->machine
, b
->machine
);
987 r
= strcmp(a
->path
, b
->path
);
989 r
= strcmp(a
->type
, b
->type
);
994 static int output_sockets_list(struct socket_info
*socket_infos
, unsigned cs
) {
995 _cleanup_(table_unrefp
) Table
*table
= NULL
;
996 struct socket_info
*s
;
997 const char *on
, *off
;
1000 table
= table_new("listen", "type", "unit", "activates");
1004 if (!arg_show_types
) {
1005 /* Hide the second (TYPE) column */
1006 r
= table_set_display(table
, (size_t) 0, (size_t) 2, (size_t) 3, (size_t) -1);
1008 return log_error_errno(r
, "Failed to set columns to display: %m");
1011 table_set_header(table
, !arg_no_legend
);
1013 table_set_width(table
, 0);
1015 (void) table_set_empty_string(table
, "-");
1018 for (s
= socket_infos
; s
< socket_infos
+ cs
; s
++) {
1019 _cleanup_free_
char *j
= NULL
;
1023 j
= strjoin(s
->machine
, ":", s
->path
);
1030 r
= table_add_many(table
,
1032 TABLE_STRING
, s
->type
,
1033 TABLE_STRING
, s
->id
);
1035 return table_log_add_error(r
);
1037 if (strv_isempty(s
->triggered
))
1038 r
= table_add_cell(table
, NULL
, TABLE_EMPTY
, NULL
);
1039 else if (strv_length(s
->triggered
) == 1)
1040 r
= table_add_cell(table
, NULL
, TABLE_STRING
, s
->triggered
[0]);
1042 /* This should never happen, currently our socket units can only trigger a
1043 * single unit. But let's handle this anyway, who knows what the future
1045 r
= table_add_cell(table
, NULL
, TABLE_STRV
, s
->triggered
);
1047 return table_log_add_error(r
);
1051 on
= ansi_highlight();
1052 off
= ansi_normal();
1054 on
= ansi_highlight_red();
1055 off
= ansi_normal();
1058 r
= output_table(table
);
1062 if (!arg_no_legend
) {
1063 printf("\n%s%u sockets listed.%s\n", on
, cs
, off
);
1065 printf("Pass --all to see loaded but inactive sockets, too.\n");
1071 static int list_sockets(int argc
, char *argv
[], void *userdata
) {
1072 _cleanup_(message_set_freep
) Set
*replies
= NULL
;
1073 _cleanup_strv_free_
char **machines
= NULL
;
1074 _cleanup_strv_free_
char **sockets_with_suffix
= NULL
;
1075 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
1076 _cleanup_free_
struct socket_info
*socket_infos
= NULL
;
1078 struct socket_info
*s
;
1084 r
= acquire_bus(BUS_MANAGER
, &bus
);
1088 (void) pager_open(arg_pager_flags
);
1090 r
= expand_names(bus
, strv_skip(argv
, 1), ".socket", &sockets_with_suffix
, NULL
);
1094 if (argc
== 1 || sockets_with_suffix
) {
1095 n
= get_unit_list_recursive(bus
, sockets_with_suffix
, &unit_infos
, &replies
, &machines
);
1099 for (u
= unit_infos
; u
< unit_infos
+ n
; u
++) {
1100 _cleanup_strv_free_
char **listening
= NULL
, **triggered
= NULL
;
1103 if (!endswith(u
->id
, ".socket"))
1106 r
= get_triggered_units(bus
, u
->unit_path
, &triggered
);
1110 c
= get_listening(bus
, u
->unit_path
, &listening
);
1116 if (!GREEDY_REALLOC(socket_infos
, size
, cs
+ c
)) {
1121 for (i
= 0; i
< c
; i
++)
1122 socket_infos
[cs
+ i
] = (struct socket_info
) {
1123 .machine
= u
->machine
,
1125 .type
= listening
[i
*2],
1126 .path
= listening
[i
*2 + 1],
1127 .triggered
= triggered
,
1128 .own_triggered
= i
==0,
1131 /* from this point on we will cleanup those socket_infos */
1134 listening
= triggered
= NULL
; /* avoid cleanup */
1137 typesafe_qsort(socket_infos
, cs
, socket_info_compare
);
1140 output_sockets_list(socket_infos
, cs
);
1143 assert(cs
== 0 || socket_infos
);
1144 for (s
= socket_infos
; s
< socket_infos
+ cs
; s
++) {
1147 if (s
->own_triggered
)
1148 strv_free(s
->triggered
);
1154 static int get_next_elapse(
1157 dual_timestamp
*next
) {
1159 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1167 r
= sd_bus_get_property_trivial(
1169 "org.freedesktop.systemd1",
1171 "org.freedesktop.systemd1.Timer",
1172 "NextElapseUSecMonotonic",
1177 return log_error_errno(r
, "Failed to get next elapse time: %s", bus_error_message(&error
, r
));
1179 r
= sd_bus_get_property_trivial(
1181 "org.freedesktop.systemd1",
1183 "org.freedesktop.systemd1.Timer",
1184 "NextElapseUSecRealtime",
1189 return log_error_errno(r
, "Failed to get next elapse time: %s", bus_error_message(&error
, r
));
1195 static int get_last_trigger(
1200 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1207 r
= sd_bus_get_property_trivial(
1209 "org.freedesktop.systemd1",
1211 "org.freedesktop.systemd1.Timer",
1217 return log_error_errno(r
, "Failed to get last trigger time: %s", bus_error_message(&error
, r
));
1223 const char* machine
;
1226 usec_t last_trigger
;
1230 static int timer_info_compare(const struct timer_info
*a
, const struct timer_info
*b
) {
1236 if (!a
->machine
&& b
->machine
)
1238 if (a
->machine
&& !b
->machine
)
1240 if (a
->machine
&& b
->machine
) {
1241 r
= strcasecmp(a
->machine
, b
->machine
);
1246 r
= CMP(a
->next_elapse
, b
->next_elapse
);
1250 return strcmp(a
->id
, b
->id
);
1253 static int output_timers_list(struct timer_info
*timer_infos
, unsigned n
) {
1254 _cleanup_(table_unrefp
) Table
*table
= NULL
;
1255 struct timer_info
*t
;
1256 const char *on
, *off
;
1259 assert(timer_infos
|| n
== 0);
1261 table
= table_new("next", "left", "last", "passed", "unit", "activates");
1265 table_set_header(table
, !arg_no_legend
);
1267 table_set_width(table
, 0);
1269 (void) table_set_empty_string(table
, "-");
1272 for (t
= timer_infos
; t
< timer_infos
+ n
; t
++) {
1273 _cleanup_free_
char *j
= NULL
, *activates
= NULL
;
1277 j
= strjoin(t
->machine
, ":", t
->id
);
1284 activates
= strv_join(t
->triggered
, ", ");
1288 r
= table_add_many(table
,
1289 TABLE_TIMESTAMP
, t
->next_elapse
,
1290 TABLE_TIMESTAMP_RELATIVE
, t
->next_elapse
,
1291 TABLE_TIMESTAMP
, t
->last_trigger
,
1292 TABLE_TIMESTAMP_RELATIVE
, t
->last_trigger
,
1294 TABLE_STRING
, activates
);
1296 return table_log_add_error(r
);
1299 on
= ansi_highlight();
1300 off
= ansi_normal();
1302 on
= ansi_highlight_red();
1303 off
= ansi_normal();
1306 r
= output_table(table
);
1310 if (!arg_no_legend
) {
1311 printf("\n%s%u timers listed.%s\n", on
, n
, off
);
1313 printf("Pass --all to see loaded but inactive timers, too.\n");
1319 static usec_t
calc_next_elapse(dual_timestamp
*nw
, dual_timestamp
*next
) {
1325 if (timestamp_is_set(next
->monotonic
)) {
1328 if (next
->monotonic
> nw
->monotonic
)
1329 converted
= nw
->realtime
+ (next
->monotonic
- nw
->monotonic
);
1331 converted
= nw
->realtime
- (nw
->monotonic
- next
->monotonic
);
1333 if (timestamp_is_set(next
->realtime
))
1334 next_elapse
= MIN(converted
, next
->realtime
);
1336 next_elapse
= converted
;
1339 next_elapse
= next
->realtime
;
1344 static int list_timers(int argc
, char *argv
[], void *userdata
) {
1345 _cleanup_(message_set_freep
) Set
*replies
= NULL
;
1346 _cleanup_strv_free_
char **machines
= NULL
;
1347 _cleanup_strv_free_
char **timers_with_suffix
= NULL
;
1348 _cleanup_free_
struct timer_info
*timer_infos
= NULL
;
1349 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
1350 struct timer_info
*t
;
1358 r
= acquire_bus(BUS_MANAGER
, &bus
);
1362 (void) pager_open(arg_pager_flags
);
1364 r
= expand_names(bus
, strv_skip(argv
, 1), ".timer", &timers_with_suffix
, NULL
);
1368 if (argc
== 1 || timers_with_suffix
) {
1369 n
= get_unit_list_recursive(bus
, timers_with_suffix
, &unit_infos
, &replies
, &machines
);
1373 dual_timestamp_get(&nw
);
1375 for (u
= unit_infos
; u
< unit_infos
+ n
; u
++) {
1376 _cleanup_strv_free_
char **triggered
= NULL
;
1377 dual_timestamp next
= DUAL_TIMESTAMP_NULL
;
1380 if (!endswith(u
->id
, ".timer"))
1383 r
= get_triggered_units(bus
, u
->unit_path
, &triggered
);
1387 r
= get_next_elapse(bus
, u
->unit_path
, &next
);
1391 get_last_trigger(bus
, u
->unit_path
, &last
);
1393 if (!GREEDY_REALLOC(timer_infos
, size
, c
+1)) {
1398 m
= calc_next_elapse(&nw
, &next
);
1400 timer_infos
[c
++] = (struct timer_info
) {
1401 .machine
= u
->machine
,
1404 .last_trigger
= last
,
1405 .triggered
= TAKE_PTR(triggered
),
1409 typesafe_qsort(timer_infos
, c
, timer_info_compare
);
1412 output_timers_list(timer_infos
, c
);
1415 for (t
= timer_infos
; t
< timer_infos
+ c
; t
++)
1416 strv_free(t
->triggered
);
1421 static int compare_unit_file_list(const UnitFileList
*a
, const UnitFileList
*b
) {
1422 const char *d1
, *d2
;
1424 d1
= strrchr(a
->path
, '.');
1425 d2
= strrchr(b
->path
, '.');
1430 r
= strcasecmp(d1
, d2
);
1435 return strcasecmp(basename(a
->path
), basename(b
->path
));
1438 static bool output_show_unit_file(const UnitFileList
*u
, char **states
, char **patterns
) {
1441 if (!strv_fnmatch_or_empty(patterns
, basename(u
->path
), FNM_NOESCAPE
))
1444 if (!strv_isempty(arg_types
)) {
1447 dot
= strrchr(u
->path
, '.');
1451 if (!strv_find(arg_types
, dot
+1))
1455 if (!strv_isempty(states
) &&
1456 !strv_find(states
, unit_file_state_to_string(u
->state
)))
1462 static bool show_preset_for_state(UnitFileState state
) {
1463 /* Don't show preset state in those unit file states, it'll only confuse users. */
1464 return !IN_SET(state
,
1467 UNIT_FILE_GENERATED
,
1468 UNIT_FILE_TRANSIENT
);
1471 static int output_unit_file_list(const UnitFileList
*units
, unsigned c
) {
1472 _cleanup_(table_unrefp
) Table
*table
= NULL
;
1473 _cleanup_(unit_file_presets_freep
) UnitFilePresets presets
= {};
1476 table
= table_new("unit file", "state", "vendor preset");
1480 table_set_header(table
, !arg_no_legend
);
1482 table_set_width(table
, 0);
1484 (void) table_set_empty_string(table
, "-");
1486 for (const UnitFileList
*u
= units
; u
< units
+ c
; u
++) {
1487 const char *on_underline
= NULL
, *on_unit_color
= NULL
, *id
;
1490 underline
= u
+ 1 < units
+ c
&&
1491 !streq(unit_type_suffix(u
->path
), unit_type_suffix((u
+ 1)->path
));
1494 on_underline
= ansi_underline();
1496 if (IN_SET(u
->state
,
1498 UNIT_FILE_MASKED_RUNTIME
,
1501 on_unit_color
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
1502 else if (IN_SET(u
->state
,
1505 on_unit_color
= underline
? ansi_highlight_green_underline() : ansi_highlight_green();
1507 on_unit_color
= on_underline
;
1509 id
= basename(u
->path
);
1511 r
= table_add_many(table
,
1513 TABLE_SET_BOTH_COLORS
, strempty(on_underline
),
1514 TABLE_STRING
, unit_file_state_to_string(u
->state
),
1515 TABLE_SET_BOTH_COLORS
, strempty(on_unit_color
));
1517 return table_log_add_error(r
);
1519 if (show_preset_for_state(u
->state
)) {
1520 const char *unit_preset_str
, *on_preset_color
;
1522 r
= unit_file_query_preset(arg_scope
, arg_root
, id
, &presets
);
1524 unit_preset_str
= "n/a";
1525 on_preset_color
= underline
? on_underline
: ansi_normal();
1526 } else if (r
== 0) {
1527 unit_preset_str
= "disabled";
1528 on_preset_color
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
1530 unit_preset_str
= "enabled";
1531 on_preset_color
= underline
? ansi_highlight_green_underline() : ansi_highlight_green();
1534 r
= table_add_many(table
,
1535 TABLE_STRING
, unit_preset_str
,
1536 TABLE_SET_BOTH_COLORS
, strempty(on_preset_color
));
1538 r
= table_add_many(table
,
1540 TABLE_SET_BOTH_COLORS
, underline
? ansi_grey_underline() : ansi_grey());
1542 return table_log_add_error(r
);
1545 r
= output_table(table
);
1550 printf("\n%u unit files listed.\n", c
);
1555 static int list_unit_files(int argc
, char *argv
[], void *userdata
) {
1556 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1557 _cleanup_free_ UnitFileList
*units
= NULL
;
1564 bool fallback
= false;
1566 if (install_client_side()) {
1572 h
= hashmap_new(&string_hash_ops
);
1576 r
= unit_file_get_list(arg_scope
, arg_root
, h
, arg_states
, strv_skip(argv
, 1));
1578 unit_file_list_free(h
);
1579 return log_error_errno(r
, "Failed to get unit file list: %m");
1582 n_units
= hashmap_size(h
);
1584 units
= new(UnitFileList
, n_units
?: 1); /* avoid malloc(0) */
1586 unit_file_list_free(h
);
1590 HASHMAP_FOREACH(u
, h
, i
) {
1591 if (!output_show_unit_file(u
, NULL
, NULL
))
1598 assert(c
<= n_units
);
1603 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
1604 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1607 r
= acquire_bus(BUS_MANAGER
, &bus
);
1611 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "ListUnitFilesByPatterns");
1613 return bus_log_create_error(r
);
1615 r
= sd_bus_message_append_strv(m
, arg_states
);
1617 return bus_log_create_error(r
);
1619 if (arg_with_dependencies
) {
1620 _cleanup_strv_free_
char **names_with_deps
= NULL
;
1622 r
= append_unit_dependencies(bus
, strv_skip(argv
, 1), &names_with_deps
);
1624 return log_error_errno(r
, "Failed to append unit dependencies: %m");
1626 r
= sd_bus_message_append_strv(m
, names_with_deps
);
1628 return bus_log_create_error(r
);
1630 r
= sd_bus_message_append_strv(m
, strv_skip(argv
, 1));
1632 return bus_log_create_error(r
);
1635 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1636 if (r
< 0 && sd_bus_error_has_name(&error
, SD_BUS_ERROR_UNKNOWN_METHOD
)) {
1637 /* Fallback to legacy ListUnitFiles method */
1639 log_debug_errno(r
, "Failed to list unit files: %s Falling back to ListUnitsFiles method.", bus_error_message(&error
, r
));
1640 m
= sd_bus_message_unref(m
);
1641 sd_bus_error_free(&error
);
1643 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "ListUnitFiles");
1645 return bus_log_create_error(r
);
1647 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1650 return log_error_errno(r
, "Failed to list unit files: %s", bus_error_message(&error
, r
));
1652 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ss)");
1654 return bus_log_parse_error(r
);
1656 while ((r
= sd_bus_message_read(reply
, "(ss)", &path
, &state
)) > 0) {
1658 if (!GREEDY_REALLOC(units
, size
, c
+ 1))
1661 units
[c
] = (struct UnitFileList
) {
1663 unit_file_state_from_string(state
)
1666 if (output_show_unit_file(&units
[c
],
1667 fallback
? arg_states
: NULL
,
1668 fallback
? strv_skip(argv
, 1) : NULL
))
1673 return bus_log_parse_error(r
);
1675 r
= sd_bus_message_exit_container(reply
);
1677 return bus_log_parse_error(r
);
1680 (void) pager_open(arg_pager_flags
);
1682 typesafe_qsort(units
, c
, compare_unit_file_list
);
1683 r
= output_unit_file_list(units
, c
);
1687 if (install_client_side())
1688 for (unit
= units
; unit
< units
+ c
; unit
++)
1697 static int list_dependencies_print(const char *name
, int level
, unsigned branches
, bool last
) {
1698 _cleanup_free_
char *n
= NULL
;
1699 size_t max_len
= MAX(columns(),20u);
1705 for (i
= level
- 1; i
>= 0; i
--) {
1707 if (len
> max_len
- 3 && !arg_full
) {
1708 printf("%s...\n",max_len
% 2 ? "" : " ");
1711 printf("%s", special_glyph(branches
& (1 << i
) ? SPECIAL_GLYPH_TREE_VERTICAL
: SPECIAL_GLYPH_TREE_SPACE
));
1715 if (len
> max_len
- 3 && !arg_full
) {
1716 printf("%s...\n",max_len
% 2 ? "" : " ");
1720 printf("%s", special_glyph(last
? SPECIAL_GLYPH_TREE_RIGHT
: SPECIAL_GLYPH_TREE_BRANCH
));
1724 printf("%s\n", name
);
1728 n
= ellipsize(name
, max_len
-len
, 100);
1736 static int list_dependencies_compare(char * const *a
, char * const *b
) {
1737 if (unit_name_to_type(*a
) == UNIT_TARGET
&& unit_name_to_type(*b
) != UNIT_TARGET
)
1739 if (unit_name_to_type(*a
) != UNIT_TARGET
&& unit_name_to_type(*b
) == UNIT_TARGET
)
1742 return strcasecmp(*a
, *b
);
1745 static int list_dependencies_one(
1750 unsigned branches
) {
1752 _cleanup_strv_free_
char **deps
= NULL
;
1760 r
= strv_extend(units
, name
);
1764 r
= list_dependencies_get_dependencies(bus
, name
, &deps
);
1768 typesafe_qsort(deps
, strv_length(deps
), list_dependencies_compare
);
1770 STRV_FOREACH(c
, deps
) {
1771 if (strv_contains(*units
, *c
)) {
1774 r
= list_dependencies_print("...", level
+ 1, (branches
<< 1) | (c
[1] == NULL
? 0 : 1), 1);
1784 UnitActiveState active_state
= _UNIT_ACTIVE_STATE_INVALID
;
1787 (void) get_state_one_unit(bus
, *c
, &active_state
);
1789 switch (active_state
) {
1791 case UNIT_RELOADING
:
1792 case UNIT_ACTIVATING
:
1793 on
= ansi_highlight_green();
1797 case UNIT_DEACTIVATING
:
1802 on
= ansi_highlight_red();
1806 printf("%s%s%s ", on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), ansi_normal());
1809 r
= list_dependencies_print(*c
, level
, branches
, c
[1] == NULL
);
1813 if (arg_all
|| unit_name_to_type(*c
) == UNIT_TARGET
) {
1814 r
= list_dependencies_one(bus
, *c
, level
+ 1, units
, (branches
<< 1) | (c
[1] == NULL
? 0 : 1));
1821 strv_remove(*units
, name
);
1826 static int list_dependencies(int argc
, char *argv
[], void *userdata
) {
1827 _cleanup_strv_free_
char **units
= NULL
, **done
= NULL
;
1828 char **u
, **patterns
;
1832 r
= acquire_bus(BUS_MANAGER
, &bus
);
1836 patterns
= strv_skip(argv
, 1);
1837 if (strv_isempty(patterns
)) {
1838 units
= strv_new(SPECIAL_DEFAULT_TARGET
);
1842 r
= expand_names(bus
, patterns
, NULL
, &units
, NULL
);
1844 return log_error_errno(r
, "Failed to expand names: %m");
1847 (void) pager_open(arg_pager_flags
);
1849 STRV_FOREACH(u
, units
) {
1854 r
= list_dependencies_one(bus
, *u
, 0, &done
, 0);
1862 struct machine_info
{
1866 char *control_group
;
1867 uint32_t n_failed_units
;
1872 static const struct bus_properties_map machine_info_property_map
[] = {
1873 { "SystemState", "s", NULL
, offsetof(struct machine_info
, state
) },
1874 { "NJobs", "u", NULL
, offsetof(struct machine_info
, n_jobs
) },
1875 { "NFailedUnits", "u", NULL
, offsetof(struct machine_info
, n_failed_units
) },
1876 { "ControlGroup", "s", NULL
, offsetof(struct machine_info
, control_group
) },
1877 { "UserspaceTimestamp", "t", NULL
, offsetof(struct machine_info
, timestamp
) },
1881 static void machine_info_clear(struct machine_info
*info
) {
1886 free(info
->control_group
);
1890 static void free_machines_list(struct machine_info
*machine_infos
, int n
) {
1896 for (i
= 0; i
< n
; i
++)
1897 machine_info_clear(&machine_infos
[i
]);
1899 free(machine_infos
);
1902 static int compare_machine_info(const struct machine_info
*a
, const struct machine_info
*b
) {
1905 r
= CMP(b
->is_host
, a
->is_host
);
1909 return strcasecmp(a
->name
, b
->name
);
1912 static int get_machine_properties(sd_bus
*bus
, struct machine_info
*mi
) {
1913 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*container
= NULL
;
1919 r
= sd_bus_open_system_machine(&container
, mi
->name
);
1926 r
= bus_map_all_properties(
1928 "org.freedesktop.systemd1",
1929 "/org/freedesktop/systemd1",
1930 machine_info_property_map
,
1941 static bool output_show_machine(const char *name
, char **patterns
) {
1942 return strv_fnmatch_or_empty(patterns
, name
, FNM_NOESCAPE
);
1945 static int get_machine_list(
1947 struct machine_info
**_machine_infos
,
1950 struct machine_info
*machine_infos
= NULL
;
1951 _cleanup_strv_free_
char **m
= NULL
;
1952 _cleanup_free_
char *hn
= NULL
;
1957 hn
= gethostname_malloc();
1961 if (output_show_machine(hn
, patterns
)) {
1962 if (!GREEDY_REALLOC0(machine_infos
, sz
, c
+1))
1965 machine_infos
[c
].is_host
= true;
1966 machine_infos
[c
].name
= TAKE_PTR(hn
);
1968 (void) get_machine_properties(bus
, &machine_infos
[c
]);
1972 r
= sd_get_machine_names(&m
);
1974 return log_error_errno(r
, "Failed to get machine list: %m");
1976 STRV_FOREACH(i
, m
) {
1977 _cleanup_free_
char *class = NULL
;
1979 if (!output_show_machine(*i
, patterns
))
1982 sd_machine_get_class(*i
, &class);
1983 if (!streq_ptr(class, "container"))
1986 if (!GREEDY_REALLOC0(machine_infos
, sz
, c
+1)) {
1987 free_machines_list(machine_infos
, c
);
1991 machine_infos
[c
].is_host
= false;
1992 machine_infos
[c
].name
= strdup(*i
);
1993 if (!machine_infos
[c
].name
) {
1994 free_machines_list(machine_infos
, c
);
1998 (void) get_machine_properties(NULL
, &machine_infos
[c
]);
2002 *_machine_infos
= machine_infos
;
2006 static int output_machines_list(struct machine_info
*machine_infos
, unsigned n
) {
2007 _cleanup_(table_unrefp
) Table
*table
= NULL
;
2008 struct machine_info
*m
;
2009 bool state_missing
= false;
2012 assert(machine_infos
|| n
== 0);
2014 table
= table_new("", "name", "state", "failed", "jobs");
2018 table_set_header(table
, !arg_no_legend
);
2020 /* Hide the 'glyph' column when --plain is requested */
2021 r
= table_hide_column_from_display(table
, 0);
2023 return log_error_errno(r
, "Failed to hide column: %m");
2026 table_set_width(table
, 0);
2028 (void) table_set_empty_string(table
, "-");
2030 for (m
= machine_infos
; m
< machine_infos
+ n
; m
++) {
2031 _cleanup_free_
char *mname
= NULL
;
2032 const char *on_state
= "", *on_failed
= "";
2033 bool circle
= false;
2035 if (streq_ptr(m
->state
, "degraded")) {
2036 on_state
= ansi_highlight_red();
2038 } else if (!streq_ptr(m
->state
, "running")) {
2039 on_state
= ansi_highlight_yellow();
2043 if (m
->n_failed_units
> 0)
2044 on_failed
= ansi_highlight_red();
2049 state_missing
= true;
2052 mname
= strjoin(strna(m
->name
), " (host)");
2054 r
= table_add_many(table
,
2055 TABLE_STRING
, circle
? special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
) : " ",
2056 TABLE_SET_COLOR
, on_state
,
2057 TABLE_STRING
, m
->is_host
? mname
: strna(m
->name
),
2058 TABLE_STRING
, strna(m
->state
),
2059 TABLE_SET_COLOR
, on_state
,
2060 TABLE_UINT32
, m
->n_failed_units
,
2061 TABLE_SET_COLOR
, on_failed
,
2062 TABLE_UINT32
, m
->n_jobs
);
2064 return table_log_add_error(r
);
2067 r
= output_table(table
);
2071 if (!arg_no_legend
) {
2073 if (state_missing
&& geteuid() != 0)
2074 printf("Notice: some information only available to privileged users was not shown.\n");
2075 printf("%u machines listed.\n", n
);
2081 static int list_machines(int argc
, char *argv
[], void *userdata
) {
2082 struct machine_info
*machine_infos
= NULL
;
2086 r
= acquire_bus(BUS_MANAGER
, &bus
);
2090 r
= get_machine_list(bus
, &machine_infos
, strv_skip(argv
, 1));
2094 (void) pager_open(arg_pager_flags
);
2096 typesafe_qsort(machine_infos
, r
, compare_machine_info
);
2097 rc
= output_machines_list(machine_infos
, r
);
2098 free_machines_list(machine_infos
, r
);
2103 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
2106 if (streq(key
, "systemd.unit")) {
2107 if (proc_cmdline_value_missing(key
, value
))
2109 if (!unit_name_is_valid(value
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
2110 return log_warning("Unit name specified on %s= is not valid, ignoring: %s", key
, value
);
2112 return free_and_strdup_warn(ret
, key
);
2114 } else if (!value
) {
2115 if (runlevel_to_target(key
))
2116 return free_and_strdup_warn(ret
, key
);
2122 static void emit_cmdline_warning(void) {
2123 if (arg_quiet
|| arg_root
)
2124 /* don't bother checking the commandline if we're operating on a container */
2127 _cleanup_free_
char *override
= NULL
;
2130 r
= proc_cmdline_parse(parse_proc_cmdline_item
, &override
, 0);
2132 log_debug_errno(r
, "Failed to parse kernel command line, ignoring: %m");
2134 log_notice("Note: found \"%s\" on the kernel commandline, which overrides the default unit.",
2138 static int determine_default(char **ret_name
) {
2141 if (install_client_side()) {
2142 r
= unit_file_get_default(arg_scope
, arg_root
, ret_name
);
2144 return log_error_errno(r
, "Failed to get default target: %m");
2149 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2150 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2153 r
= acquire_bus(BUS_MANAGER
, &bus
);
2157 r
= bus_call_method(bus
, bus_systemd_mgr
, "GetDefaultTarget", &error
, &reply
, NULL
);
2159 return log_error_errno(r
, "Failed to get default target: %s", bus_error_message(&error
, r
));
2161 r
= sd_bus_message_read(reply
, "s", &name
);
2163 return bus_log_parse_error(r
);
2165 return free_and_strdup_warn(ret_name
, name
);
2169 static int get_default(int argc
, char *argv
[], void *userdata
) {
2170 _cleanup_free_
char *name
= NULL
;
2173 r
= determine_default(&name
);
2177 printf("%s\n", name
);
2179 emit_cmdline_warning();
2184 static int set_default(int argc
, char *argv
[], void *userdata
) {
2185 _cleanup_free_
char *unit
= NULL
;
2186 UnitFileChange
*changes
= NULL
;
2187 size_t n_changes
= 0;
2193 r
= unit_name_mangle_with_suffix(argv
[1], "set-default",
2194 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
2197 return log_error_errno(r
, "Failed to mangle unit name: %m");
2199 if (install_client_side()) {
2200 r
= unit_file_set_default(arg_scope
, UNIT_FILE_FORCE
, arg_root
, unit
, &changes
, &n_changes
);
2201 unit_file_dump_changes(r
, "set default", changes
, n_changes
, arg_quiet
);
2206 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2207 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2210 polkit_agent_open_maybe();
2212 r
= acquire_bus(BUS_MANAGER
, &bus
);
2216 r
= bus_call_method(bus
, bus_systemd_mgr
, "SetDefaultTarget", &error
, &reply
, "sb", unit
, 1);
2218 return log_error_errno(r
, "Failed to set default target: %s", bus_error_message(&error
, r
));
2220 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
2224 /* Try to reload if enabled */
2226 r
= daemon_reload(argc
, argv
, userdata
);
2231 emit_cmdline_warning();
2234 _cleanup_free_
char *final
= NULL
;
2236 r
= determine_default(&final
);
2240 if (!streq(final
, unit
))
2241 log_notice("Note: \"%s\" is the default unit (possibly a runtime override).", final
);
2245 unit_file_changes_free(changes
, n_changes
);
2250 static int output_waiting_jobs(sd_bus
*bus
, Table
*table
, uint32_t id
, const char *method
, const char *prefix
) {
2251 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2252 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2253 const char *name
, *type
;
2259 r
= bus_call_method(bus
, bus_systemd_mgr
, method
, &error
, &reply
, "u", id
);
2261 return log_debug_errno(r
, "Failed to get waiting jobs for job %" PRIu32
, id
);
2263 r
= sd_bus_message_enter_container(reply
, 'a', "(usssoo)");
2265 return bus_log_parse_error(r
);
2267 while ((r
= sd_bus_message_read(reply
, "(usssoo)", &other_id
, &name
, &type
, NULL
, NULL
, NULL
)) > 0) {
2268 _cleanup_free_
char *row
= NULL
;
2271 if (asprintf(&row
, "%s %u (%s/%s)", prefix
, other_id
, name
, type
) < 0)
2274 rc
= table_add_many(table
,
2275 TABLE_STRING
, special_glyph(SPECIAL_GLYPH_TREE_RIGHT
),
2280 return table_log_add_error(r
);
2284 return bus_log_parse_error(r
);
2286 r
= sd_bus_message_exit_container(reply
);
2288 return bus_log_parse_error(r
);
2295 const char *name
, *type
, *state
;
2298 static int output_jobs_list(sd_bus
*bus
, const struct job_info
* jobs
, unsigned n
, bool skipped
) {
2299 _cleanup_(table_unrefp
) Table
*table
= NULL
;
2300 const struct job_info
*j
;
2301 const char *on
, *off
;
2304 assert(n
== 0 || jobs
);
2307 if (!arg_no_legend
) {
2308 on
= ansi_highlight_green();
2309 off
= ansi_normal();
2311 printf("%sNo jobs %s.%s\n", on
, skipped
? "listed" : "running", off
);
2316 (void) pager_open(arg_pager_flags
);
2318 table
= table_new("job", "unit", "type", "state");
2322 table_set_header(table
, !arg_no_legend
);
2324 table_set_width(table
, 0);
2326 (void) table_set_empty_string(table
, "-");
2328 for (j
= jobs
; j
< jobs
+ n
; j
++) {
2329 if (streq(j
->state
, "running"))
2330 on
= ansi_highlight();
2334 r
= table_add_many(table
,
2336 TABLE_STRING
, j
->name
,
2337 TABLE_SET_COLOR
, on
,
2338 TABLE_STRING
, j
->type
,
2339 TABLE_STRING
, j
->state
,
2340 TABLE_SET_COLOR
, on
);
2342 return table_log_add_error(r
);
2345 output_waiting_jobs(bus
, table
, j
->id
, "GetJobAfter", "\twaiting for job");
2346 if (arg_jobs_before
)
2347 output_waiting_jobs(bus
, table
, j
->id
, "GetJobBefore", "\tblocking job");
2350 r
= table_print(table
, NULL
);
2352 return log_error_errno(r
, "Failed to print the table: %m");
2354 if (!arg_no_legend
) {
2355 on
= ansi_highlight();
2356 off
= ansi_normal();
2358 printf("\n%s%u jobs listed%s.\n", on
, n
, off
);
2364 static bool output_show_job(struct job_info
*job
, char **patterns
) {
2365 return strv_fnmatch_or_empty(patterns
, job
->name
, FNM_NOESCAPE
);
2368 static int list_jobs(int argc
, char *argv
[], void *userdata
) {
2369 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2370 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2371 _cleanup_free_
struct job_info
*jobs
= NULL
;
2372 const char *name
, *type
, *state
;
2373 bool skipped
= false;
2380 r
= acquire_bus(BUS_MANAGER
, &bus
);
2384 r
= bus_call_method(bus
, bus_systemd_mgr
, "ListJobs", &error
, &reply
, NULL
);
2386 return log_error_errno(r
, "Failed to list jobs: %s", bus_error_message(&error
, r
));
2388 r
= sd_bus_message_enter_container(reply
, 'a', "(usssoo)");
2390 return bus_log_parse_error(r
);
2392 while ((r
= sd_bus_message_read(reply
, "(usssoo)", &id
, &name
, &type
, &state
, NULL
, NULL
)) > 0) {
2393 struct job_info job
= { id
, name
, type
, state
};
2395 if (!output_show_job(&job
, strv_skip(argv
, 1))) {
2400 if (!GREEDY_REALLOC(jobs
, size
, c
+ 1))
2406 return bus_log_parse_error(r
);
2408 r
= sd_bus_message_exit_container(reply
);
2410 return bus_log_parse_error(r
);
2412 (void) pager_open(arg_pager_flags
);
2414 return output_jobs_list(bus
, jobs
, c
, skipped
);
2417 static int cancel_job(int argc
, char *argv
[], void *userdata
) {
2423 return trivial_method(argc
, argv
, userdata
);
2425 r
= acquire_bus(BUS_MANAGER
, &bus
);
2429 polkit_agent_open_maybe();
2431 STRV_FOREACH(name
, strv_skip(argv
, 1)) {
2432 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2436 q
= safe_atou32(*name
, &id
);
2438 return log_error_errno(q
, "Failed to parse job id \"%s\": %m", *name
);
2440 q
= bus_call_method(bus
, bus_systemd_mgr
, "CancelJob", &error
, NULL
, "u", id
);
2442 log_error_errno(q
, "Failed to cancel job %"PRIu32
": %s", id
, bus_error_message(&error
, q
));
2451 static int need_daemon_reload(sd_bus
*bus
, const char *unit
) {
2452 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2456 /* We ignore all errors here, since this is used to show a
2459 /* We don't use unit_dbus_path_from_name() directly since we
2460 * don't want to load the unit if it isn't loaded. */
2462 r
= bus_call_method(bus
, bus_systemd_mgr
, "GetUnit", NULL
, &reply
, "s", unit
);
2466 r
= sd_bus_message_read(reply
, "o", &path
);
2470 r
= sd_bus_get_property_trivial(
2472 "org.freedesktop.systemd1",
2474 "org.freedesktop.systemd1.Unit",
2484 static void warn_unit_file_changed(const char *name
) {
2487 log_warning("%sWarning:%s The unit file, source configuration file or drop-ins of %s changed on disk. Run 'systemctl%s daemon-reload' to reload units.",
2488 ansi_highlight_red(),
2491 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user");
2494 static int unit_file_find_path(LookupPaths
*lp
, const char *unit_name
, char **ret_unit_path
) {
2500 STRV_FOREACH(p
, lp
->search_path
) {
2501 _cleanup_free_
char *path
= NULL
, *lpath
= NULL
;
2504 path
= path_join(*p
, unit_name
);
2508 r
= chase_symlinks(path
, arg_root
, 0, &lpath
, NULL
);
2514 return log_error_errno(r
, "Failed to access path \"%s\": %m", path
);
2517 *ret_unit_path
= TAKE_PTR(lpath
);
2523 *ret_unit_path
= NULL
;
2528 static int unit_find_template_path(
2529 const char *unit_name
,
2531 char **ret_fragment_path
,
2532 char **ret_template
) {
2534 _cleanup_free_
char *t
= NULL
, *f
= NULL
;
2537 /* Returns 1 if a fragment was found, 0 if not found, negative on error. */
2539 r
= unit_file_find_path(lp
, unit_name
, &f
);
2543 if (ret_fragment_path
)
2544 *ret_fragment_path
= TAKE_PTR(f
);
2546 *ret_template
= NULL
;
2547 return r
; /* found a real unit */
2550 r
= unit_name_template(unit_name
, &t
);
2552 if (ret_fragment_path
)
2553 *ret_fragment_path
= NULL
;
2555 *ret_template
= NULL
;
2557 return 0; /* not a template, does not exist */
2560 return log_error_errno(r
, "Failed to determine template name: %m");
2562 r
= unit_file_find_path(lp
, t
, ret_fragment_path
);
2567 *ret_template
= r
> 0 ? TAKE_PTR(t
) : NULL
;
2572 static int unit_find_paths(
2574 const char *unit_name
,
2576 bool force_client_side
,
2577 char **ret_fragment_path
,
2578 char ***ret_dropin_paths
) {
2580 _cleanup_strv_free_
char **dropins
= NULL
;
2581 _cleanup_free_
char *path
= NULL
;
2585 * Finds where the unit is defined on disk. Returns 0 if the unit is not found. Returns 1 if it is
2587 * - the path to the unit in *ret_frament_path, if it exists on disk,
2588 * - and a strv of existing drop-ins in *ret_dropin_paths, if the arg is not NULL and any dropins
2591 * Returns -ERFKILL if the unit is masked, and -EKEYREJECTED if the unit file could not be loaded for
2592 * some reason (the latter only applies if we are going through the service manager).
2596 assert(ret_fragment_path
);
2599 /* Go via the bus to acquire the path, unless we are explicitly told not to, or when the unit name is a template */
2600 if (!force_client_side
&&
2601 !install_client_side() &&
2602 !unit_name_is_valid(unit_name
, UNIT_NAME_TEMPLATE
)) {
2603 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2604 _cleanup_free_
char *load_state
= NULL
, *dbus_path
= NULL
;
2606 dbus_path
= unit_dbus_path_from_name(unit_name
);
2610 r
= sd_bus_get_property_string(
2612 "org.freedesktop.systemd1",
2614 "org.freedesktop.systemd1.Unit",
2619 return log_error_errno(r
, "Failed to get LoadState: %s", bus_error_message(&error
, r
));
2621 if (streq(load_state
, "masked"))
2623 if (streq(load_state
, "not-found")) {
2627 if (!STR_IN_SET(load_state
, "loaded", "bad-setting"))
2628 return -EKEYREJECTED
;
2630 r
= sd_bus_get_property_string(
2632 "org.freedesktop.systemd1",
2634 "org.freedesktop.systemd1.Unit",
2639 return log_error_errno(r
, "Failed to get FragmentPath: %s", bus_error_message(&error
, r
));
2641 if (ret_dropin_paths
) {
2642 r
= sd_bus_get_property_strv(
2644 "org.freedesktop.systemd1",
2646 "org.freedesktop.systemd1.Unit",
2651 return log_error_errno(r
, "Failed to get DropInPaths: %s", bus_error_message(&error
, r
));
2655 _cleanup_set_free_free_ Set
*names
= NULL
;
2657 if (!cached_name_map
) {
2658 r
= unit_file_build_name_map(lp
, NULL
, &cached_id_map
, &cached_name_map
, NULL
);
2663 r
= unit_file_find_fragment(cached_id_map
, cached_name_map
, unit_name
, &_path
, &names
);
2668 path
= strdup(_path
);
2673 if (ret_dropin_paths
) {
2674 r
= unit_file_find_dropin_paths(arg_root
, lp
->search_path
, NULL
,
2682 if (isempty(path
)) {
2683 *ret_fragment_path
= NULL
;
2686 *ret_fragment_path
= TAKE_PTR(path
);
2690 if (ret_dropin_paths
) {
2691 if (!strv_isempty(dropins
)) {
2692 *ret_dropin_paths
= TAKE_PTR(dropins
);
2695 *ret_dropin_paths
= NULL
;
2699 if (r
== 0 && !arg_force
)
2700 log_error("No files found for %s.", unit_name
);
2705 static int get_state_one_unit(sd_bus
*bus
, const char *name
, UnitActiveState
*active_state
) {
2706 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2707 _cleanup_free_
char *buf
= NULL
, *dbus_path
= NULL
;
2708 UnitActiveState state
;
2712 assert(active_state
);
2714 dbus_path
= unit_dbus_path_from_name(name
);
2718 r
= sd_bus_get_property_string(
2720 "org.freedesktop.systemd1",
2722 "org.freedesktop.systemd1.Unit",
2727 return log_error_errno(r
, "Failed to retrieve unit state: %s", bus_error_message(&error
, r
));
2729 state
= unit_active_state_from_string(buf
);
2731 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid unit state '%s' for: %s", buf
, name
);
2733 *active_state
= state
;
2737 static int unit_is_masked(sd_bus
*bus
, LookupPaths
*lp
, const char *name
) {
2738 _cleanup_free_
char *load_state
= NULL
;
2741 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
2742 _cleanup_free_
char *path
= NULL
;
2744 /* A template cannot be loaded, but it can be still masked, so
2745 * we need to use a different method. */
2747 r
= unit_file_find_path(lp
, name
, &path
);
2752 return null_or_empty_path(path
);
2755 r
= unit_load_state(bus
, name
, &load_state
);
2759 return streq(load_state
, "masked");
2762 static int check_triggering_units(sd_bus
*bus
, const char *name
) {
2763 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2764 _cleanup_free_
char *n
= NULL
, *dbus_path
= NULL
, *load_state
= NULL
;
2765 _cleanup_strv_free_
char **triggered_by
= NULL
;
2766 bool print_warning_label
= true;
2767 UnitActiveState active_state
;
2771 r
= unit_name_mangle(name
, 0, &n
);
2773 return log_error_errno(r
, "Failed to mangle unit name: %m");
2775 r
= unit_load_state(bus
, name
, &load_state
);
2779 if (streq(load_state
, "masked"))
2782 dbus_path
= unit_dbus_path_from_name(n
);
2786 r
= sd_bus_get_property_strv(
2788 "org.freedesktop.systemd1",
2790 "org.freedesktop.systemd1.Unit",
2795 return log_error_errno(r
, "Failed to get triggered by array of %s: %s", n
, bus_error_message(&error
, r
));
2797 STRV_FOREACH(i
, triggered_by
) {
2798 r
= get_state_one_unit(bus
, *i
, &active_state
);
2802 if (!IN_SET(active_state
, UNIT_ACTIVE
, UNIT_RELOADING
))
2805 if (print_warning_label
) {
2806 log_warning("Warning: Stopping %s, but it can still be activated by:", n
);
2807 print_warning_label
= false;
2810 log_warning(" %s", *i
);
2816 static const struct {
2817 const char *verb
; /* systemctl verb */
2818 const char *method
; /* Name of the specific D-Bus method */
2819 const char *job_type
; /* Job type when passing to the generic EnqueueUnitJob() method */
2820 } unit_actions
[] = {
2821 { "start", "StartUnit", "start" },
2822 { "stop", "StopUnit", "stop" },
2823 { "condstop", "StopUnit", "stop" }, /* legacy alias */
2824 { "reload", "ReloadUnit", "reload" },
2825 { "restart", "RestartUnit", "restart" },
2826 { "try-restart", "TryRestartUnit", "try-restart" },
2827 { "condrestart", "TryRestartUnit", "try-restart" }, /* legacy alias */
2828 { "reload-or-restart", "ReloadOrRestartUnit", "reload-or-restart" },
2829 { "try-reload-or-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" },
2830 { "reload-or-try-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2831 { "condreload", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2832 { "force-reload", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2835 static const char *verb_to_method(const char *verb
) {
2838 for (i
= 0; i
< ELEMENTSOF(unit_actions
); i
++)
2839 if (streq_ptr(unit_actions
[i
].verb
, verb
))
2840 return unit_actions
[i
].method
;
2845 static const char *verb_to_job_type(const char *verb
) {
2848 for (i
= 0; i
< ELEMENTSOF(unit_actions
); i
++)
2849 if (streq_ptr(unit_actions
[i
].verb
, verb
))
2850 return unit_actions
[i
].job_type
;
2855 static int start_unit_one(
2857 const char *method
, /* When using classic per-job bus methods */
2858 const char *job_type
, /* When using new-style EnqueueUnitJob() */
2861 sd_bus_error
*error
,
2863 BusWaitForUnits
*wu
) {
2865 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2875 log_debug("%s dbus call org.freedesktop.systemd1.Manager %s(%s, %s)",
2876 arg_dry_run
? "Would execute" : "Executing",
2877 method
, name
, mode
);
2882 if (arg_show_transaction
) {
2883 _cleanup_(sd_bus_error_free
) sd_bus_error enqueue_error
= SD_BUS_ERROR_NULL
;
2885 /* Use the new, fancy EnqueueUnitJob() API if the user wants us to print the transaction */
2886 r
= bus_call_method(
2893 name
, job_type
, mode
);
2895 if (!sd_bus_error_has_name(&enqueue_error
, SD_BUS_ERROR_UNKNOWN_METHOD
)) {
2896 (void) sd_bus_error_move(error
, &enqueue_error
);
2900 /* Hmm, the API is not yet available. Let's use the classic API instead (see below). */
2901 log_notice("--show-transaction not supported by this service manager, proceeding without.");
2906 r
= sd_bus_message_read(reply
, "uosos", &id
, &path
, &u
, NULL
, &jt
);
2908 return bus_log_parse_error(r
);
2910 log_info("Enqueued anchor job %" PRIu32
" %s/%s.", id
, u
, jt
);
2912 r
= sd_bus_message_enter_container(reply
, 'a', "(uosos)");
2914 return bus_log_parse_error(r
);
2916 r
= sd_bus_message_read(reply
, "(uosos)", &id
, NULL
, &u
, NULL
, &jt
);
2918 return bus_log_parse_error(r
);
2922 log_info("Enqueued auxiliary job %" PRIu32
" %s/%s.", id
, u
, jt
);
2925 r
= sd_bus_message_exit_container(reply
);
2927 return bus_log_parse_error(r
);
2934 r
= bus_call_method(bus
, bus_systemd_mgr
, method
, error
, &reply
, "ss", name
, mode
);
2938 r
= sd_bus_message_read(reply
, "o", &path
);
2940 return bus_log_parse_error(r
);
2943 if (need_daemon_reload(bus
, name
) > 0)
2944 warn_unit_file_changed(name
);
2947 log_debug("Adding %s to the set", path
);
2948 r
= bus_wait_for_jobs_add(w
, path
);
2950 return log_error_errno(r
, "Failed to watch job for %s: %m", name
);
2954 r
= bus_wait_for_units_add_unit(wu
, name
, BUS_WAIT_FOR_INACTIVE
|BUS_WAIT_NO_JOB
, NULL
, NULL
);
2956 return log_error_errno(r
, "Failed to watch unit %s: %m", name
);
2962 /* There's always a fallback possible for legacy actions. */
2963 if (arg_action
!= ACTION_SYSTEMCTL
)
2966 log_error_errno(r
, "Failed to %s %s: %s", job_type
, name
, bus_error_message(error
, r
));
2968 if (!sd_bus_error_has_name(error
, BUS_ERROR_NO_SUCH_UNIT
) &&
2969 !sd_bus_error_has_name(error
, BUS_ERROR_UNIT_MASKED
) &&
2970 !sd_bus_error_has_name(error
, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE
))
2971 log_error("See %s logs and 'systemctl%s status%s %s' for details.",
2972 arg_scope
== UNIT_FILE_SYSTEM
? "system" : "user",
2973 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user",
2974 name
[0] == '-' ? " --" : "",
2980 static const struct {
2984 } action_table
[_ACTION_MAX
] = {
2985 [ACTION_HALT
] = { SPECIAL_HALT_TARGET
, "halt", "replace-irreversibly" },
2986 [ACTION_POWEROFF
] = { SPECIAL_POWEROFF_TARGET
, "poweroff", "replace-irreversibly" },
2987 [ACTION_REBOOT
] = { SPECIAL_REBOOT_TARGET
, "reboot", "replace-irreversibly" },
2988 [ACTION_KEXEC
] = { SPECIAL_KEXEC_TARGET
, "kexec", "replace-irreversibly" },
2989 [ACTION_RUNLEVEL2
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
2990 [ACTION_RUNLEVEL3
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
2991 [ACTION_RUNLEVEL4
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
2992 [ACTION_RUNLEVEL5
] = { SPECIAL_GRAPHICAL_TARGET
, NULL
, "isolate" },
2993 [ACTION_RESCUE
] = { SPECIAL_RESCUE_TARGET
, "rescue", "isolate" },
2994 [ACTION_EMERGENCY
] = { SPECIAL_EMERGENCY_TARGET
, "emergency", "isolate" },
2995 [ACTION_DEFAULT
] = { SPECIAL_DEFAULT_TARGET
, "default", "isolate" },
2996 [ACTION_EXIT
] = { SPECIAL_EXIT_TARGET
, "exit", "replace-irreversibly" },
2997 [ACTION_SUSPEND
] = { SPECIAL_SUSPEND_TARGET
, "suspend", "replace-irreversibly" },
2998 [ACTION_HIBERNATE
] = { SPECIAL_HIBERNATE_TARGET
, "hibernate", "replace-irreversibly" },
2999 [ACTION_HYBRID_SLEEP
] = { SPECIAL_HYBRID_SLEEP_TARGET
, "hybrid-sleep", "replace-irreversibly" },
3000 [ACTION_SUSPEND_THEN_HIBERNATE
] = { SPECIAL_SUSPEND_THEN_HIBERNATE_TARGET
, "suspend-then-hibernate", "replace-irreversibly" },
3003 static enum action
verb_to_action(const char *verb
) {
3006 for (i
= 0; i
< _ACTION_MAX
; i
++)
3007 if (streq_ptr(action_table
[i
].verb
, verb
))
3010 return _ACTION_INVALID
;
3013 static const char** make_extra_args(const char *extra_args
[static 4]) {
3018 if (arg_scope
!= UNIT_FILE_SYSTEM
)
3019 extra_args
[n
++] = "--user";
3021 if (arg_transport
== BUS_TRANSPORT_REMOTE
) {
3022 extra_args
[n
++] = "-H";
3023 extra_args
[n
++] = arg_host
;
3024 } else if (arg_transport
== BUS_TRANSPORT_MACHINE
) {
3025 extra_args
[n
++] = "-M";
3026 extra_args
[n
++] = arg_host
;
3028 assert(arg_transport
== BUS_TRANSPORT_LOCAL
);
3030 extra_args
[n
] = NULL
;
3034 static int start_unit(int argc
, char *argv
[], void *userdata
) {
3035 _cleanup_(bus_wait_for_units_freep
) BusWaitForUnits
*wu
= NULL
;
3036 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
3037 const char *method
, *job_type
, *mode
, *one_name
, *suffix
= NULL
;
3038 _cleanup_free_
char **stopped_units
= NULL
; /* Do not use _cleanup_strv_free_ */
3039 _cleanup_strv_free_
char **names
= NULL
;
3040 int r
, ret
= EXIT_SUCCESS
;
3044 if (arg_wait
&& !STR_IN_SET(argv
[0], "start", "restart"))
3045 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3046 "--wait may only be used with the 'start' or 'restart' commands.");
3048 /* we cannot do sender tracking on the private bus, so we need the full
3049 * one for RefUnit to implement --wait */
3050 r
= acquire_bus(arg_wait
? BUS_FULL
: BUS_MANAGER
, &bus
);
3054 ask_password_agent_open_maybe();
3055 polkit_agent_open_maybe();
3057 if (arg_action
== ACTION_SYSTEMCTL
) {
3060 action
= verb_to_action(argv
[0]);
3062 if (action
!= _ACTION_INVALID
) {
3063 /* A command in style "systemctl reboot", "systemctl poweroff", … */
3064 method
= "StartUnit";
3066 mode
= action_table
[action
].mode
;
3067 one_name
= action_table
[action
].target
;
3069 if (streq(argv
[0], "isolate")) {
3070 /* A "systemctl isolate <unit1> <unit2> …" command */
3071 method
= "StartUnit";
3076 /* A command in style of "systemctl start <unit1> <unit2> …", "sysemctl stop <unit1> <unit2> …" and so on */
3077 method
= verb_to_method(argv
[0]);
3078 job_type
= verb_to_job_type(argv
[0]);
3079 mode
= arg_job_mode
;
3084 /* A SysV legacy command such as "halt", "reboot", "poweroff", … */
3085 assert(arg_action
>= 0 && arg_action
< _ACTION_MAX
);
3086 assert(action_table
[arg_action
].target
);
3087 assert(action_table
[arg_action
].mode
);
3089 method
= "StartUnit";
3091 mode
= action_table
[arg_action
].mode
;
3092 one_name
= action_table
[arg_action
].target
;
3096 names
= strv_new(one_name
);
3102 r
= expand_names(bus
, strv_skip(argv
, 1), suffix
, &names
, &expanded
);
3104 return log_error_errno(r
, "Failed to expand names: %m");
3106 if (!arg_all
&& expanded
&& streq(job_type
, "start") && !arg_quiet
) {
3107 log_warning("Warning: %ssystemctl start called with a glob pattern.%s",
3108 ansi_highlight_red(),
3110 log_notice("Hint: unit globs expand to loaded units, so start will usually have no effect.\n"
3111 " Passing --all will also load units which are pulled in by other units.\n"
3112 " See systemctl(1) for more details.");
3116 if (!arg_no_block
) {
3117 r
= bus_wait_for_jobs_new(bus
, &w
);
3119 return log_error_errno(r
, "Could not watch jobs: %m");
3123 r
= bus_call_method_async(bus
, NULL
, bus_systemd_mgr
, "Subscribe", NULL
, NULL
, NULL
);
3125 return log_error_errno(r
, "Failed to enable subscription: %m");
3127 r
= bus_wait_for_units_new(bus
, &wu
);
3129 return log_error_errno(r
, "Failed to allocate unit watch context: %m");
3132 STRV_FOREACH(name
, names
) {
3133 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3135 r
= start_unit_one(bus
, method
, job_type
, *name
, mode
, &error
, w
, wu
);
3136 if (ret
== EXIT_SUCCESS
&& r
< 0)
3137 ret
= translate_bus_error_to_exit_status(r
, &error
);
3139 if (r
>= 0 && streq(method
, "StopUnit")) {
3140 r
= strv_push(&stopped_units
, *name
);
3146 if (!arg_no_block
) {
3147 const char* extra_args
[4];
3149 r
= bus_wait_for_jobs(w
, arg_quiet
, make_extra_args(extra_args
));
3153 /* When stopping units, warn if they can still be triggered by
3154 * another active unit (socket, path, timer) */
3156 STRV_FOREACH(name
, stopped_units
)
3157 (void) check_triggering_units(bus
, *name
);
3161 r
= bus_wait_for_units_run(wu
);
3163 return log_error_errno(r
, "Failed to wait for units: %m");
3164 if (r
== BUS_WAIT_FAILURE
&& ret
== EXIT_SUCCESS
)
3172 static int logind_set_wall_message(void) {
3173 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3175 _cleanup_free_
char *m
= NULL
;
3178 r
= acquire_bus(BUS_FULL
, &bus
);
3182 m
= strv_join(arg_wall
, " ");
3186 log_debug("%s wall message \"%s\".", arg_dry_run
? "Would set" : "Setting", m
);
3190 r
= bus_call_method(bus
, bus_login_mgr
, "SetWallMessage", &error
, NULL
, "sb", m
, !arg_no_wall
);
3192 return log_warning_errno(r
, "Failed to set wall message, ignoring: %s", bus_error_message(&error
, r
));
3197 /* Ask systemd-logind, which might grant access to unprivileged users through polkit */
3198 static int logind_reboot(enum action a
) {
3200 static const struct {
3202 const char *description
;
3203 } actions
[_ACTION_MAX
] = {
3204 [ACTION_POWEROFF
] = { "PowerOff", "power off system" },
3205 [ACTION_REBOOT
] = { "Reboot", "reboot system" },
3206 [ACTION_HALT
] = { "Halt", "halt system" },
3207 [ACTION_SUSPEND
] = { "Suspend", "suspend system" },
3208 [ACTION_HIBERNATE
] = { "Hibernate", "hibernate system" },
3209 [ACTION_HYBRID_SLEEP
] = { "HybridSleep", "put system into hybrid sleep" },
3210 [ACTION_SUSPEND_THEN_HIBERNATE
] = { "SuspendThenHibernate", "suspend system, hibernate later" },
3213 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3217 if (a
< 0 || a
>= _ACTION_MAX
|| !actions
[a
].method
)
3220 r
= acquire_bus(BUS_FULL
, &bus
);
3224 polkit_agent_open_maybe();
3225 (void) logind_set_wall_message();
3227 log_debug("%s org.freedesktop.login1.Manager %s dbus call.", arg_dry_run
? "Would execute" : "Executing", actions
[a
].method
);
3232 r
= bus_call_method(bus
, bus_login_mgr
, actions
[a
].method
, &error
, NULL
, "b", arg_ask_password
);
3234 return log_error_errno(r
, "Failed to %s via logind: %s", actions
[a
].description
, bus_error_message(&error
, r
));
3242 static int logind_check_inhibitors(enum action a
) {
3244 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
3245 _cleanup_strv_free_
char **sessions
= NULL
;
3246 const char *what
, *who
, *why
, *mode
;
3253 if (arg_ignore_inhibitors
|| arg_force
> 0)
3265 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
3268 r
= acquire_bus(BUS_FULL
, &bus
);
3272 r
= bus_call_method(bus
, bus_login_mgr
, "ListInhibitors", NULL
, &reply
, NULL
);
3274 /* If logind is not around, then there are no inhibitors... */
3277 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssuu)");
3279 return bus_log_parse_error(r
);
3281 while ((r
= sd_bus_message_read(reply
, "(ssssuu)", &what
, &who
, &why
, &mode
, &uid
, &pid
)) > 0) {
3282 _cleanup_free_
char *comm
= NULL
, *user
= NULL
;
3283 _cleanup_strv_free_
char **sv
= NULL
;
3285 if (!streq(mode
, "block"))
3288 sv
= strv_split(what
, ":");
3292 if (!pid_is_valid((pid_t
) pid
))
3293 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Invalid PID "PID_FMT
".", (pid_t
) pid
);
3295 if (!strv_contains(sv
,
3300 ACTION_KEXEC
) ? "shutdown" : "sleep"))
3303 get_process_comm(pid
, &comm
);
3304 user
= uid_to_name(uid
);
3306 log_warning("Operation inhibited by \"%s\" (PID "PID_FMT
" \"%s\", user %s), reason is \"%s\".",
3307 who
, (pid_t
) pid
, strna(comm
), strna(user
), why
);
3312 return bus_log_parse_error(r
);
3314 r
= sd_bus_message_exit_container(reply
);
3316 return bus_log_parse_error(r
);
3318 /* Check for current sessions */
3319 sd_get_sessions(&sessions
);
3320 STRV_FOREACH(s
, sessions
) {
3321 _cleanup_free_
char *type
= NULL
, *tty
= NULL
, *seat
= NULL
, *user
= NULL
, *service
= NULL
, *class = NULL
;
3323 if (sd_session_get_uid(*s
, &uid
) < 0 || uid
== getuid())
3326 if (sd_session_get_class(*s
, &class) < 0 || !streq(class, "user"))
3329 if (sd_session_get_type(*s
, &type
) < 0 || !STR_IN_SET(type
, "x11", "wayland", "tty", "mir"))
3332 sd_session_get_tty(*s
, &tty
);
3333 sd_session_get_seat(*s
, &seat
);
3334 sd_session_get_service(*s
, &service
);
3335 user
= uid_to_name(uid
);
3337 log_warning("User %s is logged in on %s.", strna(user
), isempty(tty
) ? (isempty(seat
) ? strna(service
) : seat
) : tty
);
3344 log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'systemctl %s -i'.",
3345 action_table
[a
].verb
);
3353 static int prepare_firmware_setup(void) {
3355 if (!arg_firmware_setup
)
3359 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3363 r
= acquire_bus(BUS_FULL
, &bus
);
3367 r
= bus_call_method(bus
, bus_login_mgr
, "SetRebootToFirmwareSetup", &error
, NULL
, "b", true);
3369 return log_error_errno(r
, "Cannot indicate to EFI to boot into setup mode: %s", bus_error_message(&error
, r
));
3373 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3374 "Booting into firmware setup not supported.");
3378 static int prepare_boot_loader_menu(void) {
3380 if (arg_boot_loader_menu
== USEC_INFINITY
)
3384 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3388 r
= acquire_bus(BUS_FULL
, &bus
);
3392 r
= bus_call_method(bus
, bus_login_mgr
, "SetRebootToBootLoaderMenu", &error
, NULL
, "t", arg_boot_loader_menu
);
3394 return log_error_errno(r
, "Cannot indicate to boot loader to enter boot loader entry menu: %s", bus_error_message(&error
, r
));
3398 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3399 "Booting into boot loader menu not supported.");
3403 static int prepare_boot_loader_entry(void) {
3405 if (!arg_boot_loader_entry
)
3409 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3413 r
= acquire_bus(BUS_FULL
, &bus
);
3417 r
= bus_call_method(bus
, bus_login_mgr
, "SetRebootToBootLoaderEntry", &error
, NULL
, "s", arg_boot_loader_entry
);
3419 return log_error_errno(r
, "Cannot set boot into loader entry '%s': %s", arg_boot_loader_entry
, bus_error_message(&error
, r
));
3423 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3424 "Booting into boot loader entry not supported.");
3428 static int load_kexec_kernel(void) {
3429 _cleanup_(boot_config_free
) BootConfig config
= {};
3430 _cleanup_free_
char *kernel
= NULL
, *initrd
= NULL
, *options
= NULL
;
3435 if (kexec_loaded()) {
3436 log_debug("Kexec kernel already loaded.");
3440 if (access(KEXEC
, X_OK
) < 0)
3441 return log_error_errno(errno
, KEXEC
" is not available: %m");
3443 r
= boot_entries_load_config_auto(NULL
, NULL
, &config
);
3445 /* The call doesn't log about ENOKEY, let's do so here. */
3446 return log_error_errno(r
,
3447 "No kexec kernel loaded and autodetection failed.\n%s",
3449 ? "Cannot automatically load kernel: ESP partition mount point not found."
3450 : "Automatic loading works only on systems booted with EFI.");
3454 e
= boot_config_default_entry(&config
);
3456 return log_error_errno(SYNTHETIC_ERRNO(ENOENT
),
3457 "No boot loader entry suitable as default, refusing to guess.");
3459 log_debug("Found default boot loader entry in file \"%s\"", e
->path
);
3462 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3463 "Boot entry does not refer to Linux kernel, which is not supported currently.");
3464 if (strv_length(e
->initrd
) > 1)
3465 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3466 "Boot entry specifies multiple initrds, which is not supported currently.");
3468 kernel
= path_join(e
->root
, e
->kernel
);
3472 if (!strv_isempty(e
->initrd
)) {
3473 initrd
= path_join(e
->root
, e
->initrd
[0]);
3478 options
= strv_join(e
->options
, " ");
3482 log_full(arg_quiet
? LOG_DEBUG
: LOG_INFO
,
3483 "%s "KEXEC
" --load \"%s\" --append \"%s\"%s%s%s",
3484 arg_dry_run
? "Would run" : "Running",
3487 initrd
? " --initrd \"" : NULL
, strempty(initrd
), initrd
? "\"" : "");
3491 r
= safe_fork("(kexec)", FORK_WAIT
|FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
, &pid
);
3495 const char* const args
[] = {
3498 "--append", options
,
3499 initrd
? "--initrd" : NULL
, initrd
,
3504 execv(args
[0], (char * const *) args
);
3505 _exit(EXIT_FAILURE
);
3511 static int set_exit_code(uint8_t code
) {
3512 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3516 r
= acquire_bus(BUS_MANAGER
, &bus
);
3520 r
= bus_call_method(bus
, bus_systemd_mgr
, "SetExitCode", &error
, NULL
, "y", code
);
3522 return log_error_errno(r
, "Failed to set exit code: %s", bus_error_message(&error
, r
));
3527 static int start_special(int argc
, char *argv
[], void *userdata
) {
3530 bool termination_action
; /* an action that terminates the manager,
3531 * can be performed also by signal. */
3535 a
= verb_to_action(argv
[0]);
3537 r
= logind_check_inhibitors(a
);
3541 if (arg_force
>= 2) {
3547 r
= prepare_firmware_setup();
3551 r
= prepare_boot_loader_menu();
3555 r
= prepare_boot_loader_entry();
3559 if (a
== ACTION_REBOOT
&& argc
> 1) {
3560 r
= update_reboot_parameter_and_warn(argv
[1], false);
3564 } else if (a
== ACTION_KEXEC
) {
3565 r
= load_kexec_kernel();
3566 if (r
< 0 && arg_force
>= 1)
3567 log_notice("Failed to load kexec kernel, continuing without.");
3571 } else if (a
== ACTION_EXIT
&& argc
> 1) {
3574 /* If the exit code is not given on the command line,
3575 * don't reset it to zero: just keep it as it might
3576 * have been set previously. */
3578 r
= safe_atou8(argv
[1], &code
);
3580 return log_error_errno(r
, "Invalid exit code.");
3582 r
= set_exit_code(code
);
3587 termination_action
= IN_SET(a
,
3591 if (termination_action
&& arg_force
>= 2)
3594 if (arg_force
>= 1 &&
3595 (termination_action
|| IN_SET(a
, ACTION_KEXEC
, ACTION_EXIT
)))
3596 r
= trivial_method(argc
, argv
, userdata
);
3598 /* First try logind, to allow authentication with polkit */
3605 ACTION_HYBRID_SLEEP
,
3606 ACTION_SUSPEND_THEN_HIBERNATE
)) {
3608 r
= logind_reboot(a
);
3611 if (IN_SET(r
, -EOPNOTSUPP
, -EINPROGRESS
))
3612 /* requested operation is not supported or already in progress */
3615 /* On all other errors, try low-level operation. In order to minimize the difference between
3616 * operation with and without logind, we explicitly enable non-blocking mode for this, as
3617 * logind's shutdown operations are always non-blocking. */
3619 arg_no_block
= true;
3621 } else if (IN_SET(a
, ACTION_EXIT
, ACTION_KEXEC
))
3622 /* Since exit/kexec are so close in behaviour to power-off/reboot, let's also make them
3623 * asynchronous, in order to not confuse the user needlessly with unexpected behaviour. */
3624 arg_no_block
= true;
3626 r
= start_unit(argc
, argv
, userdata
);
3629 if (termination_action
&& arg_force
< 2 &&
3630 IN_SET(r
, -ENOENT
, -ETIMEDOUT
))
3631 log_notice("It is possible to perform action directly, see discussion of --force --force in man:systemctl(1).");
3636 static int start_system_special(int argc
, char *argv
[], void *userdata
) {
3637 /* Like start_special above, but raises an error when running in user mode */
3639 if (arg_scope
!= UNIT_FILE_SYSTEM
)
3640 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3641 "Bad action for %s mode.",
3642 arg_scope
== UNIT_FILE_GLOBAL
? "--global" : "--user");
3644 return start_special(argc
, argv
, userdata
);
3647 static int check_unit_generic(int code
, const UnitActiveState good_states
[], int nb_states
, char **args
) {
3648 _cleanup_strv_free_
char **names
= NULL
;
3649 UnitActiveState active_state
;
3655 r
= acquire_bus(BUS_MANAGER
, &bus
);
3659 r
= expand_names(bus
, args
, NULL
, &names
, NULL
);
3661 return log_error_errno(r
, "Failed to expand names: %m");
3663 STRV_FOREACH(name
, names
) {
3664 r
= get_state_one_unit(bus
, *name
, &active_state
);
3669 puts(unit_active_state_to_string(active_state
));
3671 for (i
= 0; i
< nb_states
; ++i
)
3672 if (good_states
[i
] == active_state
)
3676 /* use the given return code for the case that we won't find
3677 * any unit which matches the list */
3678 return found
? 0 : code
;
3681 static int check_unit_active(int argc
, char *argv
[], void *userdata
) {
3682 static const UnitActiveState states
[] = {
3687 /* According to LSB: 3, "program is not running" */
3688 return check_unit_generic(EXIT_PROGRAM_NOT_RUNNING
, states
, ELEMENTSOF(states
), strv_skip(argv
, 1));
3691 static int check_unit_failed(int argc
, char *argv
[], void *userdata
) {
3692 static const UnitActiveState states
[] = {
3696 return check_unit_generic(EXIT_PROGRAM_DEAD_AND_PID_EXISTS
, states
, ELEMENTSOF(states
), strv_skip(argv
, 1));
3699 static int kill_unit(int argc
, char *argv
[], void *userdata
) {
3700 _cleanup_strv_free_
char **names
= NULL
;
3701 char *kill_who
= NULL
, **name
;
3705 r
= acquire_bus(BUS_MANAGER
, &bus
);
3709 polkit_agent_open_maybe();
3712 arg_kill_who
= "all";
3714 /* --fail was specified */
3715 if (streq(arg_job_mode
, "fail"))
3716 kill_who
= strjoina(arg_kill_who
, "-fail");
3718 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
3720 return log_error_errno(r
, "Failed to expand names: %m");
3722 STRV_FOREACH(name
, names
) {
3723 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3725 q
= bus_call_method(
3731 "ssi", *name
, kill_who
? kill_who
: arg_kill_who
, arg_signal
);
3733 log_error_errno(q
, "Failed to kill unit %s: %s", *name
, bus_error_message(&error
, q
));
3742 static int clean_or_freeze_unit(int argc
, char *argv
[], void *userdata
) {
3743 _cleanup_(bus_wait_for_units_freep
) BusWaitForUnits
*w
= NULL
;
3744 _cleanup_strv_free_
char **names
= NULL
;
3745 int r
, ret
= EXIT_SUCCESS
;
3750 r
= acquire_bus(BUS_FULL
, &bus
);
3754 polkit_agent_open_maybe();
3756 if (!arg_clean_what
) {
3757 arg_clean_what
= strv_new("cache", "runtime");
3758 if (!arg_clean_what
)
3762 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
3764 return log_error_errno(r
, "Failed to expand names: %m");
3766 if (!arg_no_block
) {
3767 r
= bus_wait_for_units_new(bus
, &w
);
3769 return log_error_errno(r
, "Failed to allocate unit waiter: %m");
3772 if (streq(argv
[0], "clean"))
3773 method
= "CleanUnit";
3774 else if (streq(argv
[0], "freeze"))
3775 method
= "FreezeUnit";
3776 else if (streq(argv
[0], "thaw"))
3777 method
= "ThawUnit";
3779 STRV_FOREACH(name
, names
) {
3780 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3781 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
3784 /* If we shall wait for the cleaning to complete, let's add a ref on the unit first */
3785 r
= bus_call_method(bus
, bus_systemd_mgr
, "RefUnit", &error
, NULL
, "s", *name
);
3787 log_error_errno(r
, "Failed to add reference to unit %s: %s", *name
, bus_error_message(&error
, r
));
3788 if (ret
== EXIT_SUCCESS
)
3794 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, method
);
3796 return bus_log_create_error(r
);
3798 r
= sd_bus_message_append(m
, "s", *name
);
3800 return bus_log_create_error(r
);
3802 if (streq(method
, "CleanUnit")) {
3803 r
= sd_bus_message_append_strv(m
, arg_clean_what
);
3805 return bus_log_create_error(r
);
3808 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
3810 log_error_errno(r
, "Failed to %s unit %s: %s", argv
[0], *name
, bus_error_message(&error
, r
));
3811 if (ret
== EXIT_SUCCESS
) {
3818 r
= bus_wait_for_units_add_unit(w
, *name
, BUS_WAIT_REFFED
|BUS_WAIT_FOR_MAINTENANCE_END
, NULL
, NULL
);
3820 return log_error_errno(r
, "Failed to watch unit %s: %m", *name
);
3824 r
= bus_wait_for_units_run(w
);
3826 return log_error_errno(r
, "Failed to wait for units: %m");
3827 if (r
== BUS_WAIT_FAILURE
)
3833 typedef struct ExecStatusInfo
{
3841 usec_t start_timestamp
;
3842 usec_t exit_timestamp
;
3847 ExecCommandFlags flags
;
3849 LIST_FIELDS(struct ExecStatusInfo
, exec
);
3852 static void exec_status_info_free(ExecStatusInfo
*i
) {
3861 static int exec_status_info_deserialize(sd_bus_message
*m
, ExecStatusInfo
*i
, bool is_ex_prop
) {
3862 _cleanup_strv_free_
char **ex_opts
= NULL
;
3863 uint64_t start_timestamp
, exit_timestamp
, start_timestamp_monotonic
, exit_timestamp_monotonic
;
3866 int32_t code
, status
;
3872 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_STRUCT
, is_ex_prop
? "sasasttttuii" : "sasbttttuii");
3874 return bus_log_parse_error(r
);
3878 r
= sd_bus_message_read(m
, "s", &path
);
3880 return bus_log_parse_error(r
);
3882 i
->path
= strdup(path
);
3886 r
= sd_bus_message_read_strv(m
, &i
->argv
);
3888 return bus_log_parse_error(r
);
3890 r
= is_ex_prop
? sd_bus_message_read_strv(m
, &ex_opts
) : sd_bus_message_read(m
, "b", &ignore
);
3892 return bus_log_parse_error(r
);
3894 r
= sd_bus_message_read(m
,
3896 &start_timestamp
, &start_timestamp_monotonic
,
3897 &exit_timestamp
, &exit_timestamp_monotonic
,
3901 return bus_log_parse_error(r
);
3904 r
= exec_command_flags_from_strv(ex_opts
, &i
->flags
);
3906 return log_error_errno(r
, "Failed to convert strv to ExecCommandFlags: %m");
3908 i
->ignore
= FLAGS_SET(i
->flags
, EXEC_COMMAND_IGNORE_FAILURE
);
3912 i
->start_timestamp
= (usec_t
) start_timestamp
;
3913 i
->exit_timestamp
= (usec_t
) exit_timestamp
;
3914 i
->pid
= (pid_t
) pid
;
3918 r
= sd_bus_message_exit_container(m
);
3920 return bus_log_parse_error(r
);
3925 typedef struct UnitCondition
{
3932 LIST_FIELDS(struct UnitCondition
, conditions
);
3935 static void unit_condition_free(UnitCondition
*c
) {
3944 DEFINE_TRIVIAL_CLEANUP_FUNC(UnitCondition
*, unit_condition_free
);
3946 typedef struct UnitStatusInfo
{
3948 const char *load_state
;
3949 const char *active_state
;
3950 const char *freezer_state
;
3951 const char *sub_state
;
3952 const char *unit_file_state
;
3953 const char *unit_file_preset
;
3955 const char *description
;
3956 const char *following
;
3958 char **documentation
;
3960 const char *fragment_path
;
3961 const char *source_path
;
3962 const char *control_group
;
3964 char **dropin_paths
;
3966 char **triggered_by
;
3969 const char *load_error
;
3972 usec_t inactive_exit_timestamp
;
3973 usec_t inactive_exit_timestamp_monotonic
;
3974 usec_t active_enter_timestamp
;
3975 usec_t active_exit_timestamp
;
3976 usec_t inactive_enter_timestamp
;
3978 bool need_daemon_reload
;
3984 const char *status_text
;
3985 const char *pid_file
;
3989 usec_t start_timestamp
;
3990 usec_t exit_timestamp
;
3992 int exit_code
, exit_status
;
3994 const char *log_namespace
;
3996 usec_t condition_timestamp
;
3997 bool condition_result
;
3998 LIST_HEAD(UnitCondition
, conditions
);
4000 usec_t assert_timestamp
;
4002 bool failed_assert_trigger
;
4003 bool failed_assert_negate
;
4004 const char *failed_assert
;
4005 const char *failed_assert_parameter
;
4006 usec_t next_elapse_real
;
4007 usec_t next_elapse_monotonic
;
4010 unsigned n_accepted
;
4011 unsigned n_connections
;
4015 /* Pairs of type, path */
4019 const char *sysfs_path
;
4021 /* Mount, Automount */
4028 uint64_t memory_current
;
4029 uint64_t memory_min
;
4030 uint64_t memory_low
;
4031 uint64_t memory_high
;
4032 uint64_t memory_max
;
4033 uint64_t memory_swap_max
;
4034 uint64_t memory_limit
;
4035 uint64_t cpu_usage_nsec
;
4036 uint64_t tasks_current
;
4038 uint64_t ip_ingress_bytes
;
4039 uint64_t ip_egress_bytes
;
4040 uint64_t io_read_bytes
;
4041 uint64_t io_write_bytes
;
4043 uint64_t default_memory_min
;
4044 uint64_t default_memory_low
;
4046 LIST_HEAD(ExecStatusInfo
, exec
);
4049 static void unit_status_info_free(UnitStatusInfo
*info
) {
4053 strv_free(info
->documentation
);
4054 strv_free(info
->dropin_paths
);
4055 strv_free(info
->triggered_by
);
4056 strv_free(info
->triggers
);
4057 strv_free(info
->listen
);
4059 while ((c
= info
->conditions
)) {
4060 LIST_REMOVE(conditions
, info
->conditions
, c
);
4061 unit_condition_free(c
);
4064 while ((p
= info
->exec
)) {
4065 LIST_REMOVE(exec
, info
->exec
, p
);
4066 exec_status_info_free(p
);
4070 static void format_active_state(const char *active_state
, const char **active_on
, const char **active_off
) {
4071 if (streq_ptr(active_state
, "failed")) {
4072 *active_on
= ansi_highlight_red();
4073 *active_off
= ansi_normal();
4074 } else if (STRPTR_IN_SET(active_state
, "active", "reloading")) {
4075 *active_on
= ansi_highlight_green();
4076 *active_off
= ansi_normal();
4078 *active_on
= *active_off
= "";
4081 static void print_status_info(
4086 char since1
[FORMAT_TIMESTAMP_RELATIVE_MAX
], since2
[FORMAT_TIMESTAMP_MAX
];
4087 const char *s1
, *s2
, *active_on
, *active_off
, *on
, *off
, *ss
, *fs
;
4088 _cleanup_free_
char *formatted_path
= NULL
;
4097 /* This shows pretty information about a unit. See
4098 * print_property() for a low-level property printer */
4100 format_active_state(i
->active_state
, &active_on
, &active_off
);
4102 printf("%s%s%s %s", active_on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), active_off
, strna(i
->id
));
4104 if (i
->description
&& !streq_ptr(i
->id
, i
->description
))
4105 printf(" - %s", i
->description
);
4110 printf(" Follow: unit currently follows state of %s\n", i
->following
);
4112 if (STRPTR_IN_SET(i
->load_state
, "error", "not-found", "bad-setting")) {
4113 on
= ansi_highlight_red();
4114 off
= ansi_normal();
4118 path
= i
->source_path
?: i
->fragment_path
;
4119 if (path
&& terminal_urlify_path(path
, NULL
, &formatted_path
) >= 0)
4120 path
= formatted_path
;
4122 if (!isempty(i
->load_error
))
4123 printf(" Loaded: %s%s%s (Reason: %s)\n",
4124 on
, strna(i
->load_state
), off
, i
->load_error
);
4125 else if (path
&& !isempty(i
->unit_file_state
)) {
4126 bool show_preset
= !isempty(i
->unit_file_preset
) &&
4127 show_preset_for_state(unit_file_state_from_string(i
->unit_file_state
));
4129 printf(" Loaded: %s%s%s (%s; %s%s%s)\n",
4130 on
, strna(i
->load_state
), off
,
4133 show_preset
? "; vendor preset: " : "",
4134 show_preset
? i
->unit_file_preset
: "");
4137 printf(" Loaded: %s%s%s (%s)\n",
4138 on
, strna(i
->load_state
), off
, path
);
4140 printf(" Loaded: %s%s%s\n",
4141 on
, strna(i
->load_state
), off
);
4144 printf(" Transient: yes\n");
4146 if (!strv_isempty(i
->dropin_paths
)) {
4147 _cleanup_free_
char *dir
= NULL
;
4151 STRV_FOREACH(dropin
, i
->dropin_paths
) {
4152 _cleanup_free_
char *dropin_formatted
= NULL
;
4161 dir
= dirname_malloc(*dropin
);
4169 special_glyph(SPECIAL_GLYPH_TREE_RIGHT
));
4172 last
= ! (*(dropin
+ 1) && startswith(*(dropin
+ 1), dir
));
4174 if (terminal_urlify_path(*dropin
, basename(*dropin
), &dropin_formatted
) >= 0)
4175 df
= dropin_formatted
;
4179 printf("%s%s", df
, last
? "\n" : ", ");
4183 ss
= streq_ptr(i
->active_state
, i
->sub_state
) ? NULL
: i
->sub_state
;
4185 printf(" Active: %s%s (%s)%s",
4186 active_on
, strna(i
->active_state
), ss
, active_off
);
4188 printf(" Active: %s%s%s",
4189 active_on
, strna(i
->active_state
), active_off
);
4191 fs
= !isempty(i
->freezer_state
) && !streq(i
->freezer_state
, "running") ? i
->freezer_state
: NULL
;
4193 printf(" %s(%s)%s", ansi_highlight_yellow(), fs
, active_off
);
4195 if (!isempty(i
->result
) && !streq(i
->result
, "success"))
4196 printf(" (Result: %s)", i
->result
);
4198 timestamp
= STRPTR_IN_SET(i
->active_state
, "active", "reloading") ? i
->active_enter_timestamp
:
4199 STRPTR_IN_SET(i
->active_state
, "inactive", "failed") ? i
->inactive_enter_timestamp
:
4200 STRPTR_IN_SET(i
->active_state
, "activating") ? i
->inactive_exit_timestamp
:
4201 i
->active_exit_timestamp
;
4203 s1
= format_timestamp_relative(since1
, sizeof(since1
), timestamp
);
4204 s2
= format_timestamp(since2
, sizeof(since2
), timestamp
);
4207 printf(" since %s; %s\n", s2
, s1
);
4209 printf(" since %s\n", s2
);
4213 STRV_FOREACH(t
, i
->triggered_by
) {
4214 UnitActiveState state
= _UNIT_ACTIVE_STATE_INVALID
;
4216 (void) get_state_one_unit(bus
, *t
, &state
);
4217 format_active_state(unit_active_state_to_string(state
), &on
, &off
);
4219 printf("%s %s%s%s %s\n",
4220 t
== i
->triggered_by
? "TriggeredBy:" : " ",
4221 on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
,
4225 if (endswith(i
->id
, ".timer")) {
4226 char tstamp1
[FORMAT_TIMESTAMP_RELATIVE_MAX
],
4227 tstamp2
[FORMAT_TIMESTAMP_MAX
];
4228 const char *next_rel_time
, *next_time
;
4229 dual_timestamp nw
, next
= {i
->next_elapse_real
,
4230 i
->next_elapse_monotonic
};
4233 printf(" Trigger: ");
4235 dual_timestamp_get(&nw
);
4236 next_elapse
= calc_next_elapse(&nw
, &next
);
4237 next_rel_time
= format_timestamp_relative(tstamp1
, sizeof tstamp1
, next_elapse
);
4238 next_time
= format_timestamp(tstamp2
, sizeof tstamp2
, next_elapse
);
4240 if (next_time
&& next_rel_time
)
4241 printf("%s; %s\n", next_time
, next_rel_time
);
4246 STRV_FOREACH(t
, i
->triggers
) {
4247 UnitActiveState state
= _UNIT_ACTIVE_STATE_INVALID
;
4249 (void) get_state_one_unit(bus
, *t
, &state
);
4250 format_active_state(unit_active_state_to_string(state
), &on
, &off
);
4252 printf("%s %s%s%s %s\n",
4253 t
== i
->triggers
? " Triggers:" : " ",
4254 on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
,
4258 if (!i
->condition_result
&& i
->condition_timestamp
> 0) {
4262 s1
= format_timestamp_relative(since1
, sizeof(since1
), i
->condition_timestamp
);
4263 s2
= format_timestamp(since2
, sizeof(since2
), i
->condition_timestamp
);
4265 printf(" Condition: start %scondition failed%s at %s%s%s\n",
4266 ansi_highlight_yellow(), ansi_normal(),
4267 s2
, s1
? "; " : "", strempty(s1
));
4269 LIST_FOREACH(conditions
, c
, i
->conditions
)
4270 if (c
->tristate
< 0)
4273 LIST_FOREACH(conditions
, c
, i
->conditions
)
4274 if (c
->tristate
< 0)
4275 printf(" %s %s=%s%s%s was not met\n",
4276 --n
? special_glyph(SPECIAL_GLYPH_TREE_BRANCH
) : special_glyph(SPECIAL_GLYPH_TREE_RIGHT
),
4278 c
->trigger
? "|" : "",
4279 c
->negate
? "!" : "",
4283 if (!i
->assert_result
&& i
->assert_timestamp
> 0) {
4284 s1
= format_timestamp_relative(since1
, sizeof(since1
), i
->assert_timestamp
);
4285 s2
= format_timestamp(since2
, sizeof(since2
), i
->assert_timestamp
);
4287 printf(" Assert: start %sassertion failed%s at %s%s%s\n",
4288 ansi_highlight_red(), ansi_normal(),
4289 s2
, s1
? "; " : "", strempty(s1
));
4290 if (i
->failed_assert_trigger
)
4291 printf(" none of the trigger assertions were met\n");
4292 else if (i
->failed_assert
)
4293 printf(" %s=%s%s was not met\n",
4295 i
->failed_assert_negate
? "!" : "",
4296 i
->failed_assert_parameter
);
4300 printf(" Device: %s\n", i
->sysfs_path
);
4302 printf(" Where: %s\n", i
->where
);
4304 printf(" What: %s\n", i
->what
);
4306 STRV_FOREACH(t
, i
->documentation
) {
4307 _cleanup_free_
char *formatted
= NULL
;
4310 if (terminal_urlify(*t
, NULL
, &formatted
) >= 0)
4315 printf(" %*s %s\n", 9, t
== i
->documentation
? "Docs:" : "", q
);
4318 STRV_FOREACH_PAIR(t
, t2
, i
->listen
)
4319 printf(" %*s %s (%s)\n", 9, t
== i
->listen
? "Listen:" : "", *t2
, *t
);
4322 printf(" Accepted: %u; Connected: %u;", i
->n_accepted
, i
->n_connections
);
4324 printf(" Refused: %u", i
->n_refused
);
4328 LIST_FOREACH(exec
, p
, i
->exec
) {
4329 _cleanup_free_
char *argv
= NULL
;
4332 /* Only show exited processes here */
4336 /* Don't print ExecXYZEx= properties here since it will appear as a
4337 * duplicate of the non-Ex= variant. */
4338 if (endswith(p
->name
, "Ex"))
4341 argv
= strv_join(p
->argv
, " ");
4342 printf(" Process: "PID_FMT
" %s=%s ", p
->pid
, p
->name
, strna(argv
));
4344 good
= is_clean_exit(p
->code
, p
->status
, EXIT_CLEAN_DAEMON
, NULL
);
4346 on
= ansi_highlight_red();
4347 off
= ansi_normal();
4351 printf("%s(code=%s, ", on
, sigchld_code_to_string(p
->code
));
4353 if (p
->code
== CLD_EXITED
) {
4356 printf("status=%i", p
->status
);
4358 c
= exit_status_to_string(p
->status
, EXIT_STATUS_LIBC
| EXIT_STATUS_SYSTEMD
);
4363 printf("signal=%s", signal_to_string(p
->status
));
4365 printf(")%s\n", off
);
4367 if (i
->main_pid
== p
->pid
&&
4368 i
->start_timestamp
== p
->start_timestamp
&&
4369 i
->exit_timestamp
== p
->start_timestamp
)
4370 /* Let's not show this twice */
4373 if (p
->pid
== i
->control_pid
)
4377 if (i
->main_pid
> 0 || i
->control_pid
> 0) {
4378 if (i
->main_pid
> 0) {
4379 printf(" Main PID: "PID_FMT
, i
->main_pid
);
4383 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
4384 _cleanup_free_
char *comm
= NULL
;
4386 (void) get_process_comm(i
->main_pid
, &comm
);
4388 printf(" (%s)", comm
);
4391 } else if (i
->exit_code
> 0) {
4392 printf(" (code=%s, ", sigchld_code_to_string(i
->exit_code
));
4394 if (i
->exit_code
== CLD_EXITED
) {
4397 printf("status=%i", i
->exit_status
);
4399 c
= exit_status_to_string(i
->exit_status
,
4400 EXIT_STATUS_LIBC
| EXIT_STATUS_SYSTEMD
);
4405 printf("signal=%s", signal_to_string(i
->exit_status
));
4410 if (i
->control_pid
> 0) {
4411 _cleanup_free_
char *c
= NULL
;
4413 if (i
->main_pid
> 0)
4414 fputs("; Control PID: ", stdout
);
4416 fputs("Cntrl PID: ", stdout
); /* if first in column, abbreviated so it fits alignment */
4418 printf(PID_FMT
, i
->control_pid
);
4420 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
4421 (void) get_process_comm(i
->control_pid
, &c
);
4431 printf(" Status: \"%s\"\n", i
->status_text
);
4432 if (i
->status_errno
> 0)
4433 printf(" Error: %i (%s)\n", i
->status_errno
, strerror_safe(i
->status_errno
));
4435 if (i
->ip_ingress_bytes
!= (uint64_t) -1 && i
->ip_egress_bytes
!= (uint64_t) -1) {
4436 char buf_in
[FORMAT_BYTES_MAX
], buf_out
[FORMAT_BYTES_MAX
];
4438 printf(" IP: %s in, %s out\n",
4439 format_bytes(buf_in
, sizeof(buf_in
), i
->ip_ingress_bytes
),
4440 format_bytes(buf_out
, sizeof(buf_out
), i
->ip_egress_bytes
));
4443 if (i
->io_read_bytes
!= UINT64_MAX
&& i
->io_write_bytes
!= UINT64_MAX
) {
4444 char buf_in
[FORMAT_BYTES_MAX
], buf_out
[FORMAT_BYTES_MAX
];
4446 printf(" IO: %s read, %s written\n",
4447 format_bytes(buf_in
, sizeof(buf_in
), i
->io_read_bytes
),
4448 format_bytes(buf_out
, sizeof(buf_out
), i
->io_write_bytes
));
4451 if (i
->tasks_current
!= (uint64_t) -1) {
4452 printf(" Tasks: %" PRIu64
, i
->tasks_current
);
4454 if (i
->tasks_max
!= (uint64_t) -1)
4455 printf(" (limit: %" PRIu64
")\n", i
->tasks_max
);
4460 if (i
->memory_current
!= (uint64_t) -1) {
4461 char buf
[FORMAT_BYTES_MAX
];
4463 printf(" Memory: %s", format_bytes(buf
, sizeof(buf
), i
->memory_current
));
4465 if (i
->memory_min
> 0 || i
->memory_low
> 0 ||
4466 i
->memory_high
!= CGROUP_LIMIT_MAX
|| i
->memory_max
!= CGROUP_LIMIT_MAX
||
4467 i
->memory_swap_max
!= CGROUP_LIMIT_MAX
||
4468 i
->memory_limit
!= CGROUP_LIMIT_MAX
) {
4469 const char *prefix
= "";
4472 if (i
->memory_min
> 0) {
4473 printf("%smin: %s", prefix
, format_bytes_cgroup_protection(buf
, sizeof(buf
), i
->memory_min
));
4476 if (i
->memory_low
> 0) {
4477 printf("%slow: %s", prefix
, format_bytes_cgroup_protection(buf
, sizeof(buf
), i
->memory_low
));
4480 if (i
->memory_high
!= CGROUP_LIMIT_MAX
) {
4481 printf("%shigh: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_high
));
4484 if (i
->memory_max
!= CGROUP_LIMIT_MAX
) {
4485 printf("%smax: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_max
));
4488 if (i
->memory_swap_max
!= CGROUP_LIMIT_MAX
) {
4489 printf("%sswap max: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_swap_max
));
4492 if (i
->memory_limit
!= CGROUP_LIMIT_MAX
) {
4493 printf("%slimit: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_limit
));
4501 if (i
->cpu_usage_nsec
!= (uint64_t) -1) {
4502 char buf
[FORMAT_TIMESPAN_MAX
];
4503 printf(" CPU: %s\n", format_timespan(buf
, sizeof(buf
), i
->cpu_usage_nsec
/ NSEC_PER_USEC
, USEC_PER_MSEC
));
4506 if (i
->control_group
) {
4507 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
4508 static const char prefix
[] = " ";
4511 printf(" CGroup: %s\n", i
->control_group
);
4514 if (c
> sizeof(prefix
) - 1)
4515 c
-= sizeof(prefix
) - 1;
4519 r
= unit_show_processes(bus
, i
->id
, i
->control_group
, prefix
, c
, get_output_flags(), &error
);
4524 /* Fallback for older systemd versions where the GetUnitProcesses() call is not yet available */
4526 if (i
->main_pid
> 0)
4527 extra
[k
++] = i
->main_pid
;
4529 if (i
->control_pid
> 0)
4530 extra
[k
++] = i
->control_pid
;
4532 show_cgroup_and_extra(SYSTEMD_CGROUP_CONTROLLER
, i
->control_group
, prefix
, c
, extra
, k
, get_output_flags());
4534 log_warning_errno(r
, "Failed to dump process list for '%s', ignoring: %s",
4535 i
->id
, bus_error_message(&error
, r
));
4538 if (i
->id
&& arg_transport
== BUS_TRANSPORT_LOCAL
)
4539 show_journal_by_unit(
4545 i
->inactive_exit_timestamp_monotonic
,
4548 get_output_flags() | OUTPUT_BEGIN_NEWLINE
,
4549 SD_JOURNAL_LOCAL_ONLY
,
4550 arg_scope
== UNIT_FILE_SYSTEM
,
4553 if (i
->need_daemon_reload
)
4554 warn_unit_file_changed(i
->id
);
4557 static void show_unit_help(UnitStatusInfo
*i
) {
4562 if (!i
->documentation
) {
4563 log_info("Documentation for %s not known.", i
->id
);
4567 STRV_FOREACH(p
, i
->documentation
)
4568 if (startswith(*p
, "man:"))
4569 show_man_page(*p
+ 4, false);
4571 log_info("Can't show: %s", *p
);
4574 static int map_main_pid(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4575 UnitStatusInfo
*i
= userdata
;
4579 r
= sd_bus_message_read(m
, "u", &u
);
4583 i
->main_pid
= (pid_t
) u
;
4589 static int map_load_error(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4590 const char *message
, **p
= userdata
;
4593 r
= sd_bus_message_read(m
, "(ss)", NULL
, &message
);
4597 if (!isempty(message
))
4603 static int map_listen(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4604 const char *type
, *path
;
4605 char ***p
= userdata
;
4608 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
4612 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0) {
4614 r
= strv_extend(p
, type
);
4618 r
= strv_extend(p
, path
);
4625 r
= sd_bus_message_exit_container(m
);
4632 static int map_conditions(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4633 UnitStatusInfo
*i
= userdata
;
4634 const char *cond
, *param
;
4635 int trigger
, negate
;
4639 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sbbsi)");
4643 while ((r
= sd_bus_message_read(m
, "(sbbsi)", &cond
, &trigger
, &negate
, ¶m
, &state
)) > 0) {
4644 _cleanup_(unit_condition_freep
) UnitCondition
*c
= NULL
;
4646 c
= new(UnitCondition
, 1);
4650 *c
= (UnitCondition
) {
4651 .name
= strdup(cond
),
4652 .param
= strdup(param
),
4658 if (!c
->name
|| !c
->param
)
4661 LIST_PREPEND(conditions
, i
->conditions
, TAKE_PTR(c
));
4666 r
= sd_bus_message_exit_container(m
);
4673 static int map_asserts(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4674 UnitStatusInfo
*i
= userdata
;
4675 const char *cond
, *param
;
4676 int trigger
, negate
;
4680 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sbbsi)");
4684 while ((r
= sd_bus_message_read(m
, "(sbbsi)", &cond
, &trigger
, &negate
, ¶m
, &state
)) > 0) {
4685 if (state
< 0 && (!trigger
|| !i
->failed_assert
)) {
4686 i
->failed_assert
= cond
;
4687 i
->failed_assert_trigger
= trigger
;
4688 i
->failed_assert_negate
= negate
;
4689 i
->failed_assert_parameter
= param
;
4695 r
= sd_bus_message_exit_container(m
);
4702 static int map_exec(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4703 _cleanup_free_ ExecStatusInfo
*info
= NULL
;
4704 ExecStatusInfo
*last
;
4705 UnitStatusInfo
*i
= userdata
;
4706 bool is_ex_prop
= endswith(member
, "Ex");
4709 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, is_ex_prop
? "(sasasttttuii)" : "(sasbttttuii)");
4713 info
= new0(ExecStatusInfo
, 1);
4717 LIST_FIND_TAIL(exec
, i
->exec
, last
);
4719 while ((r
= exec_status_info_deserialize(m
, info
, is_ex_prop
)) > 0) {
4721 info
->name
= strdup(member
);
4725 LIST_INSERT_AFTER(exec
, i
->exec
, last
, info
);
4728 info
= new0(ExecStatusInfo
, 1);
4735 r
= sd_bus_message_exit_container(m
);
4742 static int print_property(const char *name
, const char *expected_value
, sd_bus_message
*m
, bool value
, bool all
) {
4744 const char *contents
;
4750 /* This is a low-level property printer, see
4751 * print_status_info() for the nicer output */
4753 r
= sd_bus_message_peek_type(m
, &bus_type
, &contents
);
4759 case SD_BUS_TYPE_INT32
:
4760 if (endswith(name
, "ActionExitStatus")) {
4763 r
= sd_bus_message_read_basic(m
, bus_type
, &i
);
4767 if (i
>= 0 && i
<= 255)
4768 bus_print_property_valuef(name
, expected_value
, value
, "%"PRIi32
, i
);
4770 bus_print_property_value(name
, expected_value
, value
, "[not set]");
4773 } else if (streq(name
, "NUMAPolicy")) {
4776 r
= sd_bus_message_read_basic(m
, bus_type
, &i
);
4780 bus_print_property_valuef(name
, expected_value
, value
, "%s", strna(mpol_to_string(i
)));
4786 case SD_BUS_TYPE_STRUCT
:
4788 if (contents
[0] == SD_BUS_TYPE_UINT32
&& streq(name
, "Job")) {
4791 r
= sd_bus_message_read(m
, "(uo)", &u
, NULL
);
4793 return bus_log_parse_error(r
);
4796 bus_print_property_valuef(name
, expected_value
, value
, "%"PRIu32
, u
);
4798 bus_print_property_value(name
, expected_value
, value
, "");
4802 } else if (contents
[0] == SD_BUS_TYPE_STRING
&& streq(name
, "Unit")) {
4805 r
= sd_bus_message_read(m
, "(so)", &s
, NULL
);
4807 return bus_log_parse_error(r
);
4809 if (all
|| !isempty(s
))
4810 bus_print_property_value(name
, expected_value
, value
, s
);
4814 } else if (contents
[0] == SD_BUS_TYPE_STRING
&& streq(name
, "LoadError")) {
4815 const char *a
= NULL
, *b
= NULL
;
4817 r
= sd_bus_message_read(m
, "(ss)", &a
, &b
);
4819 return bus_log_parse_error(r
);
4821 if (!isempty(a
) || !isempty(b
))
4822 bus_print_property_valuef(name
, expected_value
, value
, "%s \"%s\"", strempty(a
), strempty(b
));
4824 bus_print_property_value(name
, expected_value
, value
, "");
4828 } else if (STR_IN_SET(name
, "SystemCallFilter", "RestrictAddressFamilies")) {
4829 _cleanup_strv_free_
char **l
= NULL
;
4832 r
= sd_bus_message_enter_container(m
, 'r', "bas");
4834 return bus_log_parse_error(r
);
4836 r
= sd_bus_message_read(m
, "b", &whitelist
);
4838 return bus_log_parse_error(r
);
4840 r
= sd_bus_message_read_strv(m
, &l
);
4842 return bus_log_parse_error(r
);
4844 r
= sd_bus_message_exit_container(m
);
4846 return bus_log_parse_error(r
);
4848 if (all
|| whitelist
|| !strv_isempty(l
)) {
4853 fputs(name
, stdout
);
4860 STRV_FOREACH(i
, l
) {
4868 fputc('\n', stdout
);
4873 } else if (STR_IN_SET(name
, "SELinuxContext", "AppArmorProfile", "SmackProcessLabel")) {
4877 r
= sd_bus_message_read(m
, "(bs)", &ignore
, &s
);
4879 return bus_log_parse_error(r
);
4882 bus_print_property_valuef(name
, expected_value
, value
, "%s%s", ignore
? "-" : "", s
);
4884 bus_print_property_value(name
, expected_value
, value
, "");
4888 } else if (endswith(name
, "ExitStatus") && streq(contents
, "aiai")) {
4889 const int32_t *status
, *signal
;
4890 size_t n_status
, n_signal
, i
;
4892 r
= sd_bus_message_enter_container(m
, 'r', "aiai");
4894 return bus_log_parse_error(r
);
4896 r
= sd_bus_message_read_array(m
, 'i', (const void **) &status
, &n_status
);
4898 return bus_log_parse_error(r
);
4900 r
= sd_bus_message_read_array(m
, 'i', (const void **) &signal
, &n_signal
);
4902 return bus_log_parse_error(r
);
4904 r
= sd_bus_message_exit_container(m
);
4906 return bus_log_parse_error(r
);
4908 n_status
/= sizeof(int32_t);
4909 n_signal
/= sizeof(int32_t);
4911 if (all
|| n_status
> 0 || n_signal
> 0) {
4915 fputs(name
, stdout
);
4919 for (i
= 0; i
< n_status
; i
++) {
4925 printf("%"PRIi32
, status
[i
]);
4928 for (i
= 0; i
< n_signal
; i
++) {
4931 str
= signal_to_string((int) signal
[i
]);
4941 printf("%"PRIi32
, status
[i
]);
4944 fputc('\n', stdout
);
4951 case SD_BUS_TYPE_ARRAY
:
4953 if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "EnvironmentFiles")) {
4957 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sb)");
4959 return bus_log_parse_error(r
);
4961 while ((r
= sd_bus_message_read(m
, "(sb)", &path
, &ignore
)) > 0)
4962 bus_print_property_valuef(name
, expected_value
, value
, "%s (ignore_errors=%s)", path
, yes_no(ignore
));
4965 return bus_log_parse_error(r
);
4967 r
= sd_bus_message_exit_container(m
);
4969 return bus_log_parse_error(r
);
4973 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "Paths")) {
4974 const char *type
, *path
;
4976 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
4978 return bus_log_parse_error(r
);
4980 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0)
4981 bus_print_property_valuef(name
, expected_value
, value
, "%s (%s)", path
, type
);
4983 return bus_log_parse_error(r
);
4985 r
= sd_bus_message_exit_container(m
);
4987 return bus_log_parse_error(r
);
4991 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "Listen")) {
4992 const char *type
, *path
;
4994 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
4996 return bus_log_parse_error(r
);
4998 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0)
4999 bus_print_property_valuef(name
, expected_value
, value
, "%s (%s)", path
, type
);
5001 return bus_log_parse_error(r
);
5003 r
= sd_bus_message_exit_container(m
);
5005 return bus_log_parse_error(r
);
5009 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "TimersMonotonic")) {
5011 uint64_t v
, next_elapse
;
5013 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(stt)");
5015 return bus_log_parse_error(r
);
5017 while ((r
= sd_bus_message_read(m
, "(stt)", &base
, &v
, &next_elapse
)) > 0) {
5018 char timespan1
[FORMAT_TIMESPAN_MAX
] = "n/a", timespan2
[FORMAT_TIMESPAN_MAX
] = "n/a";
5020 (void) format_timespan(timespan1
, sizeof timespan1
, v
, 0);
5021 (void) format_timespan(timespan2
, sizeof timespan2
, next_elapse
, 0);
5023 bus_print_property_valuef(name
, expected_value
, value
,
5024 "{ %s=%s ; next_elapse=%s }", base
, timespan1
, timespan2
);
5027 return bus_log_parse_error(r
);
5029 r
= sd_bus_message_exit_container(m
);
5031 return bus_log_parse_error(r
);
5035 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "TimersCalendar")) {
5036 const char *base
, *spec
;
5037 uint64_t next_elapse
;
5039 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sst)");
5041 return bus_log_parse_error(r
);
5043 while ((r
= sd_bus_message_read(m
, "(sst)", &base
, &spec
, &next_elapse
)) > 0) {
5044 char timestamp
[FORMAT_TIMESTAMP_MAX
] = "n/a";
5046 (void) format_timestamp(timestamp
, sizeof(timestamp
), next_elapse
);
5047 bus_print_property_valuef(name
, expected_value
, value
,
5048 "{ %s=%s ; next_elapse=%s }", base
, spec
, timestamp
);
5051 return bus_log_parse_error(r
);
5053 r
= sd_bus_message_exit_container(m
);
5055 return bus_log_parse_error(r
);
5059 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& startswith(name
, "Exec")) {
5060 ExecStatusInfo info
= {};
5061 bool is_ex_prop
= endswith(name
, "Ex");
5063 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, is_ex_prop
? "(sasasttttuii)" : "(sasbttttuii)");
5065 return bus_log_parse_error(r
);
5067 while ((r
= exec_status_info_deserialize(m
, &info
, is_ex_prop
)) > 0) {
5068 char timestamp1
[FORMAT_TIMESTAMP_MAX
], timestamp2
[FORMAT_TIMESTAMP_MAX
];
5069 _cleanup_strv_free_
char **optv
= NULL
;
5070 _cleanup_free_
char *tt
, *o
= NULL
;
5072 tt
= strv_join(info
.argv
, " ");
5075 r
= exec_command_flags_to_strv(info
.flags
, &optv
);
5077 return log_error_errno(r
, "Failed to convert ExecCommandFlags to strv: %m");
5079 o
= strv_join(optv
, " ");
5081 bus_print_property_valuef(name
, expected_value
, value
,
5082 "{ path=%s ; argv[]=%s ; flags=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT
" ; code=%s ; status=%i%s%s }",
5086 strna(format_timestamp(timestamp1
, sizeof(timestamp1
), info
.start_timestamp
)),
5087 strna(format_timestamp(timestamp2
, sizeof(timestamp2
), info
.exit_timestamp
)),
5089 sigchld_code_to_string(info
.code
),
5091 info
.code
== CLD_EXITED
? "" : "/",
5092 strempty(info
.code
== CLD_EXITED
? NULL
: signal_to_string(info
.status
)));
5094 bus_print_property_valuef(name
, expected_value
, value
,
5095 "{ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT
" ; code=%s ; status=%i%s%s }",
5098 yes_no(info
.ignore
),
5099 strna(format_timestamp(timestamp1
, sizeof(timestamp1
), info
.start_timestamp
)),
5100 strna(format_timestamp(timestamp2
, sizeof(timestamp2
), info
.exit_timestamp
)),
5102 sigchld_code_to_string(info
.code
),
5104 info
.code
== CLD_EXITED
? "" : "/",
5105 strempty(info
.code
== CLD_EXITED
? NULL
: signal_to_string(info
.status
)));
5108 strv_free(info
.argv
);
5112 r
= sd_bus_message_exit_container(m
);
5114 return bus_log_parse_error(r
);
5118 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "DeviceAllow")) {
5119 const char *path
, *rwm
;
5121 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5123 return bus_log_parse_error(r
);
5125 while ((r
= sd_bus_message_read(m
, "(ss)", &path
, &rwm
)) > 0)
5126 bus_print_property_valuef(name
, expected_value
, value
, "%s %s", strna(path
), strna(rwm
));
5128 return bus_log_parse_error(r
);
5130 r
= sd_bus_message_exit_container(m
);
5132 return bus_log_parse_error(r
);
5136 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5137 STR_IN_SET(name
, "IODeviceWeight", "BlockIODeviceWeight")) {
5141 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5143 return bus_log_parse_error(r
);
5145 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &weight
)) > 0)
5146 bus_print_property_valuef(name
, expected_value
, value
, "%s %"PRIu64
, strna(path
), weight
);
5148 return bus_log_parse_error(r
);
5150 r
= sd_bus_message_exit_container(m
);
5152 return bus_log_parse_error(r
);
5156 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5157 (cgroup_io_limit_type_from_string(name
) >= 0 ||
5158 STR_IN_SET(name
, "BlockIOReadBandwidth", "BlockIOWriteBandwidth"))) {
5162 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5164 return bus_log_parse_error(r
);
5166 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &bandwidth
)) > 0)
5167 bus_print_property_valuef(name
, expected_value
, value
, "%s %"PRIu64
, strna(path
), bandwidth
);
5169 return bus_log_parse_error(r
);
5171 r
= sd_bus_message_exit_container(m
);
5173 return bus_log_parse_error(r
);
5177 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5178 streq(name
, "IODeviceLatencyTargetUSec")) {
5179 char ts
[FORMAT_TIMESPAN_MAX
];
5183 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5185 return bus_log_parse_error(r
);
5187 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &target
)) > 0)
5188 bus_print_property_valuef(name
, expected_value
, value
, "%s %s", strna(path
),
5189 format_timespan(ts
, sizeof(ts
), target
, 1));
5191 return bus_log_parse_error(r
);
5193 r
= sd_bus_message_exit_container(m
);
5195 return bus_log_parse_error(r
);
5199 } else if (contents
[0] == SD_BUS_TYPE_BYTE
&& streq(name
, "StandardInputData")) {
5200 _cleanup_free_
char *h
= NULL
;
5205 r
= sd_bus_message_read_array(m
, 'y', &p
, &sz
);
5207 return bus_log_parse_error(r
);
5209 n
= base64mem(p
, sz
, &h
);
5213 bus_print_property_value(name
, expected_value
, value
, h
);
5217 } else if (STR_IN_SET(name
, "IPAddressAllow", "IPAddressDeny")) {
5218 _cleanup_free_
char *addresses
= NULL
;
5220 r
= sd_bus_message_enter_container(m
, 'a', "(iayu)");
5222 return bus_log_parse_error(r
);
5225 _cleanup_free_
char *str
= NULL
;
5231 r
= sd_bus_message_enter_container(m
, 'r', "iayu");
5233 return bus_log_parse_error(r
);
5237 r
= sd_bus_message_read(m
, "i", &family
);
5239 return bus_log_parse_error(r
);
5241 r
= sd_bus_message_read_array(m
, 'y', &ap
, &an
);
5243 return bus_log_parse_error(r
);
5245 r
= sd_bus_message_read(m
, "u", &prefixlen
);
5247 return bus_log_parse_error(r
);
5249 r
= sd_bus_message_exit_container(m
);
5251 return bus_log_parse_error(r
);
5253 if (!IN_SET(family
, AF_INET
, AF_INET6
))
5256 if (an
!= FAMILY_ADDRESS_SIZE(family
))
5259 if (prefixlen
> FAMILY_ADDRESS_SIZE(family
) * 8)
5262 if (in_addr_prefix_to_string(family
, (union in_addr_union
*) ap
, prefixlen
, &str
) < 0)
5265 if (!strextend_with_separator(&addresses
, " ", str
, NULL
))
5269 r
= sd_bus_message_exit_container(m
);
5271 return bus_log_parse_error(r
);
5273 if (all
|| !isempty(addresses
))
5274 bus_print_property_value(name
, expected_value
, value
, strempty(addresses
));
5278 } else if (STR_IN_SET(name
, "BindPaths", "BindReadOnlyPaths")) {
5279 _cleanup_free_
char *paths
= NULL
;
5280 const char *source
, *dest
;
5284 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ssbt)");
5286 return bus_log_parse_error(r
);
5288 while ((r
= sd_bus_message_read(m
, "(ssbt)", &source
, &dest
, &ignore_enoent
, &rbind
)) > 0) {
5289 _cleanup_free_
char *str
= NULL
;
5291 if (isempty(source
))
5294 if (asprintf(&str
, "%s%s%s%s%s",
5295 ignore_enoent
? "-" : "",
5297 isempty(dest
) ? "" : ":",
5299 rbind
== MS_REC
? ":rbind" : "") < 0)
5302 if (!strextend_with_separator(&paths
, " ", str
, NULL
))
5306 return bus_log_parse_error(r
);
5308 r
= sd_bus_message_exit_container(m
);
5310 return bus_log_parse_error(r
);
5312 if (all
|| !isempty(paths
))
5313 bus_print_property_value(name
, expected_value
, value
, strempty(paths
));
5317 } else if (streq(name
, "TemporaryFileSystem")) {
5318 _cleanup_free_
char *paths
= NULL
;
5319 const char *target
, *option
;
5321 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5323 return bus_log_parse_error(r
);
5325 while ((r
= sd_bus_message_read(m
, "(ss)", &target
, &option
)) > 0) {
5326 _cleanup_free_
char *str
= NULL
;
5328 if (isempty(target
))
5331 if (asprintf(&str
, "%s%s%s", target
, isempty(option
) ? "" : ":", strempty(option
)) < 0)
5334 if (!strextend_with_separator(&paths
, " ", str
, NULL
))
5338 return bus_log_parse_error(r
);
5340 r
= sd_bus_message_exit_container(m
);
5342 return bus_log_parse_error(r
);
5344 if (all
|| !isempty(paths
))
5345 bus_print_property_value(name
, expected_value
, value
, strempty(paths
));
5349 } else if (streq(name
, "LogExtraFields")) {
5350 _cleanup_free_
char *fields
= NULL
;
5354 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "ay");
5356 return bus_log_parse_error(r
);
5358 while ((r
= sd_bus_message_read_array(m
, 'y', &p
, &sz
)) > 0) {
5359 _cleanup_free_
char *str
= NULL
;
5362 if (memchr(p
, 0, sz
))
5365 eq
= memchr(p
, '=', sz
);
5369 if (!journal_field_valid(p
, eq
- (const char*) p
, false))
5372 str
= malloc(sz
+ 1);
5379 if (!utf8_is_valid(str
))
5382 if (!strextend_with_separator(&fields
, " ", str
, NULL
))
5386 return bus_log_parse_error(r
);
5388 r
= sd_bus_message_exit_container(m
);
5390 return bus_log_parse_error(r
);
5392 if (all
|| !isempty(fields
))
5393 bus_print_property_value(name
, expected_value
, value
, strempty(fields
));
5396 } else if (contents
[0] == SD_BUS_TYPE_BYTE
&& STR_IN_SET(name
, "CPUAffinity", "NUMAMask", "AllowedCPUs", "AllowedMemoryNodes", "EffectiveCPUs", "EffectiveMemoryNodes")) {
5397 _cleanup_free_
char *affinity
= NULL
;
5398 _cleanup_(cpu_set_reset
) CPUSet set
= {};
5402 r
= sd_bus_message_read_array(m
, 'y', &a
, &n
);
5404 return bus_log_parse_error(r
);
5406 r
= cpu_set_from_dbus(a
, n
, &set
);
5408 return log_error_errno(r
, "Failed to deserialize %s: %m", name
);
5410 affinity
= cpu_set_to_range_string(&set
);
5414 bus_print_property_value(name
, expected_value
, value
, affinity
);
5425 typedef enum SystemctlShowMode
{
5426 SYSTEMCTL_SHOW_PROPERTIES
,
5427 SYSTEMCTL_SHOW_STATUS
,
5428 SYSTEMCTL_SHOW_HELP
,
5429 _SYSTEMCTL_SHOW_MODE_MAX
,
5430 _SYSTEMCTL_SHOW_MODE_INVALID
= -1,
5431 } SystemctlShowMode
;
5433 static const char* const systemctl_show_mode_table
[_SYSTEMCTL_SHOW_MODE_MAX
] = {
5434 [SYSTEMCTL_SHOW_PROPERTIES
] = "show",
5435 [SYSTEMCTL_SHOW_STATUS
] = "status",
5436 [SYSTEMCTL_SHOW_HELP
] = "help",
5439 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(systemctl_show_mode
, SystemctlShowMode
);
5441 static int show_one(
5445 SystemctlShowMode show_mode
,
5449 static const struct bus_properties_map property_map
[] = {
5450 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
5451 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
) },
5452 { "FreezerState", "s", NULL
, offsetof(UnitStatusInfo
, freezer_state
) },
5453 { "Documentation", "as", NULL
, offsetof(UnitStatusInfo
, documentation
) },
5456 { "Id", "s", NULL
, offsetof(UnitStatusInfo
, id
) },
5457 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
5458 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
) },
5459 { "FreezerState", "s", NULL
, offsetof(UnitStatusInfo
, freezer_state
) },
5460 { "SubState", "s", NULL
, offsetof(UnitStatusInfo
, sub_state
) },
5461 { "UnitFileState", "s", NULL
, offsetof(UnitStatusInfo
, unit_file_state
) },
5462 { "UnitFilePreset", "s", NULL
, offsetof(UnitStatusInfo
, unit_file_preset
) },
5463 { "Description", "s", NULL
, offsetof(UnitStatusInfo
, description
) },
5464 { "Following", "s", NULL
, offsetof(UnitStatusInfo
, following
) },
5465 { "Documentation", "as", NULL
, offsetof(UnitStatusInfo
, documentation
) },
5466 { "FragmentPath", "s", NULL
, offsetof(UnitStatusInfo
, fragment_path
) },
5467 { "SourcePath", "s", NULL
, offsetof(UnitStatusInfo
, source_path
) },
5468 { "ControlGroup", "s", NULL
, offsetof(UnitStatusInfo
, control_group
) },
5469 { "DropInPaths", "as", NULL
, offsetof(UnitStatusInfo
, dropin_paths
) },
5470 { "LoadError", "(ss)", map_load_error
, offsetof(UnitStatusInfo
, load_error
) },
5471 { "Result", "s", NULL
, offsetof(UnitStatusInfo
, result
) },
5472 { "TriggeredBy", "as", NULL
, offsetof(UnitStatusInfo
, triggered_by
) },
5473 { "Triggers", "as", NULL
, offsetof(UnitStatusInfo
, triggers
) },
5474 { "InactiveExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, inactive_exit_timestamp
) },
5475 { "InactiveExitTimestampMonotonic", "t", NULL
, offsetof(UnitStatusInfo
, inactive_exit_timestamp_monotonic
) },
5476 { "ActiveEnterTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, active_enter_timestamp
) },
5477 { "ActiveExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, active_exit_timestamp
) },
5478 { "InactiveEnterTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, inactive_enter_timestamp
) },
5479 { "NeedDaemonReload", "b", NULL
, offsetof(UnitStatusInfo
, need_daemon_reload
) },
5480 { "Transient", "b", NULL
, offsetof(UnitStatusInfo
, transient
) },
5481 { "ExecMainPID", "u", NULL
, offsetof(UnitStatusInfo
, main_pid
) },
5482 { "MainPID", "u", map_main_pid
, 0 },
5483 { "ControlPID", "u", NULL
, offsetof(UnitStatusInfo
, control_pid
) },
5484 { "StatusText", "s", NULL
, offsetof(UnitStatusInfo
, status_text
) },
5485 { "PIDFile", "s", NULL
, offsetof(UnitStatusInfo
, pid_file
) },
5486 { "StatusErrno", "i", NULL
, offsetof(UnitStatusInfo
, status_errno
) },
5487 { "ExecMainStartTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, start_timestamp
) },
5488 { "ExecMainExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, exit_timestamp
) },
5489 { "ExecMainCode", "i", NULL
, offsetof(UnitStatusInfo
, exit_code
) },
5490 { "ExecMainStatus", "i", NULL
, offsetof(UnitStatusInfo
, exit_status
) },
5491 { "LogNamespace", "s", NULL
, offsetof(UnitStatusInfo
, log_namespace
) },
5492 { "ConditionTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, condition_timestamp
) },
5493 { "ConditionResult", "b", NULL
, offsetof(UnitStatusInfo
, condition_result
) },
5494 { "Conditions", "a(sbbsi)", map_conditions
, 0 },
5495 { "AssertTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, assert_timestamp
) },
5496 { "AssertResult", "b", NULL
, offsetof(UnitStatusInfo
, assert_result
) },
5497 { "Asserts", "a(sbbsi)", map_asserts
, 0 },
5498 { "NextElapseUSecRealtime", "t", NULL
, offsetof(UnitStatusInfo
, next_elapse_real
) },
5499 { "NextElapseUSecMonotonic", "t", NULL
, offsetof(UnitStatusInfo
, next_elapse_monotonic
) },
5500 { "NAccepted", "u", NULL
, offsetof(UnitStatusInfo
, n_accepted
) },
5501 { "NConnections", "u", NULL
, offsetof(UnitStatusInfo
, n_connections
) },
5502 { "NRefused", "u", NULL
, offsetof(UnitStatusInfo
, n_refused
) },
5503 { "Accept", "b", NULL
, offsetof(UnitStatusInfo
, accept
) },
5504 { "Listen", "a(ss)", map_listen
, offsetof(UnitStatusInfo
, listen
) },
5505 { "SysFSPath", "s", NULL
, offsetof(UnitStatusInfo
, sysfs_path
) },
5506 { "Where", "s", NULL
, offsetof(UnitStatusInfo
, where
) },
5507 { "What", "s", NULL
, offsetof(UnitStatusInfo
, what
) },
5508 { "MemoryCurrent", "t", NULL
, offsetof(UnitStatusInfo
, memory_current
) },
5509 { "DefaultMemoryMin", "t", NULL
, offsetof(UnitStatusInfo
, default_memory_min
) },
5510 { "DefaultMemoryLow", "t", NULL
, offsetof(UnitStatusInfo
, default_memory_low
) },
5511 { "MemoryMin", "t", NULL
, offsetof(UnitStatusInfo
, memory_min
) },
5512 { "MemoryLow", "t", NULL
, offsetof(UnitStatusInfo
, memory_low
) },
5513 { "MemoryHigh", "t", NULL
, offsetof(UnitStatusInfo
, memory_high
) },
5514 { "MemoryMax", "t", NULL
, offsetof(UnitStatusInfo
, memory_max
) },
5515 { "MemorySwapMax", "t", NULL
, offsetof(UnitStatusInfo
, memory_swap_max
) },
5516 { "MemoryLimit", "t", NULL
, offsetof(UnitStatusInfo
, memory_limit
) },
5517 { "CPUUsageNSec", "t", NULL
, offsetof(UnitStatusInfo
, cpu_usage_nsec
) },
5518 { "TasksCurrent", "t", NULL
, offsetof(UnitStatusInfo
, tasks_current
) },
5519 { "TasksMax", "t", NULL
, offsetof(UnitStatusInfo
, tasks_max
) },
5520 { "IPIngressBytes", "t", NULL
, offsetof(UnitStatusInfo
, ip_ingress_bytes
) },
5521 { "IPEgressBytes", "t", NULL
, offsetof(UnitStatusInfo
, ip_egress_bytes
) },
5522 { "IOReadBytes", "t", NULL
, offsetof(UnitStatusInfo
, io_read_bytes
) },
5523 { "IOWriteBytes", "t", NULL
, offsetof(UnitStatusInfo
, io_write_bytes
) },
5524 { "ExecCondition", "a(sasbttttuii)", map_exec
, 0 },
5525 { "ExecConditionEx", "a(sasasttttuii)", map_exec
, 0 },
5526 { "ExecStartPre", "a(sasbttttuii)", map_exec
, 0 },
5527 { "ExecStartPreEx", "a(sasasttttuii)", map_exec
, 0 },
5528 { "ExecStart", "a(sasbttttuii)", map_exec
, 0 },
5529 { "ExecStartEx", "a(sasasttttuii)", map_exec
, 0 },
5530 { "ExecStartPost", "a(sasbttttuii)", map_exec
, 0 },
5531 { "ExecStartPostEx", "a(sasasttttuii)", map_exec
, 0 },
5532 { "ExecReload", "a(sasbttttuii)", map_exec
, 0 },
5533 { "ExecReloadEx", "a(sasasttttuii)", map_exec
, 0 },
5534 { "ExecStopPre", "a(sasbttttuii)", map_exec
, 0 },
5535 { "ExecStop", "a(sasbttttuii)", map_exec
, 0 },
5536 { "ExecStopEx", "a(sasasttttuii)", map_exec
, 0 },
5537 { "ExecStopPost", "a(sasbttttuii)", map_exec
, 0 },
5538 { "ExecStopPostEx", "a(sasasttttuii)", map_exec
, 0 },
5542 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5543 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5544 _cleanup_set_free_ Set
*found_properties
= NULL
;
5545 _cleanup_(unit_status_info_free
) UnitStatusInfo info
= {
5546 .memory_current
= (uint64_t) -1,
5547 .memory_high
= CGROUP_LIMIT_MAX
,
5548 .memory_max
= CGROUP_LIMIT_MAX
,
5549 .memory_swap_max
= CGROUP_LIMIT_MAX
,
5550 .memory_limit
= (uint64_t) -1,
5551 .cpu_usage_nsec
= (uint64_t) -1,
5552 .tasks_current
= (uint64_t) -1,
5553 .tasks_max
= (uint64_t) -1,
5554 .ip_ingress_bytes
= (uint64_t) -1,
5555 .ip_egress_bytes
= (uint64_t) -1,
5556 .io_read_bytes
= UINT64_MAX
,
5557 .io_write_bytes
= UINT64_MAX
,
5565 log_debug("Showing one %s", path
);
5567 r
= bus_map_all_properties(
5569 "org.freedesktop.systemd1",
5571 show_mode
== SYSTEMCTL_SHOW_STATUS
? status_map
: property_map
,
5572 BUS_MAP_BOOLEAN_AS_BOOL
,
5577 return log_error_errno(r
, "Failed to get properties: %s", bus_error_message(&error
, r
));
5579 if (unit
&& streq_ptr(info
.load_state
, "not-found") && streq_ptr(info
.active_state
, "inactive")) {
5580 log_full(show_mode
== SYSTEMCTL_SHOW_STATUS
? LOG_ERR
: LOG_DEBUG
,
5581 "Unit %s could not be found.", unit
);
5583 if (show_mode
== SYSTEMCTL_SHOW_STATUS
)
5584 return EXIT_PROGRAM_OR_SERVICES_STATUS_UNKNOWN
;
5585 else if (show_mode
== SYSTEMCTL_SHOW_HELP
)
5594 if (show_mode
== SYSTEMCTL_SHOW_STATUS
) {
5595 print_status_info(bus
, &info
, ellipsized
);
5597 if (info
.active_state
&& !STR_IN_SET(info
.active_state
, "active", "reloading"))
5598 return EXIT_PROGRAM_NOT_RUNNING
;
5600 return EXIT_PROGRAM_RUNNING_OR_SERVICE_OK
;
5602 } else if (show_mode
== SYSTEMCTL_SHOW_HELP
) {
5603 show_unit_help(&info
);
5607 r
= sd_bus_message_rewind(reply
, true);
5609 return log_error_errno(r
, "Failed to rewind: %s", bus_error_message(&error
, r
));
5611 r
= bus_message_print_all_properties(reply
, print_property
, arg_properties
, arg_value
, arg_all
, &found_properties
);
5613 return bus_log_parse_error(r
);
5615 STRV_FOREACH(pp
, arg_properties
)
5616 if (!set_contains(found_properties
, *pp
))
5617 log_debug("Property %s does not exist.", *pp
);
5622 static int get_unit_dbus_path_by_pid(
5627 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5628 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5632 r
= bus_call_method(bus
, bus_systemd_mgr
, "GetUnitByPID", &error
, &reply
, "u", pid
);
5634 return log_error_errno(r
, "Failed to get unit for PID %"PRIu32
": %s", pid
, bus_error_message(&error
, r
));
5636 r
= sd_bus_message_read(reply
, "o", &u
);
5638 return bus_log_parse_error(r
);
5648 static int show_all(
5653 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5654 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
5659 r
= get_unit_list(bus
, NULL
, NULL
, &unit_infos
, 0, &reply
);
5663 (void) pager_open(arg_pager_flags
);
5667 typesafe_qsort(unit_infos
, c
, compare_unit_info
);
5669 for (u
= unit_infos
; u
< unit_infos
+ c
; u
++) {
5670 _cleanup_free_
char *p
= NULL
;
5672 p
= unit_dbus_path_from_name(u
->id
);
5676 r
= show_one(bus
, p
, u
->id
, SYSTEMCTL_SHOW_STATUS
, new_line
, ellipsized
);
5679 else if (r
> 0 && ret
== 0)
5686 static int show_system_status(sd_bus
*bus
) {
5687 char since1
[FORMAT_TIMESTAMP_RELATIVE_MAX
], since2
[FORMAT_TIMESTAMP_MAX
];
5688 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5689 _cleanup_(machine_info_clear
) struct machine_info mi
= {};
5690 _cleanup_free_
char *hn
= NULL
;
5691 const char *on
, *off
;
5694 hn
= gethostname_malloc();
5698 r
= bus_map_all_properties(
5700 "org.freedesktop.systemd1",
5701 "/org/freedesktop/systemd1",
5702 machine_info_property_map
,
5708 return log_error_errno(r
, "Failed to read server status: %s", bus_error_message(&error
, r
));
5710 if (streq_ptr(mi
.state
, "degraded")) {
5711 on
= ansi_highlight_red();
5712 off
= ansi_normal();
5713 } else if (streq_ptr(mi
.state
, "running")) {
5714 on
= ansi_highlight_green();
5715 off
= ansi_normal();
5717 on
= ansi_highlight_yellow();
5718 off
= ansi_normal();
5721 printf("%s%s%s %s\n", on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
, arg_host
? arg_host
: hn
);
5723 printf(" State: %s%s%s\n",
5724 on
, strna(mi
.state
), off
);
5726 printf(" Jobs: %" PRIu32
" queued\n", mi
.n_jobs
);
5727 printf(" Failed: %" PRIu32
" units\n", mi
.n_failed_units
);
5729 printf(" Since: %s; %s\n",
5730 format_timestamp(since2
, sizeof(since2
), mi
.timestamp
),
5731 format_timestamp_relative(since1
, sizeof(since1
), mi
.timestamp
));
5733 printf(" CGroup: %s\n", mi
.control_group
?: "/");
5734 if (IN_SET(arg_transport
,
5735 BUS_TRANSPORT_LOCAL
,
5736 BUS_TRANSPORT_MACHINE
)) {
5737 static const char prefix
[] = " ";
5741 if (c
> sizeof(prefix
) - 1)
5742 c
-= sizeof(prefix
) - 1;
5746 show_cgroup(SYSTEMD_CGROUP_CONTROLLER
, strempty(mi
.control_group
), prefix
, c
, get_output_flags());
5752 static int show(int argc
, char *argv
[], void *userdata
) {
5753 bool new_line
= false, ellipsized
= false;
5754 SystemctlShowMode show_mode
;
5760 show_mode
= systemctl_show_mode_from_string(argv
[0]);
5762 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
5763 "Invalid argument.");
5765 if (show_mode
== SYSTEMCTL_SHOW_HELP
&& argc
<= 1)
5766 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
5767 "'help' command expects one or more unit names.\n"
5768 "(Alternatively, help for systemctl itself may be shown with --help)");
5770 r
= acquire_bus(BUS_MANAGER
, &bus
);
5774 (void) pager_open(arg_pager_flags
);
5776 /* If no argument is specified inspect the manager itself */
5777 if (show_mode
== SYSTEMCTL_SHOW_PROPERTIES
&& argc
<= 1)
5778 return show_one(bus
, "/org/freedesktop/systemd1", NULL
, show_mode
, &new_line
, &ellipsized
);
5780 if (show_mode
== SYSTEMCTL_SHOW_STATUS
&& argc
<= 1) {
5782 show_system_status(bus
);
5786 ret
= show_all(bus
, &new_line
, &ellipsized
);
5788 _cleanup_free_
char **patterns
= NULL
;
5791 STRV_FOREACH(name
, strv_skip(argv
, 1)) {
5792 _cleanup_free_
char *path
= NULL
, *unit
= NULL
;
5795 if (safe_atou32(*name
, &id
) < 0) {
5796 if (strv_push(&patterns
, *name
) < 0)
5800 } else if (show_mode
== SYSTEMCTL_SHOW_PROPERTIES
) {
5801 /* Interpret as job id */
5802 if (asprintf(&path
, "/org/freedesktop/systemd1/job/%u", id
) < 0)
5806 /* Interpret as PID */
5807 r
= get_unit_dbus_path_by_pid(bus
, id
, &path
);
5813 r
= unit_name_from_dbus_path(path
, &unit
);
5818 r
= show_one(bus
, path
, unit
, show_mode
, &new_line
, &ellipsized
);
5821 else if (r
> 0 && ret
== 0)
5825 if (!strv_isempty(patterns
)) {
5826 _cleanup_strv_free_
char **names
= NULL
;
5828 r
= expand_names(bus
, patterns
, NULL
, &names
, NULL
);
5830 return log_error_errno(r
, "Failed to expand names: %m");
5832 r
= maybe_extend_with_unit_dependencies(bus
, &names
);
5836 STRV_FOREACH(name
, names
) {
5837 _cleanup_free_
char *path
;
5839 path
= unit_dbus_path_from_name(*name
);
5843 r
= show_one(bus
, path
, *name
, show_mode
, &new_line
, &ellipsized
);
5846 if (r
> 0 && ret
== 0)
5852 if (ellipsized
&& !arg_quiet
)
5853 printf("Hint: Some lines were ellipsized, use -l to show in full.\n");
5858 static int cat(int argc
, char *argv
[], void *userdata
) {
5859 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
5860 _cleanup_strv_free_
char **names
= NULL
;
5866 /* Include all units by default — i.e. continue as if the --all
5867 * option was used */
5868 if (strv_isempty(arg_states
))
5871 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
5872 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot remotely cat units.");
5874 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
5876 return log_error_errno(r
, "Failed to determine unit paths: %m");
5878 r
= acquire_bus(BUS_MANAGER
, &bus
);
5882 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
5884 return log_error_errno(r
, "Failed to expand names: %m");
5886 r
= maybe_extend_with_unit_dependencies(bus
, &names
);
5890 (void) pager_open(arg_pager_flags
);
5892 STRV_FOREACH(name
, names
) {
5893 _cleanup_free_
char *fragment_path
= NULL
;
5894 _cleanup_strv_free_
char **dropin_paths
= NULL
;
5896 r
= unit_find_paths(bus
, *name
, &lp
, false, &fragment_path
, &dropin_paths
);
5897 if (r
== -ERFKILL
) {
5898 printf("%s# Unit %s is masked%s.\n",
5899 ansi_highlight_magenta(),
5904 if (r
== -EKEYREJECTED
) {
5905 printf("%s# Unit %s could not be loaded.%s\n",
5906 ansi_highlight_magenta(),
5914 /* Skip units which have no on-disk counterpart, but
5915 * propagate the error to the user */
5925 if (need_daemon_reload(bus
, *name
) > 0) /* ignore errors (<0), this is informational output */
5927 "%s# Warning: %s changed on disk, the version systemd has loaded is outdated.\n"
5928 "%s# This output shows the current version of the unit's original fragment and drop-in files.\n"
5929 "%s# If fragments or drop-ins were added or removed, they are not properly reflected in this output.\n"
5930 "%s# Run 'systemctl%s daemon-reload' to reload units.%s\n",
5931 ansi_highlight_red(),
5933 ansi_highlight_red(),
5934 ansi_highlight_red(),
5935 ansi_highlight_red(),
5936 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user",
5939 r
= cat_files(fragment_path
, dropin_paths
, 0);
5947 static int set_property(int argc
, char *argv
[], void *userdata
) {
5948 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
5949 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5950 _cleanup_free_
char *n
= NULL
;
5955 r
= acquire_bus(BUS_MANAGER
, &bus
);
5959 polkit_agent_open_maybe();
5961 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "SetUnitProperties");
5963 return bus_log_create_error(r
);
5965 r
= unit_name_mangle(argv
[1], arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, &n
);
5967 return log_error_errno(r
, "Failed to mangle unit name: %m");
5969 t
= unit_name_to_type(n
);
5971 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid unit type: %s", n
);
5973 r
= sd_bus_message_append(m
, "sb", n
, arg_runtime
);
5975 return bus_log_create_error(r
);
5977 r
= sd_bus_message_open_container(m
, SD_BUS_TYPE_ARRAY
, "(sv)");
5979 return bus_log_create_error(r
);
5981 r
= bus_append_unit_property_assignment_many(m
, t
, strv_skip(argv
, 2));
5985 r
= sd_bus_message_close_container(m
);
5987 return bus_log_create_error(r
);
5989 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
5991 return log_error_errno(r
, "Failed to set unit properties on %s: %s", n
, bus_error_message(&error
, r
));
5996 static int daemon_reload(int argc
, char *argv
[], void *userdata
) {
5997 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5998 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6003 r
= acquire_bus(BUS_MANAGER
, &bus
);
6007 polkit_agent_open_maybe();
6009 switch (arg_action
) {
6016 method
= "Reexecute";
6019 case ACTION_SYSTEMCTL
:
6020 method
= streq(argv
[0], "daemon-reexec") ? "Reexecute" :
6021 /* "daemon-reload" */ "Reload";
6025 assert_not_reached("Unexpected action");
6028 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, method
);
6030 return bus_log_create_error(r
);
6032 /* Note we use an extra-long timeout here. This is because a reload or reexec means generators are rerun which
6033 * are timed out after DEFAULT_TIMEOUT_USEC. Let's use twice that time here, so that the generators can have
6034 * their timeout, and for everything else there's the same time budget in place. */
6036 r
= sd_bus_call(bus
, m
, DEFAULT_TIMEOUT_USEC
* 2, &error
, NULL
);
6038 /* On reexecution, we expect a disconnect, not a reply */
6039 if (IN_SET(r
, -ETIMEDOUT
, -ECONNRESET
) && streq(method
, "Reexecute"))
6042 if (r
< 0 && arg_action
== ACTION_SYSTEMCTL
)
6043 return log_error_errno(r
, "Failed to reload daemon: %s", bus_error_message(&error
, r
));
6045 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
6046 * old ways of doing things, hence don't log any error in that case here. */
6048 return r
< 0 ? r
: 0;
6051 static int trivial_method(int argc
, char *argv
[], void *userdata
) {
6052 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6060 r
= acquire_bus(BUS_MANAGER
, &bus
);
6064 polkit_agent_open_maybe();
6067 streq(argv
[0], "clear-jobs") ||
6068 streq(argv
[0], "cancel") ? "ClearJobs" :
6069 streq(argv
[0], "reset-failed") ? "ResetFailed" :
6070 streq(argv
[0], "halt") ? "Halt" :
6071 streq(argv
[0], "reboot") ? "Reboot" :
6072 streq(argv
[0], "kexec") ? "KExec" :
6073 streq(argv
[0], "exit") ? "Exit" :
6074 /* poweroff */ "PowerOff";
6076 r
= bus_call_method(bus
, bus_systemd_mgr
, method
, &error
, NULL
, NULL
);
6077 if (r
< 0 && arg_action
== ACTION_SYSTEMCTL
)
6078 return log_error_errno(r
, "Failed to execute operation: %s", bus_error_message(&error
, r
));
6080 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
6081 * old ways of doing things, hence don't log any error in that case here. */
6083 return r
< 0 ? r
: 0;
6086 static int reset_failed(int argc
, char *argv
[], void *userdata
) {
6087 _cleanup_strv_free_
char **names
= NULL
;
6093 return trivial_method(argc
, argv
, userdata
);
6095 r
= acquire_bus(BUS_MANAGER
, &bus
);
6099 polkit_agent_open_maybe();
6101 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
6103 return log_error_errno(r
, "Failed to expand names: %m");
6105 STRV_FOREACH(name
, names
) {
6106 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6108 q
= bus_call_method(bus
, bus_systemd_mgr
, "ResetFailedUnit", &error
, NULL
, "s", *name
);
6110 log_error_errno(q
, "Failed to reset failed state of unit %s: %s", *name
, bus_error_message(&error
, q
));
6119 static int print_variable(const char *s
) {
6121 _cleanup_free_
char *esc
= NULL
;
6123 sep
= strchr(s
, '=');
6125 return log_error_errno(SYNTHETIC_ERRNO(EUCLEAN
),
6126 "Invalid environment block");
6128 esc
= shell_maybe_quote(sep
+ 1, ESCAPE_POSIX
);
6132 printf("%.*s=%s\n", (int)(sep
-s
), s
, esc
);
6136 static int show_environment(int argc
, char *argv
[], void *userdata
) {
6137 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6138 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
6143 r
= acquire_bus(BUS_MANAGER
, &bus
);
6147 (void) pager_open(arg_pager_flags
);
6149 r
= bus_get_property(bus
, bus_systemd_mgr
, "Environment", &error
, &reply
, "as");
6151 return log_error_errno(r
, "Failed to get environment: %s", bus_error_message(&error
, r
));
6153 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "s");
6155 return bus_log_parse_error(r
);
6157 while ((r
= sd_bus_message_read_basic(reply
, SD_BUS_TYPE_STRING
, &text
)) > 0) {
6158 r
= print_variable(text
);
6163 return bus_log_parse_error(r
);
6165 r
= sd_bus_message_exit_container(reply
);
6167 return bus_log_parse_error(r
);
6172 static int switch_root(int argc
, char *argv
[], void *userdata
) {
6173 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6174 _cleanup_free_
char *cmdline_init
= NULL
;
6175 const char *root
, *init
;
6179 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
6180 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot switch root remotely.");
6182 if (argc
< 2 || argc
> 3)
6183 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Wrong number of arguments.");
6190 r
= proc_cmdline_get_key("init", 0, &cmdline_init
);
6192 log_debug_errno(r
, "Failed to parse /proc/cmdline: %m");
6194 init
= cmdline_init
;
6197 init
= empty_to_null(init
);
6199 const char *root_systemd_path
= NULL
, *root_init_path
= NULL
;
6201 root_systemd_path
= prefix_roota(root
, "/" SYSTEMD_BINARY_PATH
);
6202 root_init_path
= prefix_roota(root
, init
);
6204 /* If the passed init is actually the same as the
6205 * systemd binary, then let's suppress it. */
6206 if (files_same(root_init_path
, root_systemd_path
, 0) > 0)
6210 /* Instruct PID1 to exclude us from its killing spree applied during the transition. Otherwise we
6211 * would exit with a failure status even though the switch to the new root has succeed. */
6213 assert(saved_argv
[0]);
6214 saved_argv
[0][0] = '@';
6216 r
= acquire_bus(BUS_MANAGER
, &bus
);
6220 /* If we are slow to exit after the root switch, the new systemd instance
6221 * will send us a signal to terminate. Just ignore it and exit normally.
6222 * This way the unit does not end up as failed.
6224 r
= ignore_signals(SIGTERM
, -1);
6226 log_warning_errno(r
, "Failed to change disposition of SIGTERM to ignore: %m");
6228 log_debug("Switching root - root: %s; init: %s", root
, strna(init
));
6230 r
= bus_call_method(bus
, bus_systemd_mgr
, "SwitchRoot", &error
, NULL
, "ss", root
, init
);
6232 (void) default_signals(SIGTERM
, -1);
6234 return log_error_errno(r
, "Failed to switch root: %s", bus_error_message(&error
, r
));
6240 static int log_level(int argc
, char *argv
[], void *userdata
) {
6242 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6245 r
= acquire_bus(BUS_MANAGER
, &bus
);
6250 _cleanup_free_
char *level
= NULL
;
6252 r
= bus_get_property_string(bus
, bus_systemd_mgr
, "LogLevel", &error
, &level
);
6254 return log_error_errno(r
, "Failed to get log level: %s", bus_error_message(&error
, r
));
6261 r
= bus_set_property(bus
, bus_systemd_mgr
, "LogLevel", &error
, "s", argv
[1]);
6263 return log_error_errno(r
, "Failed to set log level: %s", bus_error_message(&error
, r
));
6269 static int log_target(int argc
, char *argv
[], void *userdata
) {
6271 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6274 r
= acquire_bus(BUS_MANAGER
, &bus
);
6279 _cleanup_free_
char *target
= NULL
;
6281 r
= bus_get_property_string(bus
, bus_systemd_mgr
, "LogTarget", &error
, &target
);
6283 return log_error_errno(r
, "Failed to get log target: %s", bus_error_message(&error
, r
));
6290 r
= bus_set_property(bus
, bus_systemd_mgr
, "LogTarget", &error
, "s", argv
[1]);
6292 return log_error_errno(r
, "Failed to set log target: %s", bus_error_message(&error
, r
));
6298 static int service_watchdogs(int argc
, char *argv
[], void *userdata
) {
6300 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6305 r
= acquire_bus(BUS_MANAGER
, &bus
);
6310 /* get ServiceWatchdogs */
6311 r
= bus_get_property_trivial(bus
, bus_systemd_mgr
, "ServiceWatchdogs", &error
, 'b', &b
);
6313 return log_error_errno(r
, "Failed to get service-watchdog state: %s", bus_error_message(&error
, r
));
6315 printf("%s\n", yes_no(!!b
));
6318 /* set ServiceWatchdogs */
6321 b
= parse_boolean(argv
[1]);
6323 return log_error_errno(b
, "Failed to parse service-watchdogs argument: %m");
6325 r
= bus_set_property(bus
, bus_systemd_mgr
, "ServiceWatchdogs", &error
, "b", b
);
6327 return log_error_errno(r
, "Failed to set service-watchdog state: %s", bus_error_message(&error
, r
));
6333 static int set_environment(int argc
, char *argv
[], void *userdata
) {
6334 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6335 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6343 r
= acquire_bus(BUS_MANAGER
, &bus
);
6347 polkit_agent_open_maybe();
6349 method
= streq(argv
[0], "set-environment")
6351 : "UnsetEnvironment";
6353 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, method
);
6355 return bus_log_create_error(r
);
6357 r
= sd_bus_message_append_strv(m
, strv_skip(argv
, 1));
6359 return bus_log_create_error(r
);
6361 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6363 return log_error_errno(r
, "Failed to set environment: %s", bus_error_message(&error
, r
));
6368 static int import_environment(int argc
, char *argv
[], void *userdata
) {
6369 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6370 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6374 r
= acquire_bus(BUS_MANAGER
, &bus
);
6378 polkit_agent_open_maybe();
6380 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "SetEnvironment");
6382 return bus_log_create_error(r
);
6385 r
= sd_bus_message_append_strv(m
, environ
);
6389 r
= sd_bus_message_open_container(m
, 'a', "s");
6391 return bus_log_create_error(r
);
6393 STRV_FOREACH(a
, strv_skip(argv
, 1)) {
6395 if (!env_name_is_valid(*a
))
6396 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Not a valid environment variable name: %s", *a
);
6398 STRV_FOREACH(b
, environ
) {
6401 eq
= startswith(*b
, *a
);
6402 if (eq
&& *eq
== '=') {
6404 r
= sd_bus_message_append(m
, "s", *b
);
6406 return bus_log_create_error(r
);
6413 r
= sd_bus_message_close_container(m
);
6416 return bus_log_create_error(r
);
6418 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6420 return log_error_errno(r
, "Failed to import environment: %s", bus_error_message(&error
, r
));
6425 static int enable_sysv_units(const char *verb
, char **args
) {
6428 #if HAVE_SYSV_COMPAT
6429 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
6432 /* Processes all SysV units, and reshuffles the array so that afterwards only the native units remain */
6434 if (arg_scope
!= UNIT_FILE_SYSTEM
)
6437 if (getenv_bool("SYSTEMCTL_SKIP_SYSV") > 0)
6440 if (!STR_IN_SET(verb
,
6446 r
= lookup_paths_init(&paths
, arg_scope
, LOOKUP_PATHS_EXCLUDE_GENERATED
, arg_root
);
6453 const char *argv
[] = {
6454 ROOTLIBEXECDIR
"/systemd-sysv-install",
6461 _cleanup_free_
char *p
= NULL
, *q
= NULL
, *l
= NULL
, *v
= NULL
;
6462 bool found_native
= false, found_sysv
;
6470 if (!endswith(name
, ".service"))
6473 if (path_is_absolute(name
))
6476 j
= unit_file_exists(arg_scope
, &paths
, name
);
6477 if (j
< 0 && !IN_SET(j
, -ELOOP
, -ERFKILL
, -EADDRNOTAVAIL
))
6478 return log_error_errno(j
, "Failed to look up unit file state: %m");
6479 found_native
= j
!= 0;
6481 /* If we have both a native unit and a SysV script, enable/disable them both (below); for is-enabled,
6482 * prefer the native unit */
6483 if (found_native
&& streq(verb
, "is-enabled"))
6486 p
= path_join(arg_root
, SYSTEM_SYSVINIT_PATH
, name
);
6490 p
[strlen(p
) - STRLEN(".service")] = 0;
6491 found_sysv
= access(p
, F_OK
) >= 0;
6497 log_info("Synchronizing state of %s with SysV service script with %s.", name
, argv
[0]);
6499 log_info("%s is not a native service, redirecting to systemd-sysv-install.", name
);
6502 if (!isempty(arg_root
)) {
6503 q
= strjoin("--root=", arg_root
);
6510 /* Let's copy the verb, since it's still pointing directly into the original argv[] array we
6511 * got passed, but safe_fork() is likely going to rewrite that for the new child */
6517 argv
[c
++] = basename(p
);
6520 l
= strv_join((char**)argv
, " ");
6525 log_info("Executing: %s", l
);
6527 j
= safe_fork("(sysv-install)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
, &pid
);
6532 execv(argv
[0], (char**) argv
);
6533 log_error_errno(errno
, "Failed to execute %s: %m", argv
[0]);
6534 _exit(EXIT_FAILURE
);
6537 j
= wait_for_terminate_and_check("sysv-install", pid
, WAIT_LOG_ABNORMAL
);
6540 if (streq(verb
, "is-enabled")) {
6541 if (j
== EXIT_SUCCESS
) {
6550 } else if (j
!= EXIT_SUCCESS
)
6551 return -EBADE
; /* We don't warn here, under the assumption the script already showed an explanation */
6556 /* Remove this entry, so that we don't try enabling it as native unit */
6559 assert(args
[f
] == name
);
6560 strv_remove(args
+ f
, name
);
6567 static int mangle_names(const char *operation
, char **original_names
, char ***mangled_names
) {
6568 char **i
, **l
, **name
;
6571 l
= i
= new(char*, strv_length(original_names
) + 1);
6575 STRV_FOREACH(name
, original_names
) {
6577 /* When enabling units qualified path names are OK,
6578 * too, hence allow them explicitly. */
6580 if (is_path(*name
)) {
6587 r
= unit_name_mangle_with_suffix(*name
, operation
,
6588 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
6593 return log_error_errno(r
, "Failed to mangle unit name: %m");
6606 static int normalize_filenames(char **names
) {
6610 STRV_FOREACH(u
, names
)
6611 if (!path_is_absolute(*u
)) {
6612 char* normalized_path
;
6614 if (!isempty(arg_root
))
6615 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6616 "Non-absolute paths are not allowed when --root is used: %s",
6619 if (!strchr(*u
,'/'))
6620 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6621 "Link argument does contain at least one directory separator: %s",
6624 r
= path_make_absolute_cwd(*u
, &normalized_path
);
6628 free_and_replace(*u
, normalized_path
);
6634 static int normalize_names(char **names
, bool warn_if_path
) {
6636 bool was_path
= false;
6638 STRV_FOREACH(u
, names
) {
6644 r
= free_and_strdup(u
, basename(*u
));
6646 return log_error_errno(r
, "Failed to normalize unit file path: %m");
6651 if (warn_if_path
&& was_path
)
6652 log_warning("Warning: Can't execute disable on the unit file path. Proceeding with the unit name.");
6657 static int unit_exists(LookupPaths
*lp
, const char *unit
) {
6658 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6659 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6660 _cleanup_free_
char *path
= NULL
;
6661 static const struct bus_properties_map property_map
[] = {
6662 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
6663 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
)},
6666 UnitStatusInfo info
= {};
6670 if (unit_name_is_valid(unit
, UNIT_NAME_TEMPLATE
))
6671 return unit_find_template_path(unit
, lp
, NULL
, NULL
);
6673 path
= unit_dbus_path_from_name(unit
);
6677 r
= acquire_bus(BUS_MANAGER
, &bus
);
6681 r
= bus_map_all_properties(bus
, "org.freedesktop.systemd1", path
, property_map
, 0, &error
, &m
, &info
);
6683 return log_error_errno(r
, "Failed to get properties: %s", bus_error_message(&error
, r
));
6685 return !streq_ptr(info
.load_state
, "not-found") || !streq_ptr(info
.active_state
, "inactive");
6688 static int enable_unit(int argc
, char *argv
[], void *userdata
) {
6689 _cleanup_strv_free_
char **names
= NULL
;
6690 const char *verb
= argv
[0];
6691 UnitFileChange
*changes
= NULL
;
6692 size_t n_changes
= 0;
6693 int carries_install_info
= -1;
6694 bool ignore_carries_install_info
= arg_quiet
;
6700 r
= mangle_names("to enable", strv_skip(argv
, 1), &names
);
6704 r
= enable_sysv_units(verb
, names
);
6708 /* If the operation was fully executed by the SysV compat, let's finish early */
6709 if (strv_isempty(names
)) {
6710 if (arg_no_reload
|| install_client_side())
6712 return daemon_reload(argc
, argv
, userdata
);
6715 if (streq(verb
, "disable")) {
6716 r
= normalize_names(names
, true);
6721 if (streq(verb
, "link")) {
6722 r
= normalize_filenames(names
);
6727 if (install_client_side()) {
6728 UnitFileFlags flags
;
6730 flags
= args_to_flags();
6731 if (streq(verb
, "enable")) {
6732 r
= unit_file_enable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6733 carries_install_info
= r
;
6734 } else if (streq(verb
, "disable"))
6735 r
= unit_file_disable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6736 else if (streq(verb
, "reenable")) {
6737 r
= unit_file_reenable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6738 carries_install_info
= r
;
6739 } else if (streq(verb
, "link"))
6740 r
= unit_file_link(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6741 else if (streq(verb
, "preset")) {
6742 r
= unit_file_preset(arg_scope
, flags
, arg_root
, names
, arg_preset_mode
, &changes
, &n_changes
);
6743 } else if (streq(verb
, "mask"))
6744 r
= unit_file_mask(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6745 else if (streq(verb
, "unmask"))
6746 r
= unit_file_unmask(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6747 else if (streq(verb
, "revert"))
6748 r
= unit_file_revert(arg_scope
, arg_root
, names
, &changes
, &n_changes
);
6750 assert_not_reached("Unknown verb");
6752 unit_file_dump_changes(r
, verb
, changes
, n_changes
, arg_quiet
);
6757 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
, *m
= NULL
;
6758 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6759 bool expect_carries_install_info
= false;
6760 bool send_runtime
= true, send_force
= true, send_preset_mode
= false;
6764 if (STR_IN_SET(verb
, "mask", "unmask")) {
6766 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
6768 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
6772 STRV_FOREACH(name
, names
) {
6773 r
= unit_exists(&lp
, *name
);
6777 log_notice("Unit %s does not exist, proceeding anyway.", *name
);
6781 r
= acquire_bus(BUS_MANAGER
, &bus
);
6785 polkit_agent_open_maybe();
6787 if (streq(verb
, "enable")) {
6788 method
= "EnableUnitFiles";
6789 expect_carries_install_info
= true;
6790 } else if (streq(verb
, "disable")) {
6791 method
= "DisableUnitFiles";
6793 } else if (streq(verb
, "reenable")) {
6794 method
= "ReenableUnitFiles";
6795 expect_carries_install_info
= true;
6796 } else if (streq(verb
, "link"))
6797 method
= "LinkUnitFiles";
6798 else if (streq(verb
, "preset")) {
6800 if (arg_preset_mode
!= UNIT_FILE_PRESET_FULL
) {
6801 method
= "PresetUnitFilesWithMode";
6802 send_preset_mode
= true;
6804 method
= "PresetUnitFiles";
6806 expect_carries_install_info
= true;
6807 ignore_carries_install_info
= true;
6808 } else if (streq(verb
, "mask"))
6809 method
= "MaskUnitFiles";
6810 else if (streq(verb
, "unmask")) {
6811 method
= "UnmaskUnitFiles";
6813 } else if (streq(verb
, "revert")) {
6814 method
= "RevertUnitFiles";
6815 send_runtime
= send_force
= false;
6817 assert_not_reached("Unknown verb");
6819 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, method
);
6821 return bus_log_create_error(r
);
6823 r
= sd_bus_message_append_strv(m
, names
);
6825 return bus_log_create_error(r
);
6827 if (send_preset_mode
) {
6828 r
= sd_bus_message_append(m
, "s", unit_file_preset_mode_to_string(arg_preset_mode
));
6830 return bus_log_create_error(r
);
6834 r
= sd_bus_message_append(m
, "b", arg_runtime
);
6836 return bus_log_create_error(r
);
6840 r
= sd_bus_message_append(m
, "b", arg_force
);
6842 return bus_log_create_error(r
);
6845 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
6847 return log_error_errno(r
, "Failed to %s unit: %s", verb
, bus_error_message(&error
, r
));
6849 if (expect_carries_install_info
) {
6850 r
= sd_bus_message_read(reply
, "b", &carries_install_info
);
6852 return bus_log_parse_error(r
);
6855 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
6859 /* Try to reload if enabled */
6861 r
= daemon_reload(argc
, argv
, userdata
);
6866 if (carries_install_info
== 0 && !ignore_carries_install_info
)
6867 log_notice("The unit files have no installation config (WantedBy=, RequiredBy=, Also=,\n"
6868 "Alias= settings in the [Install] section, and DefaultInstance= for template\n"
6869 "units). This means they are not meant to be enabled using systemctl.\n"
6870 " \n" /* trick: the space is needed so that the line does not get stripped from output */
6871 "Possible reasons for having this kind of units are:\n"
6872 "%1$s A unit may be statically enabled by being symlinked from another unit's\n"
6873 " .wants/ or .requires/ directory.\n"
6874 "%1$s A unit's purpose may be to act as a helper for some other unit which has\n"
6875 " a requirement dependency on it.\n"
6876 "%1$s A unit may be started when needed via activation (socket, path, timer,\n"
6877 " D-Bus, udev, scripted systemctl call, ...).\n"
6878 "%1$s In case of template units, the unit is meant to be enabled with some\n"
6879 " instance name specified.",
6880 special_glyph(SPECIAL_GLYPH_BULLET
));
6882 if (arg_now
&& STR_IN_SET(argv
[0], "enable", "disable", "mask")) {
6886 r
= acquire_bus(BUS_MANAGER
, &bus
);
6890 len
= strv_length(names
);
6892 char *new_args
[len
+ 2];
6894 new_args
[0] = (char*) (streq(argv
[0], "enable") ? "start" : "stop");
6895 for (i
= 0; i
< len
; i
++)
6896 new_args
[i
+ 1] = basename(names
[i
]);
6897 new_args
[i
+ 1] = NULL
;
6899 r
= start_unit(len
+ 1, new_args
, userdata
);
6904 unit_file_changes_free(changes
, n_changes
);
6909 static int add_dependency(int argc
, char *argv
[], void *userdata
) {
6910 _cleanup_strv_free_
char **names
= NULL
;
6911 _cleanup_free_
char *target
= NULL
;
6912 const char *verb
= argv
[0];
6913 UnitFileChange
*changes
= NULL
;
6914 size_t n_changes
= 0;
6921 r
= unit_name_mangle_with_suffix(argv
[1], "as target",
6922 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
6923 ".target", &target
);
6925 return log_error_errno(r
, "Failed to mangle unit name: %m");
6927 r
= mangle_names("as dependency", strv_skip(argv
, 2), &names
);
6931 if (streq(verb
, "add-wants"))
6933 else if (streq(verb
, "add-requires"))
6934 dep
= UNIT_REQUIRES
;
6936 assert_not_reached("Unknown verb");
6938 if (install_client_side()) {
6939 r
= unit_file_add_dependency(arg_scope
, args_to_flags(), arg_root
, names
, target
, dep
, &changes
, &n_changes
);
6940 unit_file_dump_changes(r
, "add dependency on", changes
, n_changes
, arg_quiet
);
6945 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
, *m
= NULL
;
6946 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6949 r
= acquire_bus(BUS_MANAGER
, &bus
);
6953 polkit_agent_open_maybe();
6955 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "AddDependencyUnitFiles");
6957 return bus_log_create_error(r
);
6959 r
= sd_bus_message_append_strv(m
, names
);
6961 return bus_log_create_error(r
);
6963 r
= sd_bus_message_append(m
, "ssbb", target
, unit_dependency_to_string(dep
), arg_runtime
, arg_force
);
6965 return bus_log_create_error(r
);
6967 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
6969 return log_error_errno(r
, "Failed to add dependency: %s", bus_error_message(&error
, r
));
6971 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
6975 if (arg_no_reload
) {
6980 r
= daemon_reload(argc
, argv
, userdata
);
6984 unit_file_changes_free(changes
, n_changes
);
6989 static int preset_all(int argc
, char *argv
[], void *userdata
) {
6990 UnitFileChange
*changes
= NULL
;
6991 size_t n_changes
= 0;
6994 if (install_client_side()) {
6995 r
= unit_file_preset_all(arg_scope
, args_to_flags(), arg_root
, arg_preset_mode
, &changes
, &n_changes
);
6996 unit_file_dump_changes(r
, "preset", changes
, n_changes
, arg_quiet
);
7001 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7002 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7005 r
= acquire_bus(BUS_MANAGER
, &bus
);
7009 polkit_agent_open_maybe();
7011 r
= bus_call_method(
7014 "PresetAllUnitFiles",
7018 unit_file_preset_mode_to_string(arg_preset_mode
),
7022 return log_error_errno(r
, "Failed to preset all units: %s", bus_error_message(&error
, r
));
7024 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
7028 if (arg_no_reload
) {
7033 r
= daemon_reload(argc
, argv
, userdata
);
7037 unit_file_changes_free(changes
, n_changes
);
7042 static int show_installation_targets_client_side(const char *name
) {
7043 UnitFileChange
*changes
= NULL
;
7044 size_t n_changes
= 0, i
;
7045 UnitFileFlags flags
;
7049 p
= STRV_MAKE(name
);
7050 flags
= UNIT_FILE_DRY_RUN
|
7051 (arg_runtime
? UNIT_FILE_RUNTIME
: 0);
7053 r
= unit_file_disable(UNIT_FILE_SYSTEM
, flags
, NULL
, p
, &changes
, &n_changes
);
7055 return log_error_errno(r
, "Failed to get file links for %s: %m", name
);
7057 for (i
= 0; i
< n_changes
; i
++)
7058 if (changes
[i
].type
== UNIT_FILE_UNLINK
)
7059 printf(" %s\n", changes
[i
].path
);
7064 static int show_installation_targets(sd_bus
*bus
, const char *name
) {
7065 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7066 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7070 r
= bus_call_method(bus
, bus_systemd_mgr
, "GetUnitFileLinks", &error
, &reply
, "sb", name
, arg_runtime
);
7072 return log_error_errno(r
, "Failed to get unit file links for %s: %s", name
, bus_error_message(&error
, r
));
7074 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "s");
7076 return bus_log_parse_error(r
);
7078 while ((r
= sd_bus_message_read(reply
, "s", &link
)) > 0)
7079 printf(" %s\n", link
);
7082 return bus_log_parse_error(r
);
7084 r
= sd_bus_message_exit_container(reply
);
7086 return bus_log_parse_error(r
);
7091 static int unit_is_enabled(int argc
, char *argv
[], void *userdata
) {
7092 _cleanup_strv_free_
char **names
= NULL
;
7097 r
= mangle_names("to check", strv_skip(argv
, 1), &names
);
7101 r
= enable_sysv_units(argv
[0], names
);
7107 if (install_client_side()) {
7108 STRV_FOREACH(name
, names
) {
7109 UnitFileState state
;
7111 r
= unit_file_get_state(arg_scope
, arg_root
, *name
, &state
);
7113 return log_error_errno(r
, "Failed to get unit file state for %s: %m", *name
);
7117 UNIT_FILE_ENABLED_RUNTIME
,
7121 UNIT_FILE_GENERATED
))
7125 puts(unit_file_state_to_string(state
));
7127 r
= show_installation_targets_client_side(*name
);
7136 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7139 r
= acquire_bus(BUS_MANAGER
, &bus
);
7143 STRV_FOREACH(name
, names
) {
7144 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7147 r
= bus_call_method(bus
, bus_systemd_mgr
, "GetUnitFileState", &error
, &reply
, "s", *name
);
7149 return log_error_errno(r
, "Failed to get unit file state for %s: %s", *name
, bus_error_message(&error
, r
));
7151 r
= sd_bus_message_read(reply
, "s", &s
);
7153 return bus_log_parse_error(r
);
7155 if (STR_IN_SET(s
, "enabled", "enabled-runtime", "static", "indirect", "generated"))
7161 r
= show_installation_targets(bus
, *name
);
7169 return enabled
? EXIT_SUCCESS
: EXIT_FAILURE
;
7172 static int match_startup_finished(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
7173 char **state
= userdata
;
7178 r
= bus_get_property_string(sd_bus_message_get_bus(m
), bus_systemd_mgr
, "SystemState", NULL
, state
);
7180 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m
)), r
);
7184 static int is_system_running(int argc
, char *argv
[], void *userdata
) {
7185 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7186 _cleanup_(sd_bus_slot_unrefp
) sd_bus_slot
*slot_startup_finished
= NULL
;
7187 _cleanup_(sd_event_unrefp
) sd_event
* event
= NULL
;
7188 _cleanup_free_
char *state
= NULL
;
7192 if (running_in_chroot() > 0 || (arg_transport
== BUS_TRANSPORT_LOCAL
&& !sd_booted())) {
7195 return EXIT_FAILURE
;
7198 r
= acquire_bus(BUS_MANAGER
, &bus
);
7203 r
= sd_event_default(&event
);
7205 r
= sd_bus_attach_event(bus
, event
, 0);
7207 r
= bus_match_signal_async(
7209 &slot_startup_finished
,
7212 match_startup_finished
, NULL
, &state
);
7214 log_warning_errno(r
, "Failed to request match for StartupFinished: %m");
7219 r
= bus_get_property_string(bus
, bus_systemd_mgr
, "SystemState", &error
, &state
);
7221 log_warning_errno(r
, "Failed to query system state: %s", bus_error_message(&error
, r
));
7225 return EXIT_FAILURE
;
7228 if (arg_wait
&& STR_IN_SET(state
, "initializing", "starting")) {
7229 r
= sd_event_loop(event
);
7231 log_warning_errno(r
, "Failed to get property from event loop: %m");
7234 return EXIT_FAILURE
;
7241 return streq(state
, "running") ? EXIT_SUCCESS
: EXIT_FAILURE
;
7244 static int create_edit_temp_file(const char *new_path
, const char *original_path
, char **ret_tmp_fn
) {
7245 _cleanup_free_
char *t
= NULL
;
7249 assert(original_path
);
7252 r
= tempfn_random(new_path
, NULL
, &t
);
7254 return log_error_errno(r
, "Failed to determine temporary filename for \"%s\": %m", new_path
);
7256 r
= mkdir_parents(new_path
, 0755);
7258 return log_error_errno(r
, "Failed to create directories for \"%s\": %m", new_path
);
7260 r
= copy_file(original_path
, t
, 0, 0644, 0, 0, COPY_REFLINK
);
7265 return log_error_errno(r
, "Failed to create temporary file \"%s\": %m", t
);
7268 return log_error_errno(r
, "Failed to create temporary file for \"%s\": %m", new_path
);
7270 *ret_tmp_fn
= TAKE_PTR(t
);
7275 static int get_file_to_edit(
7276 const LookupPaths
*paths
,
7280 _cleanup_free_
char *path
= NULL
, *run
= NULL
;
7285 path
= path_join(paths
->persistent_config
, name
);
7290 run
= path_join(paths
->runtime_config
, name
);
7296 if (access(path
, F_OK
) >= 0)
7297 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
7298 "Refusing to create \"%s\" because it would be overridden by \"%s\" anyway.",
7301 *ret_path
= TAKE_PTR(run
);
7303 *ret_path
= TAKE_PTR(path
);
7308 static int unit_file_create_new(
7309 const LookupPaths
*paths
,
7310 const char *unit_name
,
7312 char **ret_new_path
,
7313 char **ret_tmp_path
) {
7315 _cleanup_free_
char *new_path
= NULL
, *tmp_path
= NULL
;
7320 assert(ret_new_path
);
7321 assert(ret_tmp_path
);
7323 ending
= strjoina(unit_name
, suffix
);
7324 r
= get_file_to_edit(paths
, ending
, &new_path
);
7328 r
= create_edit_temp_file(new_path
, new_path
, &tmp_path
);
7332 *ret_new_path
= TAKE_PTR(new_path
);
7333 *ret_tmp_path
= TAKE_PTR(tmp_path
);
7338 static int unit_file_create_copy(
7339 const LookupPaths
*paths
,
7340 const char *unit_name
,
7341 const char *fragment_path
,
7342 char **ret_new_path
,
7343 char **ret_tmp_path
) {
7345 _cleanup_free_
char *new_path
= NULL
, *tmp_path
= NULL
;
7348 assert(fragment_path
);
7350 assert(ret_new_path
);
7351 assert(ret_tmp_path
);
7353 r
= get_file_to_edit(paths
, unit_name
, &new_path
);
7357 if (!path_equal(fragment_path
, new_path
) && access(new_path
, F_OK
) >= 0) {
7360 r
= ask_char(&response
, "yn", "\"%s\" already exists. Overwrite with \"%s\"? [(y)es, (n)o] ", new_path
, fragment_path
);
7363 if (response
!= 'y')
7364 return log_warning_errno(SYNTHETIC_ERRNO(EKEYREJECTED
), "%s skipped.", unit_name
);
7367 r
= create_edit_temp_file(new_path
, fragment_path
, &tmp_path
);
7371 *ret_new_path
= TAKE_PTR(new_path
);
7372 *ret_tmp_path
= TAKE_PTR(tmp_path
);
7377 static int run_editor(char **paths
) {
7382 r
= safe_fork("(editor)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
|FORK_WAIT
, NULL
);
7386 char **editor_args
= NULL
, **tmp_path
, **original_path
;
7387 size_t n_editor_args
= 0, i
= 1, argc
;
7388 const char **args
, *editor
, *p
;
7390 argc
= strv_length(paths
)/2 + 1;
7392 /* SYSTEMD_EDITOR takes precedence over EDITOR which takes precedence over VISUAL
7393 * If neither SYSTEMD_EDITOR nor EDITOR nor VISUAL are present,
7394 * we try to execute well known editors
7396 editor
= getenv("SYSTEMD_EDITOR");
7398 editor
= getenv("EDITOR");
7400 editor
= getenv("VISUAL");
7402 if (!isempty(editor
)) {
7403 editor_args
= strv_split(editor
, WHITESPACE
);
7406 _exit(EXIT_FAILURE
);
7408 n_editor_args
= strv_length(editor_args
);
7409 argc
+= n_editor_args
- 1;
7412 args
= newa(const char*, argc
+ 1);
7414 if (n_editor_args
> 0) {
7415 args
[0] = editor_args
[0];
7416 for (; i
< n_editor_args
; i
++)
7417 args
[i
] = editor_args
[i
];
7420 STRV_FOREACH_PAIR(original_path
, tmp_path
, paths
)
7421 args
[i
++] = *tmp_path
;
7424 if (n_editor_args
> 0)
7425 execvp(args
[0], (char* const*) args
);
7427 FOREACH_STRING(p
, "editor", "nano", "vim", "vi") {
7429 execvp(p
, (char* const*) args
);
7430 /* We do not fail if the editor doesn't exist
7431 * because we want to try each one of them before
7434 if (errno
!= ENOENT
) {
7435 log_error_errno(errno
, "Failed to execute %s: %m", editor
);
7436 _exit(EXIT_FAILURE
);
7440 log_error("Cannot edit unit(s), no editor available. Please set either $SYSTEMD_EDITOR, $EDITOR or $VISUAL.");
7441 _exit(EXIT_FAILURE
);
7447 static int find_paths_to_edit(sd_bus
*bus
, char **names
, char ***paths
) {
7448 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
7455 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
7459 STRV_FOREACH(name
, names
) {
7460 _cleanup_free_
char *path
= NULL
, *new_path
= NULL
, *tmp_path
= NULL
, *tmp_name
= NULL
;
7461 const char *unit_name
;
7463 r
= unit_find_paths(bus
, *name
, &lp
, false, &path
, NULL
);
7464 if (r
== -EKEYREJECTED
) {
7465 /* If loading of the unit failed server side complete, then the server won't tell us the unit
7466 * file path. In that case, find the file client side. */
7467 log_debug_errno(r
, "Unit '%s' was not loaded correctly, retrying client-side.", *name
);
7468 r
= unit_find_paths(bus
, *name
, &lp
, true, &path
, NULL
);
7471 return log_error_errno(r
, "Unit '%s' masked, cannot edit.", *name
);
7479 log_info("Run 'systemctl edit%s --force --full %s' to create a new unit.",
7480 arg_scope
== UNIT_FILE_GLOBAL
? " --global" :
7481 arg_scope
== UNIT_FILE_USER
? " --user" : "",
7486 /* Create a new unit from scratch */
7488 r
= unit_file_create_new(&lp
, unit_name
,
7489 arg_full
? NULL
: ".d/override.conf",
7490 &new_path
, &tmp_path
);
7494 unit_name
= basename(path
);
7495 /* We follow unit aliases, but we need to propagate the instance */
7496 if (unit_name_is_valid(*name
, UNIT_NAME_INSTANCE
) &&
7497 unit_name_is_valid(unit_name
, UNIT_NAME_TEMPLATE
)) {
7498 _cleanup_free_
char *instance
= NULL
;
7500 r
= unit_name_to_instance(*name
, &instance
);
7504 r
= unit_name_replace_instance(unit_name
, instance
, &tmp_name
);
7508 unit_name
= tmp_name
;
7512 r
= unit_file_create_copy(&lp
, unit_name
, path
, &new_path
, &tmp_path
);
7514 r
= unit_file_create_new(&lp
, unit_name
, ".d/override.conf", &new_path
, &tmp_path
);
7519 r
= strv_push_pair(paths
, new_path
, tmp_path
);
7523 new_path
= tmp_path
= NULL
;
7529 static int edit(int argc
, char *argv
[], void *userdata
) {
7530 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
7531 _cleanup_strv_free_
char **names
= NULL
;
7532 _cleanup_strv_free_
char **paths
= NULL
;
7533 char **original
, **tmp
;
7538 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit units if not on a tty.");
7540 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
7541 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit units remotely.");
7543 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
7545 return log_error_errno(r
, "Failed to determine unit paths: %m");
7547 r
= acquire_bus(BUS_MANAGER
, &bus
);
7551 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
7553 return log_error_errno(r
, "Failed to expand names: %m");
7555 STRV_FOREACH(tmp
, names
) {
7556 r
= unit_is_masked(bus
, &lp
, *tmp
);
7560 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit %s: unit is masked.", *tmp
);
7563 r
= find_paths_to_edit(bus
, names
, &paths
);
7567 if (strv_isempty(paths
))
7570 r
= run_editor(paths
);
7574 STRV_FOREACH_PAIR(original
, tmp
, paths
) {
7575 /* If the temporary file is empty we ignore it.
7576 * This allows the user to cancel the modification.
7578 if (null_or_empty_path(*tmp
)) {
7579 log_warning("Editing \"%s\" canceled: temporary file is empty.", *original
);
7583 r
= rename(*tmp
, *original
);
7585 r
= log_error_errno(errno
, "Failed to rename \"%s\" to \"%s\": %m", *tmp
, *original
);
7592 if (!arg_no_reload
&& !install_client_side())
7593 r
= daemon_reload(argc
, argv
, userdata
);
7596 STRV_FOREACH_PAIR(original
, tmp
, paths
) {
7597 (void) unlink(*tmp
);
7599 /* Removing empty dropin dirs */
7601 _cleanup_free_
char *dir
;
7603 dir
= dirname_malloc(*original
);
7607 /* no need to check if the dir is empty, rmdir
7608 * does nothing if it is not the case.
7617 static int systemctl_help(void) {
7618 _cleanup_free_
char *link
= NULL
;
7621 (void) pager_open(arg_pager_flags
);
7623 r
= terminal_urlify_man("systemctl", "1", &link
);
7627 printf("%1$s [OPTIONS...] COMMAND ...\n\n"
7628 "%5$sQuery or send control commands to the system manager.%6$s\n"
7629 "\n%3$sUnit Commands:%4$s\n"
7630 " list-units [PATTERN...] List units currently in memory\n"
7631 " list-sockets [PATTERN...] List socket units currently in memory,\n"
7632 " ordered by address\n"
7633 " list-timers [PATTERN...] List timer units currently in memory,\n"
7634 " ordered by next elapse\n"
7635 " start UNIT... Start (activate) one or more units\n"
7636 " stop UNIT... Stop (deactivate) one or more units\n"
7637 " reload UNIT... Reload one or more units\n"
7638 " restart UNIT... Start or restart one or more units\n"
7639 " try-restart UNIT... Restart one or more units if active\n"
7640 " reload-or-restart UNIT... Reload one or more units if possible,\n"
7641 " otherwise start or restart\n"
7642 " try-reload-or-restart UNIT... If active, reload one or more units,\n"
7643 " if supported, otherwise restart\n"
7644 " isolate UNIT Start one unit and stop all others\n"
7645 " kill UNIT... Send signal to processes of a unit\n"
7646 " clean UNIT... Clean runtime, cache, state, logs or\n"
7647 " configuration of unit\n"
7648 " freeze PATTERN... Freeze execution of unit processes\n"
7649 " thaw PATTERN... Resume execution of a frozen unit\n"
7650 " is-active PATTERN... Check whether units are active\n"
7651 " is-failed PATTERN... Check whether units are failed\n"
7652 " status [PATTERN...|PID...] Show runtime status of one or more units\n"
7653 " show [PATTERN...|JOB...] Show properties of one or more\n"
7654 " units/jobs or the manager\n"
7655 " cat PATTERN... Show files and drop-ins of specified units\n"
7656 " set-property UNIT PROPERTY=VALUE... Sets one or more properties of a unit\n"
7657 " help PATTERN...|PID... Show manual for one or more units\n"
7658 " reset-failed [PATTERN...] Reset failed state for all, one, or more\n"
7660 " list-dependencies [UNIT...] Recursively show units which are required\n"
7661 " or wanted by the units or by which those\n"
7662 " units are required or wanted"
7663 "\n%3$sUnit File Commands:%4$s\n"
7664 " list-unit-files [PATTERN...] List installed unit files\n"
7665 " enable [UNIT...|PATH...] Enable one or more unit files\n"
7666 " disable UNIT... Disable one or more unit files\n"
7667 " reenable UNIT... Reenable one or more unit files\n"
7668 " preset UNIT... Enable/disable one or more unit files\n"
7669 " based on preset configuration\n"
7670 " preset-all Enable/disable all unit files based on\n"
7671 " preset configuration\n"
7672 " is-enabled UNIT... Check whether unit files are enabled\n"
7673 " mask UNIT... Mask one or more units\n"
7674 " unmask UNIT... Unmask one or more units\n"
7675 " link PATH... Link one or more units files into\n"
7676 " the search path\n"
7677 " revert UNIT... Revert one or more unit files to vendor\n"
7679 " add-wants TARGET UNIT... Add 'Wants' dependency for the target\n"
7680 " on specified one or more units\n"
7681 " add-requires TARGET UNIT... Add 'Requires' dependency for the target\n"
7682 " on specified one or more units\n"
7683 " edit UNIT... Edit one or more unit files\n"
7684 " get-default Get the name of the default target\n"
7685 " set-default TARGET Set the default target\n"
7686 "\n%3$sMachine Commands:%4$s\n"
7687 " list-machines [PATTERN...] List local containers and host\n"
7688 "\n%3$sJob Commands:%4$s\n"
7689 " list-jobs [PATTERN...] List jobs\n"
7690 " cancel [JOB...] Cancel all, one, or more jobs\n"
7691 "\n%3$sEnvironment Commands:%4$s\n"
7692 " show-environment Dump environment\n"
7693 " set-environment VARIABLE=VALUE... Set one or more environment variables\n"
7694 " unset-environment VARIABLE... Unset one or more environment variables\n"
7695 " import-environment [VARIABLE...] Import all or some environment variables\n"
7696 "\n%3$sManager State Commands:%4$s\n"
7697 " daemon-reload Reload systemd manager configuration\n"
7698 " daemon-reexec Reexecute systemd manager\n"
7699 " log-level [LEVEL] Get/set logging threshold for manager\n"
7700 " log-target [TARGET] Get/set logging target for manager\n"
7701 " service-watchdogs [BOOL] Get/set service watchdog state\n"
7702 "\n%3$sSystem Commands:%4$s\n"
7703 " is-system-running Check whether system is fully running\n"
7704 " default Enter system default mode\n"
7705 " rescue Enter system rescue mode\n"
7706 " emergency Enter system emergency mode\n"
7707 " halt Shut down and halt the system\n"
7708 " poweroff Shut down and power-off the system\n"
7709 " reboot [ARG] Shut down and reboot the system\n"
7710 " kexec Shut down and reboot the system with kexec\n"
7711 " exit [EXIT_CODE] Request user instance or container exit\n"
7712 " switch-root ROOT [INIT] Change to a different root file system\n"
7713 " suspend Suspend the system\n"
7714 " hibernate Hibernate the system\n"
7715 " hybrid-sleep Hibernate and suspend the system\n"
7716 " suspend-then-hibernate Suspend the system, wake after a period of\n"
7717 " time, and hibernate"
7718 "\n%3$sOptions:%4$s\n"
7719 " -h --help Show this help\n"
7720 " --version Show package version\n"
7721 " --system Connect to system manager\n"
7722 " --user Connect to user service manager\n"
7723 " -H --host=[USER@]HOST Operate on remote host\n"
7724 " -M --machine=CONTAINER Operate on a local container\n"
7725 " -t --type=TYPE List units of a particular type\n"
7726 " --state=STATE List units with particular LOAD or SUB or ACTIVE state\n"
7727 " --failed Shorcut for --state=failed\n"
7728 " -p --property=NAME Show only properties by this name\n"
7729 " -P NAME Equivalent to --value --property=NAME\n"
7730 " -a --all Show all properties/all units currently in memory,\n"
7731 " including dead/empty ones. To list all units installed\n"
7732 " on the system, use 'list-unit-files' instead.\n"
7733 " -l --full Don't ellipsize unit names on output\n"
7734 " -r --recursive Show unit list of host and local containers\n"
7735 " --reverse Show reverse dependencies with 'list-dependencies'\n"
7736 " --with-dependencies Show unit dependencies with 'status', 'cat',\n"
7737 " 'list-units', and 'list-unit-files'.\n"
7738 " --job-mode=MODE Specify how to deal with already queued jobs, when\n"
7739 " queueing a new job\n"
7740 " -T --show-transaction When enqueuing a unit job, show full transaction\n"
7741 " --show-types When showing sockets, explicitly show their type\n"
7742 " --value When showing properties, only print the value\n"
7743 " -i --ignore-inhibitors When shutting down or sleeping, ignore inhibitors\n"
7744 " --kill-who=WHO Whom to send signal to\n"
7745 " -s --signal=SIGNAL Which signal to send\n"
7746 " --what=RESOURCES Which types of resources to remove\n"
7747 " --now Start or stop unit after enabling or disabling it\n"
7748 " --dry-run Only print what would be done\n"
7749 " Currently supported by verbs: halt, poweroff, reboot,\n"
7750 " kexec, suspend, hibernate, suspend-then-hibernate,\n"
7751 " hybrid-sleep, default, rescue, emergency, and exit.\n"
7752 " -q --quiet Suppress output\n"
7753 " --wait For (re)start, wait until service stopped again\n"
7754 " For is-system-running, wait until startup is completed\n"
7755 " --no-block Do not wait until operation finished\n"
7756 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7757 " --no-reload Don't reload daemon after en-/dis-abling unit files\n"
7758 " --no-legend Do not print a legend (column headers and hints)\n"
7759 " --no-pager Do not pipe output into a pager\n"
7760 " --no-ask-password Do not ask for system passwords\n"
7761 " --global Enable/disable/mask unit files globally\n"
7762 " --runtime Enable/disable/mask unit files temporarily until next\n"
7764 " -f --force When enabling unit files, override existing symlinks\n"
7765 " When shutting down, execute action immediately\n"
7766 " --preset-mode= Apply only enable, only disable, or all presets\n"
7767 " --root=PATH Enable/disable/mask unit files in the specified root\n"
7769 " -n --lines=INTEGER Number of journal entries to show\n"
7770 " -o --output=STRING Change journal output mode (short, short-precise,\n"
7771 " short-iso, short-iso-precise, short-full,\n"
7772 " short-monotonic, short-unix,\n"
7773 " verbose, export, json, json-pretty, json-sse, cat)\n"
7774 " --firmware-setup Tell the firmware to show the setup menu on next boot\n"
7775 " --boot-loader-menu=TIME\n"
7776 " Boot into boot loader menu on next boot\n"
7777 " --boot-loader-entry=NAME\n"
7778 " Boot into a specific boot loader entry on next boot\n"
7779 " --plain Print unit dependencies as a list instead of a tree\n"
7780 "\nSee the %2$s for details.\n"
7781 , program_invocation_short_name
7783 , ansi_underline(), ansi_normal()
7784 , ansi_highlight(), ansi_normal()
7790 static int halt_help(void) {
7791 _cleanup_free_
char *link
= NULL
;
7794 r
= terminal_urlify_man("halt", "8", &link
);
7798 printf("%s [OPTIONS...]%s\n"
7799 "\n%s%s the system.%s\n"
7801 " --help Show this help\n"
7802 " --halt Halt the machine\n"
7803 " -p --poweroff Switch off the machine\n"
7804 " --reboot Reboot the machine\n"
7805 " -f --force Force immediate halt/power-off/reboot\n"
7806 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
7807 " -d --no-wtmp Don't write wtmp record\n"
7808 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7809 "\nSee the %s for details.\n"
7810 , program_invocation_short_name
7811 , arg_action
== ACTION_REBOOT
? " [ARG]" : ""
7813 , arg_action
== ACTION_REBOOT
? "Reboot" :
7814 arg_action
== ACTION_POWEROFF
? "Power off" :
7823 static int shutdown_help(void) {
7824 _cleanup_free_
char *link
= NULL
;
7827 r
= terminal_urlify_man("shutdown", "8", &link
);
7831 printf("%s [OPTIONS...] [TIME] [WALL...]\n"
7832 "\n%sShut down the system.%s\n"
7834 " --help Show this help\n"
7835 " -H --halt Halt the machine\n"
7836 " -P --poweroff Power-off the machine\n"
7837 " -r --reboot Reboot the machine\n"
7838 " -h Equivalent to --poweroff, overridden by --halt\n"
7839 " -k Don't halt/power-off/reboot, just send warnings\n"
7840 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7841 " -c Cancel a pending shutdown\n"
7842 "\nSee the %s for details.\n"
7843 , program_invocation_short_name
7844 , ansi_highlight(), ansi_normal()
7851 static int telinit_help(void) {
7852 _cleanup_free_
char *link
= NULL
;
7855 r
= terminal_urlify_man("telinit", "8", &link
);
7859 printf("%s [OPTIONS...] COMMAND\n\n"
7860 "%sSend control commands to the init daemon.%s\n"
7862 " 0 Power-off the machine\n"
7863 " 6 Reboot the machine\n"
7864 " 2, 3, 4, 5 Start runlevelX.target unit\n"
7865 " 1, s, S Enter rescue mode\n"
7866 " q, Q Reload init daemon configuration\n"
7867 " u, U Reexecute init daemon\n"
7869 " --help Show this help\n"
7870 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7871 "\nSee the %s for details.\n"
7872 , program_invocation_short_name
7873 , ansi_highlight(), ansi_normal()
7880 static int runlevel_help(void) {
7881 _cleanup_free_
char *link
= NULL
;
7884 r
= terminal_urlify_man("runlevel", "8", &link
);
7888 printf("%s [OPTIONS...]\n"
7889 "\n%sPrints the previous and current runlevel of the init system.%s\n"
7891 " --help Show this help\n"
7892 "\nSee the %s for details.\n"
7893 , program_invocation_short_name
7894 , ansi_highlight(), ansi_normal()
7901 static void help_types(void) {
7903 puts("Available unit types:");
7905 DUMP_STRING_TABLE(unit_type
, UnitType
, _UNIT_TYPE_MAX
);
7908 static void help_states(void) {
7910 puts("Available unit load states:");
7911 DUMP_STRING_TABLE(unit_load_state
, UnitLoadState
, _UNIT_LOAD_STATE_MAX
);
7914 puts("\nAvailable unit active states:");
7915 DUMP_STRING_TABLE(unit_active_state
, UnitActiveState
, _UNIT_ACTIVE_STATE_MAX
);
7918 puts("\nAvailable unit file states:");
7919 DUMP_STRING_TABLE(unit_file_state
, UnitFileState
, _UNIT_FILE_STATE_MAX
);
7922 puts("\nAvailable automount unit substates:");
7923 DUMP_STRING_TABLE(automount_state
, AutomountState
, _AUTOMOUNT_STATE_MAX
);
7926 puts("\nAvailable device unit substates:");
7927 DUMP_STRING_TABLE(device_state
, DeviceState
, _DEVICE_STATE_MAX
);
7930 puts("\nAvailable mount unit substates:");
7931 DUMP_STRING_TABLE(mount_state
, MountState
, _MOUNT_STATE_MAX
);
7934 puts("\nAvailable path unit substates:");
7935 DUMP_STRING_TABLE(path_state
, PathState
, _PATH_STATE_MAX
);
7938 puts("\nAvailable scope unit substates:");
7939 DUMP_STRING_TABLE(scope_state
, ScopeState
, _SCOPE_STATE_MAX
);
7942 puts("\nAvailable service unit substates:");
7943 DUMP_STRING_TABLE(service_state
, ServiceState
, _SERVICE_STATE_MAX
);
7946 puts("\nAvailable slice unit substates:");
7947 DUMP_STRING_TABLE(slice_state
, SliceState
, _SLICE_STATE_MAX
);
7950 puts("\nAvailable socket unit substates:");
7951 DUMP_STRING_TABLE(socket_state
, SocketState
, _SOCKET_STATE_MAX
);
7954 puts("\nAvailable swap unit substates:");
7955 DUMP_STRING_TABLE(swap_state
, SwapState
, _SWAP_STATE_MAX
);
7958 puts("\nAvailable target unit substates:");
7959 DUMP_STRING_TABLE(target_state
, TargetState
, _TARGET_STATE_MAX
);
7962 puts("\nAvailable timer unit substates:");
7963 DUMP_STRING_TABLE(timer_state
, TimerState
, _TIMER_STATE_MAX
);
7966 static int help_boot_loader_entry(void) {
7967 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7968 _cleanup_strv_free_
char **l
= NULL
;
7973 r
= acquire_bus(BUS_FULL
, &bus
);
7977 r
= bus_get_property_strv(bus
, bus_login_mgr
, "BootLoaderEntries", &error
, &l
);
7979 return log_error_errno(r
, "Failed to enumerate boot loader entries: %s", bus_error_message(&error
, r
));
7981 if (strv_isempty(l
))
7982 return log_error_errno(SYNTHETIC_ERRNO(ENODATA
), "No boot loader entries discovered.");
7990 static int systemctl_parse_argv(int argc
, char *argv
[]) {
7999 ARG_IGNORE_DEPENDENCIES
,
8012 ARG_NO_ASK_PASSWORD
,
8020 ARG_BOOT_LOADER_MENU
,
8021 ARG_BOOT_LOADER_ENTRY
,
8024 ARG_WITH_DEPENDENCIES
,
8029 static const struct option options
[] = {
8030 { "help", no_argument
, NULL
, 'h' },
8031 { "version", no_argument
, NULL
, ARG_VERSION
},
8032 { "type", required_argument
, NULL
, 't' },
8033 { "property", required_argument
, NULL
, 'p' },
8034 { "all", no_argument
, NULL
, 'a' },
8035 { "reverse", no_argument
, NULL
, ARG_REVERSE
},
8036 { "after", no_argument
, NULL
, ARG_AFTER
},
8037 { "before", no_argument
, NULL
, ARG_BEFORE
},
8038 { "show-types", no_argument
, NULL
, ARG_SHOW_TYPES
},
8039 { "failed", no_argument
, NULL
, ARG_FAILED
}, /* compatibility only */
8040 { "full", no_argument
, NULL
, 'l' },
8041 { "job-mode", required_argument
, NULL
, ARG_JOB_MODE
},
8042 { "fail", no_argument
, NULL
, ARG_FAIL
}, /* compatibility only */
8043 { "irreversible", no_argument
, NULL
, ARG_IRREVERSIBLE
}, /* compatibility only */
8044 { "ignore-dependencies", no_argument
, NULL
, ARG_IGNORE_DEPENDENCIES
}, /* compatibility only */
8045 { "ignore-inhibitors", no_argument
, NULL
, 'i' },
8046 { "value", no_argument
, NULL
, ARG_VALUE
},
8047 { "user", no_argument
, NULL
, ARG_USER
},
8048 { "system", no_argument
, NULL
, ARG_SYSTEM
},
8049 { "global", no_argument
, NULL
, ARG_GLOBAL
},
8050 { "wait", no_argument
, NULL
, ARG_WAIT
},
8051 { "no-block", no_argument
, NULL
, ARG_NO_BLOCK
},
8052 { "no-legend", no_argument
, NULL
, ARG_NO_LEGEND
},
8053 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
8054 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8055 { "dry-run", no_argument
, NULL
, ARG_DRY_RUN
},
8056 { "quiet", no_argument
, NULL
, 'q' },
8057 { "root", required_argument
, NULL
, ARG_ROOT
},
8058 { "force", no_argument
, NULL
, 'f' },
8059 { "no-reload", no_argument
, NULL
, ARG_NO_RELOAD
},
8060 { "kill-who", required_argument
, NULL
, ARG_KILL_WHO
},
8061 { "signal", required_argument
, NULL
, 's' },
8062 { "no-ask-password", no_argument
, NULL
, ARG_NO_ASK_PASSWORD
},
8063 { "host", required_argument
, NULL
, 'H' },
8064 { "machine", required_argument
, NULL
, 'M' },
8065 { "runtime", no_argument
, NULL
, ARG_RUNTIME
},
8066 { "lines", required_argument
, NULL
, 'n' },
8067 { "output", required_argument
, NULL
, 'o' },
8068 { "plain", no_argument
, NULL
, ARG_PLAIN
},
8069 { "state", required_argument
, NULL
, ARG_STATE
},
8070 { "recursive", no_argument
, NULL
, 'r' },
8071 { "with-dependencies", no_argument
, NULL
, ARG_WITH_DEPENDENCIES
},
8072 { "preset-mode", required_argument
, NULL
, ARG_PRESET_MODE
},
8073 { "firmware-setup", no_argument
, NULL
, ARG_FIRMWARE_SETUP
},
8074 { "boot-loader-menu", required_argument
, NULL
, ARG_BOOT_LOADER_MENU
},
8075 { "boot-loader-entry", required_argument
, NULL
, ARG_BOOT_LOADER_ENTRY
},
8076 { "now", no_argument
, NULL
, ARG_NOW
},
8077 { "message", required_argument
, NULL
, ARG_MESSAGE
},
8078 { "show-transaction", no_argument
, NULL
, 'T' },
8079 { "what", required_argument
, NULL
, ARG_WHAT
},
8088 /* we default to allowing interactive authorization only in systemctl (not in the legacy commands) */
8089 arg_ask_password
= true;
8091 while ((c
= getopt_long(argc
, argv
, "ht:p:P:alqfs:H:M:n:o:iTr.::", options
, NULL
)) >= 0)
8096 return systemctl_help();
8104 if (isempty(optarg
))
8105 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8106 "--type= requires arguments.");
8108 for (p
= optarg
;;) {
8109 _cleanup_free_
char *type
= NULL
;
8111 r
= extract_first_word(&p
, &type
, ",", 0);
8113 return log_error_errno(r
, "Failed to parse type: %s", optarg
);
8117 if (streq(type
, "help")) {
8122 if (unit_type_from_string(type
) >= 0) {
8123 if (strv_consume(&arg_types
, TAKE_PTR(type
)) < 0)
8128 /* It's much nicer to use --state= for
8129 * load states, but let's support this
8130 * in --types= too for compatibility
8131 * with old versions */
8132 if (unit_load_state_from_string(type
) >= 0) {
8133 if (strv_consume(&arg_states
, TAKE_PTR(type
)) < 0)
8138 log_error("Unknown unit type or load state '%s'.", type
);
8139 return log_info_errno(SYNTHETIC_ERRNO(EINVAL
),
8140 "Use -t help to see a list of allowed values.");
8151 /* Make sure that if the empty property list was specified, we won't show any
8153 if (isempty(optarg
) && !arg_properties
) {
8154 arg_properties
= new0(char*, 1);
8155 if (!arg_properties
)
8160 for (p
= optarg
;;) {
8161 _cleanup_free_
char *prop
= NULL
;
8163 r
= extract_first_word(&p
, &prop
, ",", 0);
8165 return log_error_errno(r
, "Failed to parse property: %s", optarg
);
8169 if (strv_consume(&arg_properties
, TAKE_PTR(prop
)) < 0)
8174 /* If the user asked for a particular property, show it, even if it is empty. */
8184 arg_dependency
= DEPENDENCY_REVERSE
;
8188 arg_dependency
= DEPENDENCY_AFTER
;
8189 arg_jobs_after
= true;
8193 arg_dependency
= DEPENDENCY_BEFORE
;
8194 arg_jobs_before
= true;
8197 case ARG_SHOW_TYPES
:
8198 arg_show_types
= true;
8206 arg_job_mode
= optarg
;
8210 arg_job_mode
= "fail";
8213 case ARG_IRREVERSIBLE
:
8214 arg_job_mode
= "replace-irreversibly";
8217 case ARG_IGNORE_DEPENDENCIES
:
8218 arg_job_mode
= "ignore-dependencies";
8222 arg_scope
= UNIT_FILE_USER
;
8226 arg_scope
= UNIT_FILE_SYSTEM
;
8230 arg_scope
= UNIT_FILE_GLOBAL
;
8238 arg_no_block
= true;
8242 arg_no_legend
= true;
8246 arg_pager_flags
|= PAGER_DISABLE
;
8254 r
= parse_path_argument_and_warn(optarg
, false, &arg_root
);
8264 if (strv_extend(&arg_states
, "failed") < 0)
8282 arg_no_reload
= true;
8286 arg_kill_who
= optarg
;
8290 if (streq(optarg
, "help")) {
8291 DUMP_STRING_TABLE(signal
, int, _NSIG
);
8295 arg_signal
= signal_from_string(optarg
);
8297 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8298 "Failed to parse signal string %s.",
8302 case ARG_NO_ASK_PASSWORD
:
8303 arg_ask_password
= false;
8307 arg_transport
= BUS_TRANSPORT_REMOTE
;
8312 arg_transport
= BUS_TRANSPORT_MACHINE
;
8321 if (safe_atou(optarg
, &arg_lines
) < 0)
8322 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8323 "Failed to parse lines '%s'",
8328 if (streq(optarg
, "help")) {
8329 DUMP_STRING_TABLE(output_mode
, OutputMode
, _OUTPUT_MODE_MAX
);
8333 arg_output
= output_mode_from_string(optarg
);
8335 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8336 "Unknown output '%s'.",
8339 if (OUTPUT_MODE_IS_JSON(arg_output
)) {
8340 arg_no_legend
= true;
8346 arg_ignore_inhibitors
= true;
8353 case ARG_FIRMWARE_SETUP
:
8354 arg_firmware_setup
= true;
8357 case ARG_BOOT_LOADER_MENU
:
8359 r
= parse_sec(optarg
, &arg_boot_loader_menu
);
8361 return log_error_errno(r
, "Failed to parse --boot-loader-menu= argument '%s': %m", optarg
);
8365 case ARG_BOOT_LOADER_ENTRY
:
8367 if (streq(optarg
, "help")) { /* Yes, this means, "help" is not a valid boot loader entry name we can deal with */
8368 r
= help_boot_loader_entry();
8375 arg_boot_loader_entry
= empty_to_null(optarg
);
8381 if (isempty(optarg
))
8382 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8383 "--state= requires arguments.");
8385 for (p
= optarg
;;) {
8386 _cleanup_free_
char *s
= NULL
;
8388 r
= extract_first_word(&p
, &s
, ",", 0);
8390 return log_error_errno(r
, "Failed to parse state: %s", optarg
);
8394 if (streq(s
, "help")) {
8399 if (strv_consume(&arg_states
, TAKE_PTR(s
)) < 0)
8407 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
8408 "--recursive requires root privileges.");
8410 arg_recursive
= true;
8413 case ARG_PRESET_MODE
:
8414 if (streq(optarg
, "help")) {
8415 DUMP_STRING_TABLE(unit_file_preset_mode
, UnitFilePresetMode
, _UNIT_FILE_PRESET_MAX
);
8419 arg_preset_mode
= unit_file_preset_mode_from_string(optarg
);
8420 if (arg_preset_mode
< 0)
8421 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8422 "Failed to parse preset mode: %s.", optarg
);
8431 if (strv_extend(&arg_wall
, optarg
) < 0)
8436 arg_show_transaction
= true;
8439 case ARG_WITH_DEPENDENCIES
:
8440 arg_with_dependencies
= true;
8446 if (isempty(optarg
))
8447 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "--what= requires arguments.");
8449 for (p
= optarg
;;) {
8450 _cleanup_free_
char *k
= NULL
;
8452 r
= extract_first_word(&p
, &k
, ",", 0);
8454 return log_error_errno(r
, "Failed to parse directory type: %s", optarg
);
8458 if (streq(k
, "help")) {
8467 r
= strv_consume(&arg_clean_what
, TAKE_PTR(k
));
8476 /* Output an error mimicking getopt, and print a hint afterwards */
8477 log_error("%s: invalid option -- '.'", program_invocation_name
);
8478 log_notice("Hint: to specify units starting with a dash, use \"--\":\n"
8479 " %s [OPTIONS...] COMMAND -- -.%s ...",
8480 program_invocation_name
, optarg
?: "mount");
8487 assert_not_reached("Unhandled option");
8490 if (arg_transport
!= BUS_TRANSPORT_LOCAL
&& arg_scope
!= UNIT_FILE_SYSTEM
)
8491 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8492 "Cannot access user instance remotely.");
8494 if (arg_wait
&& arg_no_block
)
8495 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8496 "--wait may not be combined with --no-block.");
8501 static int halt_parse_argv(int argc
, char *argv
[]) {
8509 static const struct option options
[] = {
8510 { "help", no_argument
, NULL
, ARG_HELP
},
8511 { "halt", no_argument
, NULL
, ARG_HALT
},
8512 { "poweroff", no_argument
, NULL
, 'p' },
8513 { "reboot", no_argument
, NULL
, ARG_REBOOT
},
8514 { "force", no_argument
, NULL
, 'f' },
8515 { "wtmp-only", no_argument
, NULL
, 'w' },
8516 { "no-wtmp", no_argument
, NULL
, 'd' },
8517 { "no-sync", no_argument
, NULL
, 'n' },
8518 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8527 if (utmp_get_runlevel(&runlevel
, NULL
) >= 0)
8528 if (IN_SET(runlevel
, '0', '6'))
8531 while ((c
= getopt_long(argc
, argv
, "pfwdnih", options
, NULL
)) >= 0)
8538 arg_action
= ACTION_HALT
;
8542 if (arg_action
!= ACTION_REBOOT
)
8543 arg_action
= ACTION_POWEROFF
;
8547 arg_action
= ACTION_REBOOT
;
8572 /* Compatibility nops */
8579 assert_not_reached("Unhandled option");
8582 if (arg_action
== ACTION_REBOOT
&& (argc
== optind
|| argc
== optind
+ 1)) {
8583 r
= update_reboot_parameter_and_warn(argc
== optind
+ 1 ? argv
[optind
] : NULL
, false);
8586 } else if (optind
< argc
)
8587 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8588 "Too many arguments.");
8593 static int shutdown_parse_argv(int argc
, char *argv
[]) {
8599 static const struct option options
[] = {
8600 { "help", no_argument
, NULL
, ARG_HELP
},
8601 { "halt", no_argument
, NULL
, 'H' },
8602 { "poweroff", no_argument
, NULL
, 'P' },
8603 { "reboot", no_argument
, NULL
, 'r' },
8604 { "kexec", no_argument
, NULL
, 'K' }, /* not documented extension */
8605 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8615 while ((c
= getopt_long(argc
, argv
, "HPrhkKat:fFc", options
, NULL
)) >= 0)
8619 return shutdown_help();
8622 arg_action
= ACTION_HALT
;
8626 arg_action
= ACTION_POWEROFF
;
8631 arg_action
= ACTION_KEXEC
;
8633 arg_action
= ACTION_REBOOT
;
8637 arg_action
= ACTION_KEXEC
;
8641 if (arg_action
!= ACTION_HALT
)
8642 arg_action
= ACTION_POWEROFF
;
8654 case 't': /* Note that we also ignore any passed argument to -t, not just the -t itself */
8657 /* Compatibility nops */
8661 arg_action
= ACTION_CANCEL_SHUTDOWN
;
8668 assert_not_reached("Unhandled option");
8671 if (argc
> optind
&& arg_action
!= ACTION_CANCEL_SHUTDOWN
) {
8672 r
= parse_shutdown_time_spec(argv
[optind
], &arg_when
);
8674 log_error("Failed to parse time specification: %s", argv
[optind
]);
8678 arg_when
= now(CLOCK_REALTIME
) + USEC_PER_MINUTE
;
8680 if (argc
> optind
&& arg_action
== ACTION_CANCEL_SHUTDOWN
)
8681 /* No time argument for shutdown cancel */
8682 wall
= argv
+ optind
;
8683 else if (argc
> optind
+ 1)
8684 /* We skip the time argument */
8685 wall
= argv
+ optind
+ 1;
8688 arg_wall
= strv_copy(wall
);
8698 static int telinit_parse_argv(int argc
, char *argv
[]) {
8704 static const struct option options
[] = {
8705 { "help", no_argument
, NULL
, ARG_HELP
},
8706 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8710 static const struct {
8714 { '0', ACTION_POWEROFF
},
8715 { '6', ACTION_REBOOT
},
8716 { '1', ACTION_RESCUE
},
8717 { '2', ACTION_RUNLEVEL2
},
8718 { '3', ACTION_RUNLEVEL3
},
8719 { '4', ACTION_RUNLEVEL4
},
8720 { '5', ACTION_RUNLEVEL5
},
8721 { 's', ACTION_RESCUE
},
8722 { 'S', ACTION_RESCUE
},
8723 { 'q', ACTION_RELOAD
},
8724 { 'Q', ACTION_RELOAD
},
8725 { 'u', ACTION_REEXEC
},
8726 { 'U', ACTION_REEXEC
}
8735 while ((c
= getopt_long(argc
, argv
, "", options
, NULL
)) >= 0)
8739 return telinit_help();
8749 assert_not_reached("Unhandled option");
8753 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8754 "%s: required argument missing.",
8755 program_invocation_short_name
);
8757 if (optind
+ 1 < argc
)
8758 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8759 "Too many arguments.");
8761 if (strlen(argv
[optind
]) != 1)
8762 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8763 "Expected single character argument.");
8765 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
8766 if (table
[i
].from
== argv
[optind
][0])
8769 if (i
>= ELEMENTSOF(table
))
8770 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8771 "Unknown command '%s'.", argv
[optind
]);
8773 arg_action
= table
[i
].to
;
8780 static int runlevel_parse_argv(int argc
, char *argv
[]) {
8785 static const struct option options
[] = {
8786 { "help", no_argument
, NULL
, ARG_HELP
},
8795 while ((c
= getopt_long(argc
, argv
, "", options
, NULL
)) >= 0)
8799 return runlevel_help();
8805 assert_not_reached("Unhandled option");
8809 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8810 "Too many arguments.");
8815 static int parse_argv(int argc
, char *argv
[]) {
8819 if (program_invocation_short_name
) {
8821 if (strstr(program_invocation_short_name
, "halt")) {
8822 arg_action
= ACTION_HALT
;
8823 return halt_parse_argv(argc
, argv
);
8825 } else if (strstr(program_invocation_short_name
, "poweroff")) {
8826 arg_action
= ACTION_POWEROFF
;
8827 return halt_parse_argv(argc
, argv
);
8829 } else if (strstr(program_invocation_short_name
, "reboot")) {
8831 arg_action
= ACTION_KEXEC
;
8833 arg_action
= ACTION_REBOOT
;
8834 return halt_parse_argv(argc
, argv
);
8836 } else if (strstr(program_invocation_short_name
, "shutdown")) {
8837 arg_action
= ACTION_POWEROFF
;
8838 return shutdown_parse_argv(argc
, argv
);
8840 } else if (strstr(program_invocation_short_name
, "init")) {
8842 /* Matches invocations as "init" as well as "telinit", which are synonymous when run as PID !=
8845 * On SysV "telinit" was the official command to communicate with PID 1, but "init" would
8846 * redirect itself to "telinit" if called with PID != 1. We follow the same logic here still,
8847 * though we add one level of indirection, as we implement "telinit" in "systemctl". Hence, for
8848 * us if you invoke "init" you get "systemd", but it will execve() "systemctl" immediately with
8849 * argv[] unmodified if PID is != 1. If you invoke "telinit" you directly get "systemctl". In
8850 * both cases we shall do the same thing, which is why we do strstr(p_i_s_n, "init") here, as a
8851 * quick way to match both.
8853 * Also see redirect_telinit() in src/core/main.c. */
8855 if (sd_booted() > 0) {
8856 arg_action
= _ACTION_INVALID
;
8857 return telinit_parse_argv(argc
, argv
);
8859 /* Hmm, so some other init system is running, we need to forward this request to
8860 * it. For now we simply guess that it is Upstart. */
8862 (void) rlimit_nofile_safe();
8863 execv(TELINIT
, argv
);
8865 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
8866 "Couldn't find an alternative telinit implementation to spawn.");
8869 } else if (strstr(program_invocation_short_name
, "runlevel")) {
8870 arg_action
= ACTION_RUNLEVEL
;
8871 return runlevel_parse_argv(argc
, argv
);
8875 arg_action
= ACTION_SYSTEMCTL
;
8876 return systemctl_parse_argv(argc
, argv
);
8879 #if HAVE_SYSV_COMPAT
8880 _pure_
static int action_to_runlevel(void) {
8881 static const char table
[_ACTION_MAX
] = {
8882 [ACTION_HALT
] = '0',
8883 [ACTION_POWEROFF
] = '0',
8884 [ACTION_REBOOT
] = '6',
8885 [ACTION_RUNLEVEL2
] = '2',
8886 [ACTION_RUNLEVEL3
] = '3',
8887 [ACTION_RUNLEVEL4
] = '4',
8888 [ACTION_RUNLEVEL5
] = '5',
8889 [ACTION_RESCUE
] = '1'
8892 assert(arg_action
>= 0 && arg_action
< _ACTION_MAX
);
8893 return table
[arg_action
];
8897 static int systemctl_main(int argc
, char *argv
[]) {
8898 static const Verb verbs
[] = {
8899 { "list-units", VERB_ANY
, VERB_ANY
, VERB_DEFAULT
|VERB_ONLINE_ONLY
, list_units
},
8900 { "list-unit-files", VERB_ANY
, VERB_ANY
, 0, list_unit_files
},
8901 { "list-sockets", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_sockets
},
8902 { "list-timers", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_timers
},
8903 { "list-jobs", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_jobs
},
8904 { "list-machines", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_machines
},
8905 { "clear-jobs", VERB_ANY
, 1, VERB_ONLINE_ONLY
, trivial_method
},
8906 { "cancel", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, cancel_job
},
8907 { "start", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
8908 { "stop", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
8909 { "condstop", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with ALTLinux */
8910 { "reload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
8911 { "restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
8912 { "try-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
8913 { "reload-or-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
8914 { "reload-or-try-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with old systemctl <= 228 */
8915 { "try-reload-or-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
8916 { "force-reload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with SysV */
8917 { "condreload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with ALTLinux */
8918 { "condrestart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with RH */
8919 { "isolate", 2, 2, VERB_ONLINE_ONLY
, start_unit
},
8920 { "kill", 2, VERB_ANY
, VERB_ONLINE_ONLY
, kill_unit
},
8921 { "clean", 2, VERB_ANY
, VERB_ONLINE_ONLY
, clean_or_freeze_unit
},
8922 { "freeze", 2, VERB_ANY
, VERB_ONLINE_ONLY
, clean_or_freeze_unit
},
8923 { "thaw", 2, VERB_ANY
, VERB_ONLINE_ONLY
, clean_or_freeze_unit
},
8924 { "is-active", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_active
},
8925 { "check", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_active
}, /* deprecated alias of is-active */
8926 { "is-failed", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_failed
},
8927 { "show", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
8928 { "cat", 2, VERB_ANY
, VERB_ONLINE_ONLY
, cat
},
8929 { "status", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
8930 { "help", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
8931 { "daemon-reload", VERB_ANY
, 1, VERB_ONLINE_ONLY
, daemon_reload
},
8932 { "daemon-reexec", VERB_ANY
, 1, VERB_ONLINE_ONLY
, daemon_reload
},
8933 { "log-level", VERB_ANY
, 2, VERB_ONLINE_ONLY
, log_level
},
8934 { "log-target", VERB_ANY
, 2, VERB_ONLINE_ONLY
, log_target
},
8935 { "service-watchdogs", VERB_ANY
, 2, VERB_ONLINE_ONLY
, service_watchdogs
},
8936 { "show-environment", VERB_ANY
, 1, VERB_ONLINE_ONLY
, show_environment
},
8937 { "set-environment", 2, VERB_ANY
, VERB_ONLINE_ONLY
, set_environment
},
8938 { "unset-environment", 2, VERB_ANY
, VERB_ONLINE_ONLY
, set_environment
},
8939 { "import-environment", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, import_environment
},
8940 { "halt", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
8941 { "poweroff", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
8942 { "reboot", VERB_ANY
, 2, VERB_ONLINE_ONLY
, start_system_special
},
8943 { "kexec", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
8944 { "suspend", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
8945 { "hibernate", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
8946 { "hybrid-sleep", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
8947 { "suspend-then-hibernate",VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
8948 { "default", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_special
},
8949 { "rescue", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
8950 { "emergency", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
8951 { "exit", VERB_ANY
, 2, VERB_ONLINE_ONLY
, start_special
},
8952 { "reset-failed", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, reset_failed
},
8953 { "enable", 2, VERB_ANY
, 0, enable_unit
},
8954 { "disable", 2, VERB_ANY
, 0, enable_unit
},
8955 { "is-enabled", 2, VERB_ANY
, 0, unit_is_enabled
},
8956 { "reenable", 2, VERB_ANY
, 0, enable_unit
},
8957 { "preset", 2, VERB_ANY
, 0, enable_unit
},
8958 { "preset-all", VERB_ANY
, 1, 0, preset_all
},
8959 { "mask", 2, VERB_ANY
, 0, enable_unit
},
8960 { "unmask", 2, VERB_ANY
, 0, enable_unit
},
8961 { "link", 2, VERB_ANY
, 0, enable_unit
},
8962 { "revert", 2, VERB_ANY
, 0, enable_unit
},
8963 { "switch-root", 2, VERB_ANY
, VERB_ONLINE_ONLY
, switch_root
},
8964 { "list-dependencies", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_dependencies
},
8965 { "set-default", 2, 2, 0, set_default
},
8966 { "get-default", VERB_ANY
, 1, 0, get_default
},
8967 { "set-property", 3, VERB_ANY
, VERB_ONLINE_ONLY
, set_property
},
8968 { "is-system-running", VERB_ANY
, 1, 0, is_system_running
},
8969 { "add-wants", 3, VERB_ANY
, 0, add_dependency
},
8970 { "add-requires", 3, VERB_ANY
, 0, add_dependency
},
8971 { "edit", 2, VERB_ANY
, VERB_ONLINE_ONLY
, edit
},
8975 const Verb
*verb
= verbs_find_verb(argv
[optind
], verbs
);
8976 if (verb
&& (verb
->flags
& VERB_ONLINE_ONLY
) && arg_root
)
8977 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8978 "Verb '%s' cannot be used with --root=.",
8979 argv
[optind
] ?: verb
->verb
);
8981 return dispatch_verb(argc
, argv
, verbs
, NULL
);
8984 static int reload_with_fallback(void) {
8985 /* First, try systemd via D-Bus. */
8986 if (daemon_reload(0, NULL
, NULL
) >= 0)
8989 /* Nothing else worked, so let's try signals */
8990 assert(IN_SET(arg_action
, ACTION_RELOAD
, ACTION_REEXEC
));
8992 if (kill(1, arg_action
== ACTION_RELOAD
? SIGHUP
: SIGTERM
) < 0)
8993 return log_error_errno(errno
, "kill() failed: %m");
8998 static int start_with_fallback(void) {
8999 /* First, try systemd via D-Bus. */
9000 if (start_unit(0, NULL
, NULL
) == 0)
9003 #if HAVE_SYSV_COMPAT
9004 /* Nothing else worked, so let's try /dev/initctl */
9005 if (talk_initctl(action_to_runlevel()) > 0)
9009 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
9010 "Failed to talk to init daemon.");
9013 static int halt_now(enum action a
) {
9014 /* The kernel will automatically flush ATA disks and suchlike on reboot(), but the file systems need to be
9015 * synced explicitly in advance. */
9016 if (!arg_no_sync
&& !arg_dry_run
)
9019 /* Make sure C-A-D is handled by the kernel from this point on... */
9021 (void) reboot(RB_ENABLE_CAD
);
9027 log_info("Halting.");
9030 (void) reboot(RB_HALT_SYSTEM
);
9033 case ACTION_POWEROFF
:
9035 log_info("Powering off.");
9038 (void) reboot(RB_POWER_OFF
);
9043 return reboot_with_parameter(REBOOT_FALLBACK
|
9044 (arg_quiet
? 0 : REBOOT_LOG
) |
9045 (arg_dry_run
? REBOOT_DRY_RUN
: 0));
9048 assert_not_reached("Unknown action.");
9052 static int logind_schedule_shutdown(void) {
9055 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
9056 char date
[FORMAT_TIMESTAMP_MAX
];
9061 r
= acquire_bus(BUS_FULL
, &bus
);
9065 switch (arg_action
) {
9069 case ACTION_POWEROFF
:
9070 action
= "poweroff";
9085 action
= strjoina("dry-", action
);
9087 (void) logind_set_wall_message();
9089 r
= bus_call_method(bus
, bus_login_mgr
, "ScheduleShutdown", &error
, NULL
, "st", action
, arg_when
);
9091 return log_warning_errno(r
, "Failed to call ScheduleShutdown in logind, proceeding with immediate shutdown: %s", bus_error_message(&error
, r
));
9094 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.", format_timestamp(date
, sizeof(date
), arg_when
));
9097 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
9098 "Cannot schedule shutdown without logind support, proceeding with immediate shutdown.");
9102 static int halt_main(void) {
9105 r
= logind_check_inhibitors(arg_action
);
9109 /* Delayed shutdown requested, and was successful */
9110 if (arg_when
> 0 && logind_schedule_shutdown() == 0)
9112 /* no delay, or logind failed or is not at all available */
9114 if (geteuid() != 0) {
9115 if (arg_dry_run
|| arg_force
> 0) {
9116 (void) must_be_root();
9120 /* Try logind if we are a normal user and no special
9121 * mode applies. Maybe polkit allows us to shutdown
9123 if (IN_SET(arg_action
, ACTION_POWEROFF
, ACTION_REBOOT
, ACTION_HALT
)) {
9124 r
= logind_reboot(arg_action
);
9127 if (IN_SET(r
, -EOPNOTSUPP
, -EINPROGRESS
))
9128 /* requested operation is not
9129 * supported on the local system or
9130 * already in progress */
9132 /* on all other errors, try low-level operation */
9136 /* In order to minimize the difference between operation with and
9137 * without logind, we explicitly enable non-blocking mode for this,
9138 * as logind's shutdown operations are always non-blocking. */
9139 arg_no_block
= true;
9141 if (!arg_dry_run
&& !arg_force
)
9142 return start_with_fallback();
9144 assert(geteuid() == 0);
9147 if (sd_booted() > 0)
9148 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
9150 r
= utmp_put_shutdown();
9152 log_warning_errno(r
, "Failed to write utmp record: %m");
9159 r
= halt_now(arg_action
);
9160 return log_error_errno(r
, "Failed to reboot: %m");
9163 static int runlevel_main(void) {
9164 int r
, runlevel
, previous
;
9166 r
= utmp_get_runlevel(&runlevel
, &previous
);
9173 previous
<= 0 ? 'N' : previous
,
9174 runlevel
<= 0 ? 'N' : runlevel
);
9179 static int logind_cancel_shutdown(void) {
9181 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
9185 r
= acquire_bus(BUS_FULL
, &bus
);
9189 (void) logind_set_wall_message();
9191 r
= bus_call_method(bus
, bus_login_mgr
, "CancelScheduledShutdown", &error
, NULL
, NULL
);
9193 return log_warning_errno(r
, "Failed to talk to logind, shutdown hasn't been cancelled: %s", bus_error_message(&error
, r
));
9197 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
9198 "Not compiled with logind support, cannot cancel scheduled shutdowns.");
9202 static int run(int argc
, char *argv
[]) {
9205 setlocale(LC_ALL
, "");
9206 log_parse_environment();
9209 /* The journal merging logic potentially needs a lot of fds. */
9210 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE
);
9214 /* Explicitly not on_tty() to avoid setting cached value.
9215 * This becomes relevant for piping output which might be
9217 original_stdout_is_tty
= isatty(STDOUT_FILENO
);
9219 r
= parse_argv(argc
, argv
);
9223 if (arg_action
!= ACTION_SYSTEMCTL
&& running_in_chroot() > 0) {
9225 log_info("Running in chroot, ignoring request.");
9230 /* systemctl_main() will print an error message for the bus
9231 * connection, but only if it needs to */
9233 switch (arg_action
) {
9235 case ACTION_SYSTEMCTL
:
9236 r
= systemctl_main(argc
, argv
);
9239 /* Legacy command aliases set arg_action. They provide some fallbacks,
9240 * e.g. to tell sysvinit to reboot after you have installed systemd
9244 case ACTION_POWEROFF
:
9250 case ACTION_RUNLEVEL2
:
9251 case ACTION_RUNLEVEL3
:
9252 case ACTION_RUNLEVEL4
:
9253 case ACTION_RUNLEVEL5
:
9255 r
= start_with_fallback();
9260 r
= reload_with_fallback();
9263 case ACTION_CANCEL_SHUTDOWN
:
9264 r
= logind_cancel_shutdown();
9267 case ACTION_RUNLEVEL
:
9268 r
= runlevel_main();
9272 case ACTION_SUSPEND
:
9273 case ACTION_HIBERNATE
:
9274 case ACTION_HYBRID_SLEEP
:
9275 case ACTION_SUSPEND_THEN_HIBERNATE
:
9276 case ACTION_EMERGENCY
:
9277 case ACTION_DEFAULT
:
9278 /* systemctl verbs with no equivalent in the legacy commands.
9279 * These cannot appear in arg_action. Fall through. */
9281 case _ACTION_INVALID
:
9283 assert_not_reached("Unknown action");
9289 /* Note that we return r here, not 0, so that we can implement the LSB-like return codes */
9293 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);