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-locator.h"
24 #include "bus-map-properties.h"
25 #include "bus-message.h"
26 #include "bus-print-properties.h"
27 #include "bus-unit-procs.h"
28 #include "bus-unit-util.h"
29 #include "bus-wait-for-jobs.h"
30 #include "bus-wait-for-units.h"
31 #include "cgroup-show.h"
32 #include "cgroup-util.h"
34 #include "cpu-set-util.h"
35 #include "dirent-util.h"
37 #include "efi-loader.h"
41 #include "exec-util.h"
42 #include "exit-status.h"
44 #include "format-table.h"
45 #include "format-util.h"
47 #include "glob-util.h"
48 #include "hexdecoct.h"
49 #include "hostname-util.h"
50 #include "in-addr-util.h"
54 #include "journal-util.h"
56 #include "locale-util.h"
58 #include "logs-show.h"
60 #include "main-func.h"
61 #include "memory-util.h"
63 #include "numa-util.h"
65 #include "parse-util.h"
66 #include "path-lookup.h"
67 #include "path-util.h"
68 #include "pretty-print.h"
69 #include "proc-cmdline.h"
70 #include "process-util.h"
71 #include "reboot-util.h"
72 #include "rlimit-util.h"
75 #include "signal-util.h"
76 #include "socket-util.h"
77 #include "sort-util.h"
78 #include "spawn-ask-password-agent.h"
79 #include "spawn-polkit-agent.h"
81 #include "stat-util.h"
82 #include "string-table.h"
84 #include "sysv-compat.h"
85 #include "terminal-util.h"
86 #include "tmpfile-util.h"
88 #include "unit-file.h"
89 #include "unit-name.h"
90 #include "user-util.h"
92 #include "utmp-wtmp.h"
96 static char **arg_types
= NULL
;
97 static char **arg_states
= NULL
;
98 static char **arg_properties
= NULL
;
99 static bool arg_all
= false;
100 static enum dependency
{
106 } arg_dependency
= DEPENDENCY_FORWARD
;
107 static const char *arg_job_mode
= "replace";
108 static UnitFileScope arg_scope
= UNIT_FILE_SYSTEM
;
109 static bool arg_wait
= false;
110 static bool arg_no_block
= false;
111 static bool arg_no_legend
= false;
112 static PagerFlags arg_pager_flags
= 0;
113 static bool arg_no_wtmp
= false;
114 static bool arg_no_sync
= false;
115 static bool arg_no_wall
= false;
116 static bool arg_no_reload
= false;
117 static bool arg_value
= false;
118 static bool arg_show_types
= false;
119 static bool arg_ignore_inhibitors
= false;
120 static bool arg_dry_run
= false;
121 static bool arg_quiet
= false;
122 static bool arg_full
= false;
123 static bool arg_recursive
= false;
124 static bool arg_with_dependencies
= false;
125 static bool arg_show_transaction
= false;
126 static int arg_force
= 0;
127 static bool arg_ask_password
= false;
128 static bool arg_runtime
= false;
129 static UnitFilePresetMode arg_preset_mode
= UNIT_FILE_PRESET_FULL
;
130 static char **arg_wall
= NULL
;
131 static const char *arg_kill_who
= NULL
;
132 static int arg_signal
= SIGTERM
;
133 static char *arg_root
= NULL
;
134 static usec_t arg_when
= 0;
135 static const char *arg_reboot_argument
= NULL
;
146 ACTION_SUSPEND_THEN_HIBERNATE
,
157 ACTION_CANCEL_SHUTDOWN
,
160 } arg_action
= ACTION_SYSTEMCTL
;
161 static BusTransport arg_transport
= BUS_TRANSPORT_LOCAL
;
162 static const char *arg_host
= NULL
;
163 static unsigned arg_lines
= 10;
164 static OutputMode arg_output
= OUTPUT_SHORT
;
165 static bool arg_plain
= false;
166 static bool arg_firmware_setup
= false;
167 static usec_t arg_boot_loader_menu
= USEC_INFINITY
;
168 static const char *arg_boot_loader_entry
= NULL
;
169 static bool arg_now
= false;
170 static bool arg_jobs_before
= false;
171 static bool arg_jobs_after
= false;
172 static char **arg_clean_what
= NULL
;
174 /* This is a global cache that will be constructed on first use. */
175 static Hashmap
*cached_id_map
= NULL
;
176 static Hashmap
*cached_name_map
= NULL
;
178 STATIC_DESTRUCTOR_REGISTER(arg_wall
, strv_freep
);
179 STATIC_DESTRUCTOR_REGISTER(arg_root
, freep
);
180 STATIC_DESTRUCTOR_REGISTER(arg_types
, strv_freep
);
181 STATIC_DESTRUCTOR_REGISTER(arg_states
, strv_freep
);
182 STATIC_DESTRUCTOR_REGISTER(arg_properties
, strv_freep
);
183 STATIC_DESTRUCTOR_REGISTER(arg_clean_what
, strv_freep
);
184 STATIC_DESTRUCTOR_REGISTER(cached_id_map
, hashmap_freep
);
185 STATIC_DESTRUCTOR_REGISTER(cached_name_map
, hashmap_freep
);
187 static int daemon_reload(int argc
, char *argv
[], void* userdata
);
188 static int trivial_method(int argc
, char *argv
[], void *userdata
);
189 static int halt_now(enum action a
);
190 static int get_state_one_unit(sd_bus
*bus
, const char *name
, UnitActiveState
*active_state
);
192 static bool original_stdout_is_tty
;
194 typedef enum BusFocus
{
195 BUS_FULL
, /* The full bus indicated via --system or --user */
196 BUS_MANAGER
, /* The manager itself, possibly directly, possibly via the bus */
200 static sd_bus
*buses
[_BUS_FOCUS_MAX
] = {};
202 static UnitFileFlags
args_to_flags(void) {
203 return (arg_runtime
? UNIT_FILE_RUNTIME
: 0) |
204 (arg_force
? UNIT_FILE_FORCE
: 0);
207 static int acquire_bus(BusFocus focus
, sd_bus
**ret
) {
210 assert(focus
< _BUS_FOCUS_MAX
);
213 /* We only go directly to the manager, if we are using a local transport */
214 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
217 if (getenv_bool("SYSTEMCTL_FORCE_BUS") > 0)
223 user
= arg_scope
!= UNIT_FILE_SYSTEM
;
225 if (focus
== BUS_MANAGER
)
226 r
= bus_connect_transport_systemd(arg_transport
, arg_host
, user
, &buses
[focus
]);
228 r
= bus_connect_transport(arg_transport
, arg_host
, user
, &buses
[focus
]);
230 return log_error_errno(r
, "Failed to connect to bus: %m");
232 (void) sd_bus_set_allow_interactive_authorization(buses
[focus
], arg_ask_password
);
239 static void release_busses(void) {
242 for (w
= 0; w
< _BUS_FOCUS_MAX
; w
++)
243 buses
[w
] = sd_bus_flush_close_unref(buses
[w
]);
246 static void ask_password_agent_open_maybe(void) {
247 /* Open the password agent as a child process if necessary */
252 if (arg_scope
!= UNIT_FILE_SYSTEM
)
255 ask_password_agent_open_if_enabled(arg_transport
, arg_ask_password
);
258 static void polkit_agent_open_maybe(void) {
259 /* Open the polkit agent as a child process if necessary */
261 if (arg_scope
!= UNIT_FILE_SYSTEM
)
264 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
267 static OutputFlags
get_output_flags(void) {
269 arg_all
* OUTPUT_SHOW_ALL
|
270 (arg_full
|| !on_tty() || pager_have()) * OUTPUT_FULL_WIDTH
|
271 colors_enabled() * OUTPUT_COLOR
|
272 !arg_quiet
* OUTPUT_WARN_CUTOFF
;
275 static int translate_bus_error_to_exit_status(int r
, const sd_bus_error
*error
) {
278 if (!sd_bus_error_is_set(error
))
281 if (sd_bus_error_has_name(error
, SD_BUS_ERROR_ACCESS_DENIED
) ||
282 sd_bus_error_has_name(error
, BUS_ERROR_ONLY_BY_DEPENDENCY
) ||
283 sd_bus_error_has_name(error
, BUS_ERROR_NO_ISOLATION
) ||
284 sd_bus_error_has_name(error
, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE
))
285 return EXIT_NOPERMISSION
;
287 if (sd_bus_error_has_name(error
, BUS_ERROR_NO_SUCH_UNIT
))
288 return EXIT_NOTINSTALLED
;
290 if (sd_bus_error_has_name(error
, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE
) ||
291 sd_bus_error_has_name(error
, SD_BUS_ERROR_NOT_SUPPORTED
))
292 return EXIT_NOTIMPLEMENTED
;
294 if (sd_bus_error_has_name(error
, BUS_ERROR_LOAD_FAILED
))
295 return EXIT_NOTCONFIGURED
;
303 static bool install_client_side(void) {
304 /* Decides when to execute enable/disable/... operations
305 * client-side rather than server-side. */
307 if (running_in_chroot_or_offline())
310 if (sd_booted() <= 0)
313 if (!isempty(arg_root
))
316 if (arg_scope
== UNIT_FILE_GLOBAL
)
319 /* Unsupported environment variable, mostly for debugging purposes */
320 if (getenv_bool("SYSTEMCTL_INSTALL_CLIENT_SIDE") > 0)
326 static int compare_unit_info(const UnitInfo
*a
, const UnitInfo
*b
) {
329 /* First, order by machine */
330 r
= strcasecmp_ptr(a
->machine
, b
->machine
);
334 /* Second, order by unit type */
335 r
= strcasecmp_ptr(strrchr(a
->id
, '.'), strrchr(b
->id
, '.'));
339 /* Third, order by name */
340 return strcasecmp(a
->id
, b
->id
);
343 static const char* unit_type_suffix(const char *name
) {
346 dot
= strrchr(name
, '.');
353 static bool output_show_unit(const UnitInfo
*u
, char **patterns
) {
356 if (!strv_fnmatch_or_empty(patterns
, u
->id
, FNM_NOESCAPE
))
359 if (arg_types
&& !strv_find(arg_types
, unit_type_suffix(u
->id
)))
365 /* Note that '--all' is not purely a state filter, but also a
366 * filter that hides units that "follow" other units (which is
367 * used for device units that appear under different names). */
368 if (!isempty(u
->following
))
371 if (!strv_isempty(arg_states
))
374 /* By default show all units except the ones in inactive
375 * state and with no pending job */
379 if (streq(u
->active_state
, "inactive"))
385 static int output_table(Table
*table
) {
390 if (OUTPUT_MODE_IS_JSON(arg_output
))
391 r
= table_print_json(table
, NULL
, output_mode_to_json_format_flags(arg_output
) | JSON_FORMAT_COLOR_AUTO
);
393 r
= table_print(table
, NULL
);
395 return table_log_print_error(r
);
400 static int output_units_list(const UnitInfo
*unit_infos
, unsigned c
) {
401 _cleanup_(table_unrefp
) Table
*table
= NULL
;
404 table
= table_new("", "unit", "load", "active", "sub", "job", "description");
408 table_set_header(table
, !arg_no_legend
);
410 /* Hide the 'glyph' column when --plain is requested */
411 r
= table_hide_column_from_display(table
, 0);
413 return log_error_errno(r
, "Failed to hide column: %m");
416 table_set_width(table
, 0);
418 (void) table_set_empty_string(table
, "-");
421 for (const UnitInfo
*u
= unit_infos
; unit_infos
&& u
< unit_infos
+ c
; u
++) {
422 _cleanup_free_
char *j
= NULL
;
423 const char *on_underline
= "", *on_loaded
= "", *on_active
= "";
424 const char *on_circle
= "", *id
;
425 bool circle
= false, underline
= false;
427 if (u
+ 1 < unit_infos
+ c
&&
428 !streq(unit_type_suffix(u
->id
), unit_type_suffix((u
+ 1)->id
))) {
429 on_underline
= ansi_underline();
433 if (STR_IN_SET(u
->load_state
, "error", "not-found", "bad-setting", "masked") && !arg_plain
) {
434 on_circle
= underline
? ansi_highlight_yellow_underline() : ansi_highlight_yellow();
436 on_loaded
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
437 } else if (streq(u
->active_state
, "failed") && !arg_plain
) {
438 on_circle
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
440 on_active
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
442 on_circle
= on_underline
;
443 on_active
= on_underline
;
444 on_loaded
= on_underline
;
448 j
= strjoin(u
->machine
, ":", u
->id
);
456 r
= table_add_many(table
,
457 TABLE_STRING
, circle
? special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
) : " ",
458 TABLE_SET_BOTH_COLORS
, on_circle
,
460 TABLE_SET_BOTH_COLORS
, on_active
,
461 TABLE_STRING
, u
->load_state
,
462 TABLE_SET_BOTH_COLORS
, on_loaded
,
463 TABLE_STRING
, u
->active_state
,
464 TABLE_SET_BOTH_COLORS
, on_active
,
465 TABLE_STRING
, u
->sub_state
,
466 TABLE_SET_BOTH_COLORS
, on_active
,
467 TABLE_STRING
, u
->job_id
? u
->job_type
: "",
468 TABLE_SET_BOTH_COLORS
, u
->job_id
? on_underline
: "",
469 TABLE_STRING
, u
->description
,
470 TABLE_SET_BOTH_COLORS
, on_underline
);
472 return table_log_add_error(r
);
478 if (job_count
== 0) {
479 /* There's no data in the JOB column, so let's hide it */
480 r
= table_hide_column_from_display(table
, 5);
482 return log_error_errno(r
, "Failed to hide column: %m");
485 r
= output_table(table
);
489 if (!arg_no_legend
) {
490 const char *on
, *off
;
491 size_t records
= table_get_rows(table
) - 1;
495 "LOAD = Reflects whether the unit definition was properly loaded.\n"
496 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
497 "SUB = The low-level unit activation state, values depend on unit type.");
498 puts(job_count
? "JOB = Pending job for the unit.\n" : "");
499 on
= ansi_highlight();
502 on
= ansi_highlight_red();
506 if (arg_all
|| strv_contains(arg_states
, "inactive"))
507 printf("%s%zu loaded units listed.%s\n"
508 "To show all installed unit files use 'systemctl list-unit-files'.\n",
510 else if (!arg_states
)
511 printf("%s%zu loaded units listed.%s Pass --all to see loaded but inactive units, too.\n"
512 "To show all installed unit files use 'systemctl list-unit-files'.\n",
515 printf("%zu loaded units listed.\n", records
);
521 static int get_unit_list(
525 UnitInfo
**unit_infos
,
527 sd_bus_message
**_reply
) {
529 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
530 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
531 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
535 bool fallback
= false;
541 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "ListUnitsByPatterns");
543 return bus_log_create_error(r
);
545 r
= sd_bus_message_append_strv(m
, arg_states
);
547 return bus_log_create_error(r
);
549 r
= sd_bus_message_append_strv(m
, patterns
);
551 return bus_log_create_error(r
);
553 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
554 if (r
< 0 && (sd_bus_error_has_name(&error
, SD_BUS_ERROR_UNKNOWN_METHOD
) ||
555 sd_bus_error_has_name(&error
, SD_BUS_ERROR_ACCESS_DENIED
))) {
556 /* Fallback to legacy ListUnitsFiltered method */
558 log_debug_errno(r
, "Failed to list units: %s Falling back to ListUnitsFiltered method.", bus_error_message(&error
, r
));
559 m
= sd_bus_message_unref(m
);
560 sd_bus_error_free(&error
);
562 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "ListUnitsFiltered");
564 return bus_log_create_error(r
);
566 r
= sd_bus_message_append_strv(m
, arg_states
);
568 return bus_log_create_error(r
);
570 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
573 return log_error_errno(r
, "Failed to list units: %s", bus_error_message(&error
, r
));
575 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssssouso)");
577 return bus_log_parse_error(r
);
579 while ((r
= bus_parse_unit_info(reply
, &u
)) > 0) {
582 if (!output_show_unit(&u
, fallback
? patterns
: NULL
))
585 if (!GREEDY_REALLOC(*unit_infos
, size
, c
+1))
588 (*unit_infos
)[c
++] = u
;
591 return bus_log_parse_error(r
);
593 r
= sd_bus_message_exit_container(reply
);
595 return bus_log_parse_error(r
);
597 *_reply
= TAKE_PTR(reply
);
602 static void message_set_freep(Set
**set
) {
603 set_free_with_destructor(*set
, sd_bus_message_unref
);
606 static int get_unit_list_recursive(
609 UnitInfo
**_unit_infos
,
613 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
614 _cleanup_(message_set_freep
) Set
*replies
;
615 sd_bus_message
*reply
;
623 replies
= set_new(NULL
);
627 c
= get_unit_list(bus
, NULL
, patterns
, &unit_infos
, 0, &reply
);
631 r
= set_put(replies
, reply
);
633 sd_bus_message_unref(reply
);
638 _cleanup_strv_free_
char **machines
= NULL
;
641 r
= sd_get_machine_names(&machines
);
643 return log_error_errno(r
, "Failed to get machine names: %m");
645 STRV_FOREACH(i
, machines
) {
646 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*container
= NULL
;
649 r
= sd_bus_open_system_machine(&container
, *i
);
651 log_warning_errno(r
, "Failed to connect to container %s, ignoring: %m", *i
);
655 k
= get_unit_list(container
, *i
, patterns
, &unit_infos
, c
, &reply
);
661 r
= set_put(replies
, reply
);
663 sd_bus_message_unref(reply
);
668 *_machines
= TAKE_PTR(machines
);
672 *_unit_infos
= TAKE_PTR(unit_infos
);
673 *_replies
= TAKE_PTR(replies
);
678 static int expand_names(sd_bus
*bus
, char **names
, const char* suffix
, char ***ret
, bool *ret_expanded
) {
679 _cleanup_strv_free_
char **mangled
= NULL
, **globs
= NULL
;
686 STRV_FOREACH(name
, names
) {
688 UnitNameMangle options
= UNIT_NAME_MANGLE_GLOB
| (arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
);
690 r
= unit_name_mangle_with_suffix(*name
, NULL
, options
, suffix
?: ".service", &t
);
692 return log_error_errno(r
, "Failed to mangle name: %m");
694 if (string_is_glob(t
))
695 r
= strv_consume(&globs
, t
);
697 r
= strv_consume(&mangled
, t
);
702 /* Query the manager only if any of the names are a glob, since
703 * this is fairly expensive */
704 bool expanded
= !strv_isempty(globs
);
706 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
707 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
710 r
= get_unit_list(bus
, NULL
, globs
, &unit_infos
, 0, &reply
);
714 n
= strv_length(mangled
);
717 for (i
= 0; i
< r
; i
++) {
718 if (!GREEDY_REALLOC(mangled
, allocated
, n
+2))
721 mangled
[n
] = strdup(unit_infos
[i
].id
);
730 *ret_expanded
= expanded
;
732 *ret
= TAKE_PTR(mangled
);
736 static int list_dependencies_get_dependencies(sd_bus
*bus
, const char *name
, char ***ret
) {
737 _cleanup_strv_free_
char **deps
= NULL
;
739 static const struct bus_properties_map map
[_DEPENDENCY_MAX
][6] = {
740 [DEPENDENCY_FORWARD
] = {
741 { "Requires", "as", NULL
, 0 },
742 { "Requisite", "as", NULL
, 0 },
743 { "Wants", "as", NULL
, 0 },
744 { "ConsistsOf", "as", NULL
, 0 },
745 { "BindsTo", "as", NULL
, 0 },
748 [DEPENDENCY_REVERSE
] = {
749 { "RequiredBy", "as", NULL
, 0 },
750 { "RequisiteOf", "as", NULL
, 0 },
751 { "WantedBy", "as", NULL
, 0 },
752 { "PartOf", "as", NULL
, 0 },
753 { "BoundBy", "as", NULL
, 0 },
756 [DEPENDENCY_AFTER
] = {
757 { "After", "as", NULL
, 0 },
760 [DEPENDENCY_BEFORE
] = {
761 { "Before", "as", NULL
, 0 },
766 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
767 _cleanup_free_
char *dbus_path
= NULL
;
774 dbus_path
= unit_dbus_path_from_name(name
);
778 r
= bus_map_all_properties(bus
,
779 "org.freedesktop.systemd1",
787 return log_error_errno(r
, "Failed to get properties of %s: %s", name
, bus_error_message(&error
, r
));
789 strv_uniq(deps
); /* Sometimes a unit might have multiple deps on the other unit,
790 * but we still want to show it just once. */
791 *ret
= TAKE_PTR(deps
);
796 static int append_unit_dependencies(sd_bus
*bus
, char **names
, char ***ret
) {
797 _cleanup_strv_free_
char **with_deps
= NULL
;
803 STRV_FOREACH(name
, names
) {
804 _cleanup_strv_free_
char **deps
= NULL
;
806 if (strv_extend(&with_deps
, *name
) < 0)
809 (void) list_dependencies_get_dependencies(bus
, *name
, &deps
);
811 if (strv_extend_strv(&with_deps
, deps
, true) < 0)
815 *ret
= TAKE_PTR(with_deps
);
820 static int maybe_extend_with_unit_dependencies(sd_bus
*bus
, char ***list
) {
824 if (arg_with_dependencies
) {
826 _cleanup_strv_free_
char **list_with_deps
= NULL
;
828 r
= append_unit_dependencies(bus
, *list
, &list_with_deps
);
830 return log_error_errno(r
, "Failed to append unit dependencies: %m");
833 *list
= TAKE_PTR(list_with_deps
);
839 static int list_units(int argc
, char *argv
[], void *userdata
) {
840 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
841 _cleanup_(message_set_freep
) Set
*replies
= NULL
;
842 _cleanup_strv_free_
char **machines
= NULL
;
846 r
= acquire_bus(BUS_MANAGER
, &bus
);
850 (void) pager_open(arg_pager_flags
);
852 if (arg_with_dependencies
) {
853 _cleanup_strv_free_
char **names
= NULL
;
855 r
= append_unit_dependencies(bus
, strv_skip(argv
, 1), &names
);
859 r
= get_unit_list_recursive(bus
, names
, &unit_infos
, &replies
, &machines
);
863 r
= get_unit_list_recursive(bus
, strv_skip(argv
, 1), &unit_infos
, &replies
, &machines
);
868 typesafe_qsort(unit_infos
, r
, compare_unit_info
);
869 return output_units_list(unit_infos
, r
);
872 static int get_triggered_units(
877 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
884 r
= sd_bus_get_property_strv(
886 "org.freedesktop.systemd1",
888 "org.freedesktop.systemd1.Unit",
893 return log_error_errno(r
, "Failed to determine triggers: %s", bus_error_message(&error
, r
));
898 static int get_listening(
900 const char* unit_path
,
903 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
904 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
905 const char *type
, *path
;
908 r
= sd_bus_get_property(
910 "org.freedesktop.systemd1",
912 "org.freedesktop.systemd1.Socket",
918 return log_error_errno(r
, "Failed to get list of listening sockets: %s", bus_error_message(&error
, r
));
920 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ss)");
922 return bus_log_parse_error(r
);
924 while ((r
= sd_bus_message_read(reply
, "(ss)", &type
, &path
)) > 0) {
926 r
= strv_extend(listening
, type
);
930 r
= strv_extend(listening
, path
);
937 return bus_log_parse_error(r
);
939 r
= sd_bus_message_exit_container(reply
);
941 return bus_log_parse_error(r
);
953 /* Note: triggered is a list here, although it almost certainly
954 * will always be one unit. Nevertheless, dbus API allows for multiple
955 * values, so let's follow that. */
958 /* The strv above is shared. free is set only in the first one. */
962 static int socket_info_compare(const struct socket_info
*a
, const struct socket_info
*b
) {
968 r
= strcasecmp_ptr(a
->machine
, b
->machine
);
972 r
= strcmp(a
->path
, b
->path
);
976 return strcmp(a
->type
, b
->type
);
979 static int output_sockets_list(struct socket_info
*socket_infos
, unsigned cs
) {
980 _cleanup_(table_unrefp
) Table
*table
= NULL
;
981 struct socket_info
*s
;
982 const char *on
, *off
;
985 table
= table_new("listen", "type", "unit", "activates");
989 if (!arg_show_types
) {
990 /* Hide the second (TYPE) column */
991 r
= table_set_display(table
, (size_t) 0, (size_t) 2, (size_t) 3, (size_t) -1);
993 return log_error_errno(r
, "Failed to set columns to display: %m");
996 table_set_header(table
, !arg_no_legend
);
998 table_set_width(table
, 0);
1000 (void) table_set_empty_string(table
, "-");
1003 for (s
= socket_infos
; s
< socket_infos
+ cs
; s
++) {
1004 _cleanup_free_
char *j
= NULL
;
1008 j
= strjoin(s
->machine
, ":", s
->path
);
1015 r
= table_add_many(table
,
1017 TABLE_STRING
, s
->type
,
1018 TABLE_STRING
, s
->id
);
1020 return table_log_add_error(r
);
1022 if (strv_isempty(s
->triggered
))
1023 r
= table_add_cell(table
, NULL
, TABLE_EMPTY
, NULL
);
1024 else if (strv_length(s
->triggered
) == 1)
1025 r
= table_add_cell(table
, NULL
, TABLE_STRING
, s
->triggered
[0]);
1027 /* This should never happen, currently our socket units can only trigger a
1028 * single unit. But let's handle this anyway, who knows what the future
1030 r
= table_add_cell(table
, NULL
, TABLE_STRV
, s
->triggered
);
1032 return table_log_add_error(r
);
1036 on
= ansi_highlight();
1037 off
= ansi_normal();
1039 on
= ansi_highlight_red();
1040 off
= ansi_normal();
1043 r
= output_table(table
);
1047 if (!arg_no_legend
) {
1048 printf("\n%s%u sockets listed.%s\n", on
, cs
, off
);
1050 printf("Pass --all to see loaded but inactive sockets, too.\n");
1056 static int list_sockets(int argc
, char *argv
[], void *userdata
) {
1057 _cleanup_(message_set_freep
) Set
*replies
= NULL
;
1058 _cleanup_strv_free_
char **machines
= NULL
;
1059 _cleanup_strv_free_
char **sockets_with_suffix
= NULL
;
1060 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
1061 _cleanup_free_
struct socket_info
*socket_infos
= NULL
;
1063 struct socket_info
*s
;
1069 r
= acquire_bus(BUS_MANAGER
, &bus
);
1073 (void) pager_open(arg_pager_flags
);
1075 r
= expand_names(bus
, strv_skip(argv
, 1), ".socket", &sockets_with_suffix
, NULL
);
1079 if (argc
== 1 || sockets_with_suffix
) {
1080 n
= get_unit_list_recursive(bus
, sockets_with_suffix
, &unit_infos
, &replies
, &machines
);
1084 for (u
= unit_infos
; u
< unit_infos
+ n
; u
++) {
1085 _cleanup_strv_free_
char **listening
= NULL
, **triggered
= NULL
;
1088 if (!endswith(u
->id
, ".socket"))
1091 r
= get_triggered_units(bus
, u
->unit_path
, &triggered
);
1095 c
= get_listening(bus
, u
->unit_path
, &listening
);
1101 if (!GREEDY_REALLOC(socket_infos
, size
, cs
+ c
)) {
1106 for (i
= 0; i
< c
; i
++)
1107 socket_infos
[cs
+ i
] = (struct socket_info
) {
1108 .machine
= u
->machine
,
1110 .type
= listening
[i
*2],
1111 .path
= listening
[i
*2 + 1],
1112 .triggered
= triggered
,
1113 .own_triggered
= i
==0,
1116 /* from this point on we will cleanup those socket_infos */
1119 listening
= triggered
= NULL
; /* avoid cleanup */
1122 typesafe_qsort(socket_infos
, cs
, socket_info_compare
);
1125 output_sockets_list(socket_infos
, cs
);
1128 assert(cs
== 0 || socket_infos
);
1129 for (s
= socket_infos
; s
< socket_infos
+ cs
; s
++) {
1132 if (s
->own_triggered
)
1133 strv_free(s
->triggered
);
1139 static int get_next_elapse(
1142 dual_timestamp
*next
) {
1144 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1152 r
= sd_bus_get_property_trivial(
1154 "org.freedesktop.systemd1",
1156 "org.freedesktop.systemd1.Timer",
1157 "NextElapseUSecMonotonic",
1162 return log_error_errno(r
, "Failed to get next elapse time: %s", bus_error_message(&error
, r
));
1164 r
= sd_bus_get_property_trivial(
1166 "org.freedesktop.systemd1",
1168 "org.freedesktop.systemd1.Timer",
1169 "NextElapseUSecRealtime",
1174 return log_error_errno(r
, "Failed to get next elapse time: %s", bus_error_message(&error
, r
));
1180 static int get_last_trigger(
1185 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1192 r
= sd_bus_get_property_trivial(
1194 "org.freedesktop.systemd1",
1196 "org.freedesktop.systemd1.Timer",
1202 return log_error_errno(r
, "Failed to get last trigger time: %s", bus_error_message(&error
, r
));
1208 const char* machine
;
1211 usec_t last_trigger
;
1215 static int timer_info_compare(const struct timer_info
*a
, const struct timer_info
*b
) {
1221 r
= strcasecmp_ptr(a
->machine
, b
->machine
);
1225 r
= CMP(a
->next_elapse
, b
->next_elapse
);
1229 return strcmp(a
->id
, b
->id
);
1232 static int output_timers_list(struct timer_info
*timer_infos
, unsigned n
) {
1233 _cleanup_(table_unrefp
) Table
*table
= NULL
;
1234 struct timer_info
*t
;
1235 const char *on
, *off
;
1238 assert(timer_infos
|| n
== 0);
1240 table
= table_new("next", "left", "last", "passed", "unit", "activates");
1244 table_set_header(table
, !arg_no_legend
);
1246 table_set_width(table
, 0);
1248 (void) table_set_empty_string(table
, "-");
1251 for (t
= timer_infos
; t
< timer_infos
+ n
; t
++) {
1252 _cleanup_free_
char *j
= NULL
, *activates
= NULL
;
1256 j
= strjoin(t
->machine
, ":", t
->id
);
1263 activates
= strv_join(t
->triggered
, ", ");
1267 r
= table_add_many(table
,
1268 TABLE_TIMESTAMP
, t
->next_elapse
,
1269 TABLE_TIMESTAMP_RELATIVE
, t
->next_elapse
,
1270 TABLE_TIMESTAMP
, t
->last_trigger
,
1271 TABLE_TIMESTAMP_RELATIVE
, t
->last_trigger
,
1273 TABLE_STRING
, activates
);
1275 return table_log_add_error(r
);
1278 on
= ansi_highlight();
1279 off
= ansi_normal();
1281 on
= ansi_highlight_red();
1282 off
= ansi_normal();
1285 r
= output_table(table
);
1289 if (!arg_no_legend
) {
1290 printf("\n%s%u timers listed.%s\n", on
, n
, off
);
1292 printf("Pass --all to see loaded but inactive timers, too.\n");
1298 static usec_t
calc_next_elapse(dual_timestamp
*nw
, dual_timestamp
*next
) {
1304 if (timestamp_is_set(next
->monotonic
)) {
1307 if (next
->monotonic
> nw
->monotonic
)
1308 converted
= nw
->realtime
+ (next
->monotonic
- nw
->monotonic
);
1310 converted
= nw
->realtime
- (nw
->monotonic
- next
->monotonic
);
1312 if (timestamp_is_set(next
->realtime
))
1313 next_elapse
= MIN(converted
, next
->realtime
);
1315 next_elapse
= converted
;
1318 next_elapse
= next
->realtime
;
1323 static int list_timers(int argc
, char *argv
[], void *userdata
) {
1324 _cleanup_(message_set_freep
) Set
*replies
= NULL
;
1325 _cleanup_strv_free_
char **machines
= NULL
;
1326 _cleanup_strv_free_
char **timers_with_suffix
= NULL
;
1327 _cleanup_free_
struct timer_info
*timer_infos
= NULL
;
1328 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
1329 struct timer_info
*t
;
1337 r
= acquire_bus(BUS_MANAGER
, &bus
);
1341 (void) pager_open(arg_pager_flags
);
1343 r
= expand_names(bus
, strv_skip(argv
, 1), ".timer", &timers_with_suffix
, NULL
);
1347 if (argc
== 1 || timers_with_suffix
) {
1348 n
= get_unit_list_recursive(bus
, timers_with_suffix
, &unit_infos
, &replies
, &machines
);
1352 dual_timestamp_get(&nw
);
1354 for (u
= unit_infos
; u
< unit_infos
+ n
; u
++) {
1355 _cleanup_strv_free_
char **triggered
= NULL
;
1356 dual_timestamp next
= DUAL_TIMESTAMP_NULL
;
1359 if (!endswith(u
->id
, ".timer"))
1362 r
= get_triggered_units(bus
, u
->unit_path
, &triggered
);
1366 r
= get_next_elapse(bus
, u
->unit_path
, &next
);
1370 get_last_trigger(bus
, u
->unit_path
, &last
);
1372 if (!GREEDY_REALLOC(timer_infos
, size
, c
+1)) {
1377 m
= calc_next_elapse(&nw
, &next
);
1379 timer_infos
[c
++] = (struct timer_info
) {
1380 .machine
= u
->machine
,
1383 .last_trigger
= last
,
1384 .triggered
= TAKE_PTR(triggered
),
1388 typesafe_qsort(timer_infos
, c
, timer_info_compare
);
1391 output_timers_list(timer_infos
, c
);
1394 for (t
= timer_infos
; t
< timer_infos
+ c
; t
++)
1395 strv_free(t
->triggered
);
1400 static int compare_unit_file_list(const UnitFileList
*a
, const UnitFileList
*b
) {
1401 const char *d1
, *d2
;
1403 d1
= strrchr(a
->path
, '.');
1404 d2
= strrchr(b
->path
, '.');
1409 r
= strcasecmp(d1
, d2
);
1414 return strcasecmp(basename(a
->path
), basename(b
->path
));
1417 static bool output_show_unit_file(const UnitFileList
*u
, char **states
, char **patterns
) {
1420 if (!strv_fnmatch_or_empty(patterns
, basename(u
->path
), FNM_NOESCAPE
))
1423 if (!strv_isempty(arg_types
)) {
1426 dot
= strrchr(u
->path
, '.');
1430 if (!strv_find(arg_types
, dot
+1))
1434 if (!strv_isempty(states
) &&
1435 !strv_find(states
, unit_file_state_to_string(u
->state
)))
1441 static bool show_preset_for_state(UnitFileState state
) {
1442 /* Don't show preset state in those unit file states, it'll only confuse users. */
1443 return !IN_SET(state
,
1446 UNIT_FILE_GENERATED
,
1447 UNIT_FILE_TRANSIENT
);
1450 static int output_unit_file_list(const UnitFileList
*units
, unsigned c
) {
1451 _cleanup_(table_unrefp
) Table
*table
= NULL
;
1452 _cleanup_(unit_file_presets_freep
) UnitFilePresets presets
= {};
1455 table
= table_new("unit file", "state", "vendor preset");
1459 table_set_header(table
, !arg_no_legend
);
1461 table_set_width(table
, 0);
1463 (void) table_set_empty_string(table
, "-");
1465 for (const UnitFileList
*u
= units
; u
< units
+ c
; u
++) {
1466 const char *on_underline
= NULL
, *on_unit_color
= NULL
, *id
;
1469 underline
= u
+ 1 < units
+ c
&&
1470 !streq(unit_type_suffix(u
->path
), unit_type_suffix((u
+ 1)->path
));
1473 on_underline
= ansi_underline();
1475 if (IN_SET(u
->state
,
1477 UNIT_FILE_MASKED_RUNTIME
,
1480 on_unit_color
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
1481 else if (IN_SET(u
->state
,
1484 on_unit_color
= underline
? ansi_highlight_green_underline() : ansi_highlight_green();
1486 on_unit_color
= on_underline
;
1488 id
= basename(u
->path
);
1490 r
= table_add_many(table
,
1492 TABLE_SET_BOTH_COLORS
, strempty(on_underline
),
1493 TABLE_STRING
, unit_file_state_to_string(u
->state
),
1494 TABLE_SET_BOTH_COLORS
, strempty(on_unit_color
));
1496 return table_log_add_error(r
);
1498 if (show_preset_for_state(u
->state
)) {
1499 const char *unit_preset_str
, *on_preset_color
;
1501 r
= unit_file_query_preset(arg_scope
, arg_root
, id
, &presets
);
1503 unit_preset_str
= "n/a";
1504 on_preset_color
= underline
? on_underline
: ansi_normal();
1505 } else if (r
== 0) {
1506 unit_preset_str
= "disabled";
1507 on_preset_color
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
1509 unit_preset_str
= "enabled";
1510 on_preset_color
= underline
? ansi_highlight_green_underline() : ansi_highlight_green();
1513 r
= table_add_many(table
,
1514 TABLE_STRING
, unit_preset_str
,
1515 TABLE_SET_BOTH_COLORS
, strempty(on_preset_color
));
1517 r
= table_add_many(table
,
1519 TABLE_SET_BOTH_COLORS
, underline
? ansi_grey_underline() : ansi_grey());
1521 return table_log_add_error(r
);
1524 r
= output_table(table
);
1529 printf("\n%u unit files listed.\n", c
);
1534 static int list_unit_files(int argc
, char *argv
[], void *userdata
) {
1535 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1536 _cleanup_free_ UnitFileList
*units
= NULL
;
1543 bool fallback
= false;
1545 if (install_client_side()) {
1551 h
= hashmap_new(&string_hash_ops
);
1555 r
= unit_file_get_list(arg_scope
, arg_root
, h
, arg_states
, strv_skip(argv
, 1));
1557 unit_file_list_free(h
);
1558 return log_error_errno(r
, "Failed to get unit file list: %m");
1561 n_units
= hashmap_size(h
);
1563 units
= new(UnitFileList
, n_units
?: 1); /* avoid malloc(0) */
1565 unit_file_list_free(h
);
1569 HASHMAP_FOREACH(u
, h
, i
) {
1570 if (!output_show_unit_file(u
, NULL
, NULL
))
1577 assert(c
<= n_units
);
1582 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
1583 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1586 r
= acquire_bus(BUS_MANAGER
, &bus
);
1590 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "ListUnitFilesByPatterns");
1592 return bus_log_create_error(r
);
1594 r
= sd_bus_message_append_strv(m
, arg_states
);
1596 return bus_log_create_error(r
);
1598 if (arg_with_dependencies
) {
1599 _cleanup_strv_free_
char **names_with_deps
= NULL
;
1601 r
= append_unit_dependencies(bus
, strv_skip(argv
, 1), &names_with_deps
);
1603 return log_error_errno(r
, "Failed to append unit dependencies: %m");
1605 r
= sd_bus_message_append_strv(m
, names_with_deps
);
1607 return bus_log_create_error(r
);
1609 r
= sd_bus_message_append_strv(m
, strv_skip(argv
, 1));
1611 return bus_log_create_error(r
);
1614 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1615 if (r
< 0 && sd_bus_error_has_name(&error
, SD_BUS_ERROR_UNKNOWN_METHOD
)) {
1616 /* Fallback to legacy ListUnitFiles method */
1618 log_debug_errno(r
, "Failed to list unit files: %s Falling back to ListUnitsFiles method.", bus_error_message(&error
, r
));
1619 m
= sd_bus_message_unref(m
);
1620 sd_bus_error_free(&error
);
1622 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "ListUnitFiles");
1624 return bus_log_create_error(r
);
1626 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1629 return log_error_errno(r
, "Failed to list unit files: %s", bus_error_message(&error
, r
));
1631 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ss)");
1633 return bus_log_parse_error(r
);
1635 while ((r
= sd_bus_message_read(reply
, "(ss)", &path
, &state
)) > 0) {
1637 if (!GREEDY_REALLOC(units
, size
, c
+ 1))
1640 units
[c
] = (struct UnitFileList
) {
1642 unit_file_state_from_string(state
)
1645 if (output_show_unit_file(&units
[c
],
1646 fallback
? arg_states
: NULL
,
1647 fallback
? strv_skip(argv
, 1) : NULL
))
1652 return bus_log_parse_error(r
);
1654 r
= sd_bus_message_exit_container(reply
);
1656 return bus_log_parse_error(r
);
1659 (void) pager_open(arg_pager_flags
);
1661 typesafe_qsort(units
, c
, compare_unit_file_list
);
1662 r
= output_unit_file_list(units
, c
);
1666 if (install_client_side())
1667 for (unit
= units
; unit
< units
+ c
; unit
++)
1676 static int list_dependencies_print(const char *name
, int level
, unsigned branches
, bool last
) {
1677 _cleanup_free_
char *n
= NULL
;
1678 size_t max_len
= MAX(columns(),20u);
1684 for (i
= level
- 1; i
>= 0; i
--) {
1686 if (len
> max_len
- 3 && !arg_full
) {
1687 printf("%s...\n",max_len
% 2 ? "" : " ");
1690 printf("%s", special_glyph(branches
& (1 << i
) ? SPECIAL_GLYPH_TREE_VERTICAL
: SPECIAL_GLYPH_TREE_SPACE
));
1694 if (len
> max_len
- 3 && !arg_full
) {
1695 printf("%s...\n",max_len
% 2 ? "" : " ");
1699 printf("%s", special_glyph(last
? SPECIAL_GLYPH_TREE_RIGHT
: SPECIAL_GLYPH_TREE_BRANCH
));
1703 printf("%s\n", name
);
1707 n
= ellipsize(name
, max_len
-len
, 100);
1715 static int list_dependencies_compare(char * const *a
, char * const *b
) {
1716 if (unit_name_to_type(*a
) == UNIT_TARGET
&& unit_name_to_type(*b
) != UNIT_TARGET
)
1718 if (unit_name_to_type(*a
) != UNIT_TARGET
&& unit_name_to_type(*b
) == UNIT_TARGET
)
1721 return strcasecmp(*a
, *b
);
1724 static int list_dependencies_one(
1729 unsigned branches
) {
1731 _cleanup_strv_free_
char **deps
= NULL
;
1739 r
= strv_extend(units
, name
);
1743 r
= list_dependencies_get_dependencies(bus
, name
, &deps
);
1747 typesafe_qsort(deps
, strv_length(deps
), list_dependencies_compare
);
1749 STRV_FOREACH(c
, deps
) {
1750 if (strv_contains(*units
, *c
)) {
1753 r
= list_dependencies_print("...", level
+ 1, (branches
<< 1) | (c
[1] == NULL
? 0 : 1), 1);
1763 UnitActiveState active_state
= _UNIT_ACTIVE_STATE_INVALID
;
1766 (void) get_state_one_unit(bus
, *c
, &active_state
);
1768 switch (active_state
) {
1770 case UNIT_RELOADING
:
1771 case UNIT_ACTIVATING
:
1772 on
= ansi_highlight_green();
1776 case UNIT_DEACTIVATING
:
1781 on
= ansi_highlight_red();
1785 printf("%s%s%s ", on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), ansi_normal());
1788 r
= list_dependencies_print(*c
, level
, branches
, c
[1] == NULL
);
1792 if (arg_all
|| unit_name_to_type(*c
) == UNIT_TARGET
) {
1793 r
= list_dependencies_one(bus
, *c
, level
+ 1, units
, (branches
<< 1) | (c
[1] == NULL
? 0 : 1));
1800 strv_remove(*units
, name
);
1805 static int list_dependencies(int argc
, char *argv
[], void *userdata
) {
1806 _cleanup_strv_free_
char **units
= NULL
, **done
= NULL
;
1807 char **u
, **patterns
;
1811 r
= acquire_bus(BUS_MANAGER
, &bus
);
1815 patterns
= strv_skip(argv
, 1);
1816 if (strv_isempty(patterns
)) {
1817 units
= strv_new(SPECIAL_DEFAULT_TARGET
);
1821 r
= expand_names(bus
, patterns
, NULL
, &units
, NULL
);
1823 return log_error_errno(r
, "Failed to expand names: %m");
1826 (void) pager_open(arg_pager_flags
);
1828 STRV_FOREACH(u
, units
) {
1833 r
= list_dependencies_one(bus
, *u
, 0, &done
, 0);
1841 struct machine_info
{
1845 char *control_group
;
1846 uint32_t n_failed_units
;
1851 static const struct bus_properties_map machine_info_property_map
[] = {
1852 { "SystemState", "s", NULL
, offsetof(struct machine_info
, state
) },
1853 { "NJobs", "u", NULL
, offsetof(struct machine_info
, n_jobs
) },
1854 { "NFailedUnits", "u", NULL
, offsetof(struct machine_info
, n_failed_units
) },
1855 { "ControlGroup", "s", NULL
, offsetof(struct machine_info
, control_group
) },
1856 { "UserspaceTimestamp", "t", NULL
, offsetof(struct machine_info
, timestamp
) },
1860 static void machine_info_clear(struct machine_info
*info
) {
1865 free(info
->control_group
);
1869 static void free_machines_list(struct machine_info
*machine_infos
, int n
) {
1875 for (i
= 0; i
< n
; i
++)
1876 machine_info_clear(&machine_infos
[i
]);
1878 free(machine_infos
);
1881 static int compare_machine_info(const struct machine_info
*a
, const struct machine_info
*b
) {
1884 r
= CMP(b
->is_host
, a
->is_host
);
1888 return strcasecmp(a
->name
, b
->name
);
1891 static int get_machine_properties(sd_bus
*bus
, struct machine_info
*mi
) {
1892 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*container
= NULL
;
1898 r
= sd_bus_open_system_machine(&container
, mi
->name
);
1905 r
= bus_map_all_properties(
1907 "org.freedesktop.systemd1",
1908 "/org/freedesktop/systemd1",
1909 machine_info_property_map
,
1920 static bool output_show_machine(const char *name
, char **patterns
) {
1921 return strv_fnmatch_or_empty(patterns
, name
, FNM_NOESCAPE
);
1924 static int get_machine_list(
1926 struct machine_info
**_machine_infos
,
1929 struct machine_info
*machine_infos
= NULL
;
1930 _cleanup_strv_free_
char **m
= NULL
;
1931 _cleanup_free_
char *hn
= NULL
;
1936 hn
= gethostname_malloc();
1940 if (output_show_machine(hn
, patterns
)) {
1941 if (!GREEDY_REALLOC0(machine_infos
, sz
, c
+1))
1944 machine_infos
[c
].is_host
= true;
1945 machine_infos
[c
].name
= TAKE_PTR(hn
);
1947 (void) get_machine_properties(bus
, &machine_infos
[c
]);
1951 r
= sd_get_machine_names(&m
);
1953 return log_error_errno(r
, "Failed to get machine list: %m");
1955 STRV_FOREACH(i
, m
) {
1956 _cleanup_free_
char *class = NULL
;
1958 if (!output_show_machine(*i
, patterns
))
1961 sd_machine_get_class(*i
, &class);
1962 if (!streq_ptr(class, "container"))
1965 if (!GREEDY_REALLOC0(machine_infos
, sz
, c
+1)) {
1966 free_machines_list(machine_infos
, c
);
1970 machine_infos
[c
].is_host
= false;
1971 machine_infos
[c
].name
= strdup(*i
);
1972 if (!machine_infos
[c
].name
) {
1973 free_machines_list(machine_infos
, c
);
1977 (void) get_machine_properties(NULL
, &machine_infos
[c
]);
1981 *_machine_infos
= machine_infos
;
1985 static int output_machines_list(struct machine_info
*machine_infos
, unsigned n
) {
1986 _cleanup_(table_unrefp
) Table
*table
= NULL
;
1987 struct machine_info
*m
;
1988 bool state_missing
= false;
1991 assert(machine_infos
|| n
== 0);
1993 table
= table_new("", "name", "state", "failed", "jobs");
1997 table_set_header(table
, !arg_no_legend
);
1999 /* Hide the 'glyph' column when --plain is requested */
2000 r
= table_hide_column_from_display(table
, 0);
2002 return log_error_errno(r
, "Failed to hide column: %m");
2005 table_set_width(table
, 0);
2007 (void) table_set_empty_string(table
, "-");
2009 for (m
= machine_infos
; m
< machine_infos
+ n
; m
++) {
2010 _cleanup_free_
char *mname
= NULL
;
2011 const char *on_state
= "", *on_failed
= "";
2012 bool circle
= false;
2014 if (streq_ptr(m
->state
, "degraded")) {
2015 on_state
= ansi_highlight_red();
2017 } else if (!streq_ptr(m
->state
, "running")) {
2018 on_state
= ansi_highlight_yellow();
2022 if (m
->n_failed_units
> 0)
2023 on_failed
= ansi_highlight_red();
2028 state_missing
= true;
2031 mname
= strjoin(strna(m
->name
), " (host)");
2033 r
= table_add_many(table
,
2034 TABLE_STRING
, circle
? special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
) : " ",
2035 TABLE_SET_COLOR
, on_state
,
2036 TABLE_STRING
, m
->is_host
? mname
: strna(m
->name
),
2037 TABLE_STRING
, strna(m
->state
),
2038 TABLE_SET_COLOR
, on_state
,
2039 TABLE_UINT32
, m
->n_failed_units
,
2040 TABLE_SET_COLOR
, on_failed
,
2041 TABLE_UINT32
, m
->n_jobs
);
2043 return table_log_add_error(r
);
2046 r
= output_table(table
);
2050 if (!arg_no_legend
) {
2052 if (state_missing
&& geteuid() != 0)
2053 printf("Notice: some information only available to privileged users was not shown.\n");
2054 printf("%u machines listed.\n", n
);
2060 static int list_machines(int argc
, char *argv
[], void *userdata
) {
2061 struct machine_info
*machine_infos
= NULL
;
2065 r
= acquire_bus(BUS_MANAGER
, &bus
);
2069 r
= get_machine_list(bus
, &machine_infos
, strv_skip(argv
, 1));
2073 (void) pager_open(arg_pager_flags
);
2075 typesafe_qsort(machine_infos
, r
, compare_machine_info
);
2076 rc
= output_machines_list(machine_infos
, r
);
2077 free_machines_list(machine_infos
, r
);
2082 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
2085 if (streq(key
, "systemd.unit")) {
2086 if (proc_cmdline_value_missing(key
, value
))
2088 if (!unit_name_is_valid(value
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
2089 return log_warning("Unit name specified on %s= is not valid, ignoring: %s", key
, value
);
2091 return free_and_strdup_warn(ret
, key
);
2093 } else if (!value
) {
2094 if (runlevel_to_target(key
))
2095 return free_and_strdup_warn(ret
, key
);
2101 static void emit_cmdline_warning(void) {
2102 if (arg_quiet
|| arg_root
)
2103 /* don't bother checking the commandline if we're operating on a container */
2106 _cleanup_free_
char *override
= NULL
;
2109 r
= proc_cmdline_parse(parse_proc_cmdline_item
, &override
, 0);
2111 log_debug_errno(r
, "Failed to parse kernel command line, ignoring: %m");
2113 log_notice("Note: found \"%s\" on the kernel commandline, which overrides the default unit.",
2117 static int determine_default(char **ret_name
) {
2120 if (install_client_side()) {
2121 r
= unit_file_get_default(arg_scope
, arg_root
, ret_name
);
2123 return log_error_errno(r
, "Failed to get default target: %m");
2128 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2129 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2132 r
= acquire_bus(BUS_MANAGER
, &bus
);
2136 r
= bus_call_method(bus
, bus_systemd_mgr
, "GetDefaultTarget", &error
, &reply
, NULL
);
2138 return log_error_errno(r
, "Failed to get default target: %s", bus_error_message(&error
, r
));
2140 r
= sd_bus_message_read(reply
, "s", &name
);
2142 return bus_log_parse_error(r
);
2144 return free_and_strdup_warn(ret_name
, name
);
2148 static int get_default(int argc
, char *argv
[], void *userdata
) {
2149 _cleanup_free_
char *name
= NULL
;
2152 r
= determine_default(&name
);
2156 printf("%s\n", name
);
2158 emit_cmdline_warning();
2163 static int set_default(int argc
, char *argv
[], void *userdata
) {
2164 _cleanup_free_
char *unit
= NULL
;
2165 UnitFileChange
*changes
= NULL
;
2166 size_t n_changes
= 0;
2172 r
= unit_name_mangle_with_suffix(argv
[1], "set-default",
2173 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
2176 return log_error_errno(r
, "Failed to mangle unit name: %m");
2178 if (install_client_side()) {
2179 r
= unit_file_set_default(arg_scope
, UNIT_FILE_FORCE
, arg_root
, unit
, &changes
, &n_changes
);
2180 unit_file_dump_changes(r
, "set default", changes
, n_changes
, arg_quiet
);
2185 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2186 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2189 polkit_agent_open_maybe();
2191 r
= acquire_bus(BUS_MANAGER
, &bus
);
2195 r
= bus_call_method(bus
, bus_systemd_mgr
, "SetDefaultTarget", &error
, &reply
, "sb", unit
, 1);
2197 return log_error_errno(r
, "Failed to set default target: %s", bus_error_message(&error
, r
));
2199 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
2203 /* Try to reload if enabled */
2205 r
= daemon_reload(argc
, argv
, userdata
);
2210 emit_cmdline_warning();
2213 _cleanup_free_
char *final
= NULL
;
2215 r
= determine_default(&final
);
2219 if (!streq(final
, unit
))
2220 log_notice("Note: \"%s\" is the default unit (possibly a runtime override).", final
);
2224 unit_file_changes_free(changes
, n_changes
);
2229 static int output_waiting_jobs(sd_bus
*bus
, Table
*table
, uint32_t id
, const char *method
, const char *prefix
) {
2230 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2231 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2232 const char *name
, *type
;
2238 r
= bus_call_method(bus
, bus_systemd_mgr
, method
, &error
, &reply
, "u", id
);
2240 return log_debug_errno(r
, "Failed to get waiting jobs for job %" PRIu32
, id
);
2242 r
= sd_bus_message_enter_container(reply
, 'a', "(usssoo)");
2244 return bus_log_parse_error(r
);
2246 while ((r
= sd_bus_message_read(reply
, "(usssoo)", &other_id
, &name
, &type
, NULL
, NULL
, NULL
)) > 0) {
2247 _cleanup_free_
char *row
= NULL
;
2250 if (asprintf(&row
, "%s %u (%s/%s)", prefix
, other_id
, name
, type
) < 0)
2253 rc
= table_add_many(table
,
2254 TABLE_STRING
, special_glyph(SPECIAL_GLYPH_TREE_RIGHT
),
2259 return table_log_add_error(r
);
2263 return bus_log_parse_error(r
);
2265 r
= sd_bus_message_exit_container(reply
);
2267 return bus_log_parse_error(r
);
2274 const char *name
, *type
, *state
;
2277 static int output_jobs_list(sd_bus
*bus
, const struct job_info
* jobs
, unsigned n
, bool skipped
) {
2278 _cleanup_(table_unrefp
) Table
*table
= NULL
;
2279 const struct job_info
*j
;
2280 const char *on
, *off
;
2283 assert(n
== 0 || jobs
);
2286 if (!arg_no_legend
) {
2287 on
= ansi_highlight_green();
2288 off
= ansi_normal();
2290 printf("%sNo jobs %s.%s\n", on
, skipped
? "listed" : "running", off
);
2295 (void) pager_open(arg_pager_flags
);
2297 table
= table_new("job", "unit", "type", "state");
2301 table_set_header(table
, !arg_no_legend
);
2303 table_set_width(table
, 0);
2305 (void) table_set_empty_string(table
, "-");
2307 for (j
= jobs
; j
< jobs
+ n
; j
++) {
2308 if (streq(j
->state
, "running"))
2309 on
= ansi_highlight();
2313 r
= table_add_many(table
,
2315 TABLE_STRING
, j
->name
,
2316 TABLE_SET_COLOR
, on
,
2317 TABLE_STRING
, j
->type
,
2318 TABLE_STRING
, j
->state
,
2319 TABLE_SET_COLOR
, on
);
2321 return table_log_add_error(r
);
2324 output_waiting_jobs(bus
, table
, j
->id
, "GetJobAfter", "\twaiting for job");
2325 if (arg_jobs_before
)
2326 output_waiting_jobs(bus
, table
, j
->id
, "GetJobBefore", "\tblocking job");
2329 r
= table_print(table
, NULL
);
2331 return log_error_errno(r
, "Failed to print the table: %m");
2333 if (!arg_no_legend
) {
2334 on
= ansi_highlight();
2335 off
= ansi_normal();
2337 printf("\n%s%u jobs listed%s.\n", on
, n
, off
);
2343 static bool output_show_job(struct job_info
*job
, char **patterns
) {
2344 return strv_fnmatch_or_empty(patterns
, job
->name
, FNM_NOESCAPE
);
2347 static int list_jobs(int argc
, char *argv
[], void *userdata
) {
2348 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2349 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2350 _cleanup_free_
struct job_info
*jobs
= NULL
;
2351 const char *name
, *type
, *state
;
2352 bool skipped
= false;
2359 r
= acquire_bus(BUS_MANAGER
, &bus
);
2363 r
= bus_call_method(bus
, bus_systemd_mgr
, "ListJobs", &error
, &reply
, NULL
);
2365 return log_error_errno(r
, "Failed to list jobs: %s", bus_error_message(&error
, r
));
2367 r
= sd_bus_message_enter_container(reply
, 'a', "(usssoo)");
2369 return bus_log_parse_error(r
);
2371 while ((r
= sd_bus_message_read(reply
, "(usssoo)", &id
, &name
, &type
, &state
, NULL
, NULL
)) > 0) {
2372 struct job_info job
= { id
, name
, type
, state
};
2374 if (!output_show_job(&job
, strv_skip(argv
, 1))) {
2379 if (!GREEDY_REALLOC(jobs
, size
, c
+ 1))
2385 return bus_log_parse_error(r
);
2387 r
= sd_bus_message_exit_container(reply
);
2389 return bus_log_parse_error(r
);
2391 (void) pager_open(arg_pager_flags
);
2393 return output_jobs_list(bus
, jobs
, c
, skipped
);
2396 static int cancel_job(int argc
, char *argv
[], void *userdata
) {
2402 return trivial_method(argc
, argv
, userdata
);
2404 r
= acquire_bus(BUS_MANAGER
, &bus
);
2408 polkit_agent_open_maybe();
2410 STRV_FOREACH(name
, strv_skip(argv
, 1)) {
2411 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2415 q
= safe_atou32(*name
, &id
);
2417 return log_error_errno(q
, "Failed to parse job id \"%s\": %m", *name
);
2419 q
= bus_call_method(bus
, bus_systemd_mgr
, "CancelJob", &error
, NULL
, "u", id
);
2421 log_error_errno(q
, "Failed to cancel job %"PRIu32
": %s", id
, bus_error_message(&error
, q
));
2430 static int need_daemon_reload(sd_bus
*bus
, const char *unit
) {
2431 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2435 /* We ignore all errors here, since this is used to show a
2438 /* We don't use unit_dbus_path_from_name() directly since we
2439 * don't want to load the unit if it isn't loaded. */
2441 r
= bus_call_method(bus
, bus_systemd_mgr
, "GetUnit", NULL
, &reply
, "s", unit
);
2445 r
= sd_bus_message_read(reply
, "o", &path
);
2449 r
= sd_bus_get_property_trivial(
2451 "org.freedesktop.systemd1",
2453 "org.freedesktop.systemd1.Unit",
2463 static void warn_unit_file_changed(const char *name
) {
2466 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.",
2467 ansi_highlight_red(),
2470 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user");
2473 static int unit_file_find_path(LookupPaths
*lp
, const char *unit_name
, char **ret_unit_path
) {
2479 STRV_FOREACH(p
, lp
->search_path
) {
2480 _cleanup_free_
char *path
= NULL
, *lpath
= NULL
;
2483 path
= path_join(*p
, unit_name
);
2487 r
= chase_symlinks(path
, arg_root
, 0, &lpath
, NULL
);
2493 return log_error_errno(r
, "Failed to access path \"%s\": %m", path
);
2496 *ret_unit_path
= TAKE_PTR(lpath
);
2502 *ret_unit_path
= NULL
;
2507 static int unit_find_template_path(
2508 const char *unit_name
,
2510 char **ret_fragment_path
,
2511 char **ret_template
) {
2513 _cleanup_free_
char *t
= NULL
, *f
= NULL
;
2516 /* Returns 1 if a fragment was found, 0 if not found, negative on error. */
2518 r
= unit_file_find_path(lp
, unit_name
, &f
);
2522 if (ret_fragment_path
)
2523 *ret_fragment_path
= TAKE_PTR(f
);
2525 *ret_template
= NULL
;
2526 return r
; /* found a real unit */
2529 r
= unit_name_template(unit_name
, &t
);
2531 if (ret_fragment_path
)
2532 *ret_fragment_path
= NULL
;
2534 *ret_template
= NULL
;
2536 return 0; /* not a template, does not exist */
2539 return log_error_errno(r
, "Failed to determine template name: %m");
2541 r
= unit_file_find_path(lp
, t
, ret_fragment_path
);
2546 *ret_template
= r
> 0 ? TAKE_PTR(t
) : NULL
;
2551 static int unit_find_paths(
2553 const char *unit_name
,
2555 bool force_client_side
,
2556 char **ret_fragment_path
,
2557 char ***ret_dropin_paths
) {
2559 _cleanup_strv_free_
char **dropins
= NULL
;
2560 _cleanup_free_
char *path
= NULL
;
2564 * Finds where the unit is defined on disk. Returns 0 if the unit is not found. Returns 1 if it is
2566 * - the path to the unit in *ret_frament_path, if it exists on disk,
2567 * - and a strv of existing drop-ins in *ret_dropin_paths, if the arg is not NULL and any dropins
2570 * Returns -ERFKILL if the unit is masked, and -EKEYREJECTED if the unit file could not be loaded for
2571 * some reason (the latter only applies if we are going through the service manager).
2575 assert(ret_fragment_path
);
2578 /* Go via the bus to acquire the path, unless we are explicitly told not to, or when the unit name is a template */
2579 if (!force_client_side
&&
2580 !install_client_side() &&
2581 !unit_name_is_valid(unit_name
, UNIT_NAME_TEMPLATE
)) {
2582 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2583 _cleanup_free_
char *load_state
= NULL
, *dbus_path
= NULL
;
2585 dbus_path
= unit_dbus_path_from_name(unit_name
);
2589 r
= sd_bus_get_property_string(
2591 "org.freedesktop.systemd1",
2593 "org.freedesktop.systemd1.Unit",
2598 return log_error_errno(r
, "Failed to get LoadState: %s", bus_error_message(&error
, r
));
2600 if (streq(load_state
, "masked"))
2602 if (streq(load_state
, "not-found")) {
2606 if (!STR_IN_SET(load_state
, "loaded", "bad-setting"))
2607 return -EKEYREJECTED
;
2609 r
= sd_bus_get_property_string(
2611 "org.freedesktop.systemd1",
2613 "org.freedesktop.systemd1.Unit",
2618 return log_error_errno(r
, "Failed to get FragmentPath: %s", bus_error_message(&error
, r
));
2620 if (ret_dropin_paths
) {
2621 r
= sd_bus_get_property_strv(
2623 "org.freedesktop.systemd1",
2625 "org.freedesktop.systemd1.Unit",
2630 return log_error_errno(r
, "Failed to get DropInPaths: %s", bus_error_message(&error
, r
));
2634 _cleanup_set_free_free_ Set
*names
= NULL
;
2636 if (!cached_name_map
) {
2637 r
= unit_file_build_name_map(lp
, NULL
, &cached_id_map
, &cached_name_map
, NULL
);
2642 r
= unit_file_find_fragment(cached_id_map
, cached_name_map
, unit_name
, &_path
, &names
);
2647 path
= strdup(_path
);
2652 if (ret_dropin_paths
) {
2653 r
= unit_file_find_dropin_paths(arg_root
, lp
->search_path
, NULL
,
2655 NULL
, names
, &dropins
);
2661 if (isempty(path
)) {
2662 *ret_fragment_path
= NULL
;
2665 *ret_fragment_path
= TAKE_PTR(path
);
2669 if (ret_dropin_paths
) {
2670 if (!strv_isempty(dropins
)) {
2671 *ret_dropin_paths
= TAKE_PTR(dropins
);
2674 *ret_dropin_paths
= NULL
;
2678 if (r
== 0 && !arg_force
)
2679 log_error("No files found for %s.", unit_name
);
2684 static int get_state_one_unit(sd_bus
*bus
, const char *name
, UnitActiveState
*active_state
) {
2685 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2686 _cleanup_free_
char *buf
= NULL
, *dbus_path
= NULL
;
2687 UnitActiveState state
;
2691 assert(active_state
);
2693 dbus_path
= unit_dbus_path_from_name(name
);
2697 r
= sd_bus_get_property_string(
2699 "org.freedesktop.systemd1",
2701 "org.freedesktop.systemd1.Unit",
2706 return log_error_errno(r
, "Failed to retrieve unit state: %s", bus_error_message(&error
, r
));
2708 state
= unit_active_state_from_string(buf
);
2710 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid unit state '%s' for: %s", buf
, name
);
2712 *active_state
= state
;
2716 static int unit_is_masked(sd_bus
*bus
, LookupPaths
*lp
, const char *name
) {
2717 _cleanup_free_
char *load_state
= NULL
;
2720 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
2721 _cleanup_free_
char *path
= NULL
;
2723 /* A template cannot be loaded, but it can be still masked, so
2724 * we need to use a different method. */
2726 r
= unit_file_find_path(lp
, name
, &path
);
2731 return null_or_empty_path(path
);
2734 r
= unit_load_state(bus
, name
, &load_state
);
2738 return streq(load_state
, "masked");
2741 static int check_triggering_units(sd_bus
*bus
, const char *name
) {
2742 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2743 _cleanup_free_
char *n
= NULL
, *dbus_path
= NULL
, *load_state
= NULL
;
2744 _cleanup_strv_free_
char **triggered_by
= NULL
;
2745 bool print_warning_label
= true;
2746 UnitActiveState active_state
;
2750 r
= unit_name_mangle(name
, 0, &n
);
2752 return log_error_errno(r
, "Failed to mangle unit name: %m");
2754 r
= unit_load_state(bus
, name
, &load_state
);
2758 if (streq(load_state
, "masked"))
2761 dbus_path
= unit_dbus_path_from_name(n
);
2765 r
= sd_bus_get_property_strv(
2767 "org.freedesktop.systemd1",
2769 "org.freedesktop.systemd1.Unit",
2774 return log_error_errno(r
, "Failed to get triggered by array of %s: %s", n
, bus_error_message(&error
, r
));
2776 STRV_FOREACH(i
, triggered_by
) {
2777 r
= get_state_one_unit(bus
, *i
, &active_state
);
2781 if (!IN_SET(active_state
, UNIT_ACTIVE
, UNIT_RELOADING
))
2784 if (print_warning_label
) {
2785 log_warning("Warning: Stopping %s, but it can still be activated by:", n
);
2786 print_warning_label
= false;
2789 log_warning(" %s", *i
);
2795 static const struct {
2796 const char *verb
; /* systemctl verb */
2797 const char *method
; /* Name of the specific D-Bus method */
2798 const char *job_type
; /* Job type when passing to the generic EnqueueUnitJob() method */
2799 } unit_actions
[] = {
2800 { "start", "StartUnit", "start" },
2801 { "stop", "StopUnit", "stop" },
2802 { "condstop", "StopUnit", "stop" }, /* legacy alias */
2803 { "reload", "ReloadUnit", "reload" },
2804 { "restart", "RestartUnit", "restart" },
2805 { "try-restart", "TryRestartUnit", "try-restart" },
2806 { "condrestart", "TryRestartUnit", "try-restart" }, /* legacy alias */
2807 { "reload-or-restart", "ReloadOrRestartUnit", "reload-or-restart" },
2808 { "try-reload-or-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" },
2809 { "reload-or-try-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2810 { "condreload", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2811 { "force-reload", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2814 static const char *verb_to_method(const char *verb
) {
2817 for (i
= 0; i
< ELEMENTSOF(unit_actions
); i
++)
2818 if (streq_ptr(unit_actions
[i
].verb
, verb
))
2819 return unit_actions
[i
].method
;
2824 static const char *verb_to_job_type(const char *verb
) {
2827 for (i
= 0; i
< ELEMENTSOF(unit_actions
); i
++)
2828 if (streq_ptr(unit_actions
[i
].verb
, verb
))
2829 return unit_actions
[i
].job_type
;
2834 static int start_unit_one(
2836 const char *method
, /* When using classic per-job bus methods */
2837 const char *job_type
, /* When using new-style EnqueueUnitJob() */
2840 sd_bus_error
*error
,
2842 BusWaitForUnits
*wu
) {
2844 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2854 log_debug("%s dbus call org.freedesktop.systemd1.Manager %s(%s, %s)",
2855 arg_dry_run
? "Would execute" : "Executing",
2856 method
, name
, mode
);
2861 if (arg_show_transaction
) {
2862 _cleanup_(sd_bus_error_free
) sd_bus_error enqueue_error
= SD_BUS_ERROR_NULL
;
2864 /* Use the new, fancy EnqueueUnitJob() API if the user wants us to print the transaction */
2865 r
= bus_call_method(
2872 name
, job_type
, mode
);
2874 if (!sd_bus_error_has_name(&enqueue_error
, SD_BUS_ERROR_UNKNOWN_METHOD
)) {
2875 (void) sd_bus_error_move(error
, &enqueue_error
);
2879 /* Hmm, the API is not yet available. Let's use the classic API instead (see below). */
2880 log_notice("--show-transaction not supported by this service manager, proceeding without.");
2885 r
= sd_bus_message_read(reply
, "uosos", &id
, &path
, &u
, NULL
, &jt
);
2887 return bus_log_parse_error(r
);
2889 log_info("Enqueued anchor job %" PRIu32
" %s/%s.", id
, u
, jt
);
2891 r
= sd_bus_message_enter_container(reply
, 'a', "(uosos)");
2893 return bus_log_parse_error(r
);
2895 r
= sd_bus_message_read(reply
, "(uosos)", &id
, NULL
, &u
, NULL
, &jt
);
2897 return bus_log_parse_error(r
);
2901 log_info("Enqueued auxiliary job %" PRIu32
" %s/%s.", id
, u
, jt
);
2904 r
= sd_bus_message_exit_container(reply
);
2906 return bus_log_parse_error(r
);
2913 r
= bus_call_method(bus
, bus_systemd_mgr
, method
, error
, &reply
, "ss", name
, mode
);
2917 r
= sd_bus_message_read(reply
, "o", &path
);
2919 return bus_log_parse_error(r
);
2922 if (need_daemon_reload(bus
, name
) > 0)
2923 warn_unit_file_changed(name
);
2926 log_debug("Adding %s to the set", path
);
2927 r
= bus_wait_for_jobs_add(w
, path
);
2929 return log_error_errno(r
, "Failed to watch job for %s: %m", name
);
2933 r
= bus_wait_for_units_add_unit(wu
, name
, BUS_WAIT_FOR_INACTIVE
|BUS_WAIT_NO_JOB
, NULL
, NULL
);
2935 return log_error_errno(r
, "Failed to watch unit %s: %m", name
);
2941 /* There's always a fallback possible for legacy actions. */
2942 if (arg_action
!= ACTION_SYSTEMCTL
)
2945 log_error_errno(r
, "Failed to %s %s: %s", job_type
, name
, bus_error_message(error
, r
));
2947 if (!sd_bus_error_has_name(error
, BUS_ERROR_NO_SUCH_UNIT
) &&
2948 !sd_bus_error_has_name(error
, BUS_ERROR_UNIT_MASKED
) &&
2949 !sd_bus_error_has_name(error
, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE
))
2950 log_error("See %s logs and 'systemctl%s status%s %s' for details.",
2951 arg_scope
== UNIT_FILE_SYSTEM
? "system" : "user",
2952 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user",
2953 name
[0] == '-' ? " --" : "",
2959 static const struct {
2963 } action_table
[_ACTION_MAX
] = {
2964 [ACTION_HALT
] = { SPECIAL_HALT_TARGET
, "halt", "replace-irreversibly" },
2965 [ACTION_POWEROFF
] = { SPECIAL_POWEROFF_TARGET
, "poweroff", "replace-irreversibly" },
2966 [ACTION_REBOOT
] = { SPECIAL_REBOOT_TARGET
, "reboot", "replace-irreversibly" },
2967 [ACTION_KEXEC
] = { SPECIAL_KEXEC_TARGET
, "kexec", "replace-irreversibly" },
2968 [ACTION_RUNLEVEL2
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
2969 [ACTION_RUNLEVEL3
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
2970 [ACTION_RUNLEVEL4
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
2971 [ACTION_RUNLEVEL5
] = { SPECIAL_GRAPHICAL_TARGET
, NULL
, "isolate" },
2972 [ACTION_RESCUE
] = { SPECIAL_RESCUE_TARGET
, "rescue", "isolate" },
2973 [ACTION_EMERGENCY
] = { SPECIAL_EMERGENCY_TARGET
, "emergency", "isolate" },
2974 [ACTION_DEFAULT
] = { SPECIAL_DEFAULT_TARGET
, "default", "isolate" },
2975 [ACTION_EXIT
] = { SPECIAL_EXIT_TARGET
, "exit", "replace-irreversibly" },
2976 [ACTION_SUSPEND
] = { SPECIAL_SUSPEND_TARGET
, "suspend", "replace-irreversibly" },
2977 [ACTION_HIBERNATE
] = { SPECIAL_HIBERNATE_TARGET
, "hibernate", "replace-irreversibly" },
2978 [ACTION_HYBRID_SLEEP
] = { SPECIAL_HYBRID_SLEEP_TARGET
, "hybrid-sleep", "replace-irreversibly" },
2979 [ACTION_SUSPEND_THEN_HIBERNATE
] = { SPECIAL_SUSPEND_THEN_HIBERNATE_TARGET
, "suspend-then-hibernate", "replace-irreversibly" },
2982 static enum action
verb_to_action(const char *verb
) {
2985 for (i
= 0; i
< _ACTION_MAX
; i
++)
2986 if (streq_ptr(action_table
[i
].verb
, verb
))
2989 return _ACTION_INVALID
;
2992 static const char** make_extra_args(const char *extra_args
[static 4]) {
2997 if (arg_scope
!= UNIT_FILE_SYSTEM
)
2998 extra_args
[n
++] = "--user";
3000 if (arg_transport
== BUS_TRANSPORT_REMOTE
) {
3001 extra_args
[n
++] = "-H";
3002 extra_args
[n
++] = arg_host
;
3003 } else if (arg_transport
== BUS_TRANSPORT_MACHINE
) {
3004 extra_args
[n
++] = "-M";
3005 extra_args
[n
++] = arg_host
;
3007 assert(arg_transport
== BUS_TRANSPORT_LOCAL
);
3009 extra_args
[n
] = NULL
;
3013 static int start_unit(int argc
, char *argv
[], void *userdata
) {
3014 _cleanup_(bus_wait_for_units_freep
) BusWaitForUnits
*wu
= NULL
;
3015 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
3016 const char *method
, *job_type
, *mode
, *one_name
, *suffix
= NULL
;
3017 _cleanup_free_
char **stopped_units
= NULL
; /* Do not use _cleanup_strv_free_ */
3018 _cleanup_strv_free_
char **names
= NULL
;
3019 int r
, ret
= EXIT_SUCCESS
;
3023 if (arg_wait
&& !STR_IN_SET(argv
[0], "start", "restart"))
3024 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3025 "--wait may only be used with the 'start' or 'restart' commands.");
3027 /* we cannot do sender tracking on the private bus, so we need the full
3028 * one for RefUnit to implement --wait */
3029 r
= acquire_bus(arg_wait
? BUS_FULL
: BUS_MANAGER
, &bus
);
3033 ask_password_agent_open_maybe();
3034 polkit_agent_open_maybe();
3036 if (arg_action
== ACTION_SYSTEMCTL
) {
3039 action
= verb_to_action(argv
[0]);
3041 if (action
!= _ACTION_INVALID
) {
3042 /* A command in style "systemctl reboot", "systemctl poweroff", … */
3043 method
= "StartUnit";
3045 mode
= action_table
[action
].mode
;
3046 one_name
= action_table
[action
].target
;
3048 if (streq(argv
[0], "isolate")) {
3049 /* A "systemctl isolate <unit1> <unit2> …" command */
3050 method
= "StartUnit";
3055 /* A command in style of "systemctl start <unit1> <unit2> …", "sysemctl stop <unit1> <unit2> …" and so on */
3056 method
= verb_to_method(argv
[0]);
3057 job_type
= verb_to_job_type(argv
[0]);
3058 mode
= arg_job_mode
;
3063 /* A SysV legacy command such as "halt", "reboot", "poweroff", … */
3064 assert(arg_action
>= 0 && arg_action
< _ACTION_MAX
);
3065 assert(action_table
[arg_action
].target
);
3066 assert(action_table
[arg_action
].mode
);
3068 method
= "StartUnit";
3070 mode
= action_table
[arg_action
].mode
;
3071 one_name
= action_table
[arg_action
].target
;
3075 names
= strv_new(one_name
);
3081 r
= expand_names(bus
, strv_skip(argv
, 1), suffix
, &names
, &expanded
);
3083 return log_error_errno(r
, "Failed to expand names: %m");
3085 if (!arg_all
&& expanded
&& streq(job_type
, "start") && !arg_quiet
) {
3086 log_warning("Warning: %ssystemctl start called with a glob pattern.%s",
3087 ansi_highlight_red(),
3089 log_notice("Hint: unit globs expand to loaded units, so start will usually have no effect.\n"
3090 " Passing --all will also load units which are pulled in by other units.\n"
3091 " See systemctl(1) for more details.");
3095 if (!arg_no_block
) {
3096 r
= bus_wait_for_jobs_new(bus
, &w
);
3098 return log_error_errno(r
, "Could not watch jobs: %m");
3102 r
= bus_call_method_async(bus
, NULL
, bus_systemd_mgr
, "Subscribe", NULL
, NULL
, NULL
);
3104 return log_error_errno(r
, "Failed to enable subscription: %m");
3106 r
= bus_wait_for_units_new(bus
, &wu
);
3108 return log_error_errno(r
, "Failed to allocate unit watch context: %m");
3111 STRV_FOREACH(name
, names
) {
3112 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3114 r
= start_unit_one(bus
, method
, job_type
, *name
, mode
, &error
, w
, wu
);
3115 if (ret
== EXIT_SUCCESS
&& r
< 0)
3116 ret
= translate_bus_error_to_exit_status(r
, &error
);
3118 if (r
>= 0 && streq(method
, "StopUnit")) {
3119 r
= strv_push(&stopped_units
, *name
);
3125 if (!arg_no_block
) {
3126 const char* extra_args
[4];
3128 r
= bus_wait_for_jobs(w
, arg_quiet
, make_extra_args(extra_args
));
3132 /* When stopping units, warn if they can still be triggered by
3133 * another active unit (socket, path, timer) */
3135 STRV_FOREACH(name
, stopped_units
)
3136 (void) check_triggering_units(bus
, *name
);
3140 r
= bus_wait_for_units_run(wu
);
3142 return log_error_errno(r
, "Failed to wait for units: %m");
3143 if (r
== BUS_WAIT_FAILURE
&& ret
== EXIT_SUCCESS
)
3151 static int logind_set_wall_message(void) {
3152 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3154 _cleanup_free_
char *m
= NULL
;
3157 r
= acquire_bus(BUS_FULL
, &bus
);
3161 m
= strv_join(arg_wall
, " ");
3165 log_debug("%s wall message \"%s\".", arg_dry_run
? "Would set" : "Setting", m
);
3169 r
= bus_call_method(bus
, bus_login_mgr
, "SetWallMessage", &error
, NULL
, "sb", m
, !arg_no_wall
);
3171 return log_warning_errno(r
, "Failed to set wall message, ignoring: %s", bus_error_message(&error
, r
));
3176 /* Ask systemd-logind, which might grant access to unprivileged users through polkit */
3177 static int logind_reboot(enum action a
) {
3179 static const struct {
3181 const char *description
;
3182 } actions
[_ACTION_MAX
] = {
3183 [ACTION_POWEROFF
] = { "PowerOff", "power off system" },
3184 [ACTION_REBOOT
] = { "Reboot", "reboot system" },
3185 [ACTION_HALT
] = { "Halt", "halt system" },
3186 [ACTION_SUSPEND
] = { "Suspend", "suspend system" },
3187 [ACTION_HIBERNATE
] = { "Hibernate", "hibernate system" },
3188 [ACTION_HYBRID_SLEEP
] = { "HybridSleep", "put system into hybrid sleep" },
3189 [ACTION_SUSPEND_THEN_HIBERNATE
] = { "SuspendThenHibernate", "suspend system, hibernate later" },
3192 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3196 if (a
< 0 || a
>= _ACTION_MAX
|| !actions
[a
].method
)
3199 r
= acquire_bus(BUS_FULL
, &bus
);
3203 polkit_agent_open_maybe();
3204 (void) logind_set_wall_message();
3206 log_debug("%s org.freedesktop.login1.Manager %s dbus call.", arg_dry_run
? "Would execute" : "Executing", actions
[a
].method
);
3211 r
= bus_call_method(bus
, bus_login_mgr
, actions
[a
].method
, &error
, NULL
, "b", arg_ask_password
);
3213 return log_error_errno(r
, "Failed to %s via logind: %s", actions
[a
].description
, bus_error_message(&error
, r
));
3221 static int logind_check_inhibitors(enum action a
) {
3223 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
3224 _cleanup_strv_free_
char **sessions
= NULL
;
3225 const char *what
, *who
, *why
, *mode
;
3232 if (arg_ignore_inhibitors
|| arg_force
> 0)
3244 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
3247 r
= acquire_bus(BUS_FULL
, &bus
);
3251 r
= bus_call_method(bus
, bus_login_mgr
, "ListInhibitors", NULL
, &reply
, NULL
);
3253 /* If logind is not around, then there are no inhibitors... */
3256 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssuu)");
3258 return bus_log_parse_error(r
);
3260 while ((r
= sd_bus_message_read(reply
, "(ssssuu)", &what
, &who
, &why
, &mode
, &uid
, &pid
)) > 0) {
3261 _cleanup_free_
char *comm
= NULL
, *user
= NULL
;
3262 _cleanup_strv_free_
char **sv
= NULL
;
3264 if (!streq(mode
, "block"))
3267 sv
= strv_split(what
, ":");
3271 if (!pid_is_valid((pid_t
) pid
))
3272 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Invalid PID "PID_FMT
".", (pid_t
) pid
);
3274 if (!strv_contains(sv
,
3279 ACTION_KEXEC
) ? "shutdown" : "sleep"))
3282 get_process_comm(pid
, &comm
);
3283 user
= uid_to_name(uid
);
3285 log_warning("Operation inhibited by \"%s\" (PID "PID_FMT
" \"%s\", user %s), reason is \"%s\".",
3286 who
, (pid_t
) pid
, strna(comm
), strna(user
), why
);
3291 return bus_log_parse_error(r
);
3293 r
= sd_bus_message_exit_container(reply
);
3295 return bus_log_parse_error(r
);
3297 /* Check for current sessions */
3298 sd_get_sessions(&sessions
);
3299 STRV_FOREACH(s
, sessions
) {
3300 _cleanup_free_
char *type
= NULL
, *tty
= NULL
, *seat
= NULL
, *user
= NULL
, *service
= NULL
, *class = NULL
;
3302 if (sd_session_get_uid(*s
, &uid
) < 0 || uid
== getuid())
3305 if (sd_session_get_class(*s
, &class) < 0 || !streq(class, "user"))
3308 if (sd_session_get_type(*s
, &type
) < 0 || !STR_IN_SET(type
, "x11", "wayland", "tty", "mir"))
3311 sd_session_get_tty(*s
, &tty
);
3312 sd_session_get_seat(*s
, &seat
);
3313 sd_session_get_service(*s
, &service
);
3314 user
= uid_to_name(uid
);
3316 log_warning("User %s is logged in on %s.", strna(user
), isempty(tty
) ? (isempty(seat
) ? strna(service
) : seat
) : tty
);
3323 log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'systemctl %s -i'.",
3324 action_table
[a
].verb
);
3332 static int prepare_firmware_setup(void) {
3334 if (!arg_firmware_setup
)
3338 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3342 r
= acquire_bus(BUS_FULL
, &bus
);
3346 r
= bus_call_method(bus
, bus_login_mgr
, "SetRebootToFirmwareSetup", &error
, NULL
, "b", true);
3348 return log_error_errno(r
, "Cannot indicate to EFI to boot into setup mode: %s", bus_error_message(&error
, r
));
3352 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3353 "Booting into firmware setup not supported.");
3357 static int prepare_boot_loader_menu(void) {
3359 if (arg_boot_loader_menu
== USEC_INFINITY
)
3363 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3367 r
= acquire_bus(BUS_FULL
, &bus
);
3371 r
= bus_call_method(bus
, bus_login_mgr
, "SetRebootToBootLoaderMenu", &error
, NULL
, "t", arg_boot_loader_menu
);
3373 return log_error_errno(r
, "Cannot indicate to boot loader to enter boot loader entry menu: %s", bus_error_message(&error
, r
));
3377 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3378 "Booting into boot loader menu not supported.");
3382 static int prepare_boot_loader_entry(void) {
3384 if (!arg_boot_loader_entry
)
3388 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3392 r
= acquire_bus(BUS_FULL
, &bus
);
3396 r
= bus_call_method(bus
, bus_login_mgr
, "SetRebootToBootLoaderEntry", &error
, NULL
, "s", arg_boot_loader_entry
);
3398 return log_error_errno(r
, "Cannot set boot into loader entry '%s': %s", arg_boot_loader_entry
, bus_error_message(&error
, r
));
3402 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3403 "Booting into boot loader entry not supported.");
3407 static int load_kexec_kernel(void) {
3408 _cleanup_(boot_config_free
) BootConfig config
= {};
3409 _cleanup_free_
char *kernel
= NULL
, *initrd
= NULL
, *options
= NULL
;
3414 if (kexec_loaded()) {
3415 log_debug("Kexec kernel already loaded.");
3419 if (access(KEXEC
, X_OK
) < 0)
3420 return log_error_errno(errno
, KEXEC
" is not available: %m");
3422 r
= boot_entries_load_config_auto(NULL
, NULL
, &config
);
3424 /* The call doesn't log about ENOKEY, let's do so here. */
3425 return log_error_errno(r
,
3426 "No kexec kernel loaded and autodetection failed.\n%s",
3428 ? "Cannot automatically load kernel: ESP partition mount point not found."
3429 : "Automatic loading works only on systems booted with EFI.");
3433 e
= boot_config_default_entry(&config
);
3435 return log_error_errno(SYNTHETIC_ERRNO(ENOENT
),
3436 "No boot loader entry suitable as default, refusing to guess.");
3438 log_debug("Found default boot loader entry in file \"%s\"", e
->path
);
3441 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3442 "Boot entry does not refer to Linux kernel, which is not supported currently.");
3443 if (strv_length(e
->initrd
) > 1)
3444 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3445 "Boot entry specifies multiple initrds, which is not supported currently.");
3447 kernel
= path_join(e
->root
, e
->kernel
);
3451 if (!strv_isempty(e
->initrd
)) {
3452 initrd
= path_join(e
->root
, e
->initrd
[0]);
3457 options
= strv_join(e
->options
, " ");
3461 log_full(arg_quiet
? LOG_DEBUG
: LOG_INFO
,
3462 "%s "KEXEC
" --load \"%s\" --append \"%s\"%s%s%s",
3463 arg_dry_run
? "Would run" : "Running",
3466 initrd
? " --initrd \"" : NULL
, strempty(initrd
), initrd
? "\"" : "");
3470 r
= safe_fork("(kexec)", FORK_WAIT
|FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
, &pid
);
3474 const char* const args
[] = {
3477 "--append", options
,
3478 initrd
? "--initrd" : NULL
, initrd
,
3483 execv(args
[0], (char * const *) args
);
3484 _exit(EXIT_FAILURE
);
3490 static int set_exit_code(uint8_t code
) {
3491 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3495 r
= acquire_bus(BUS_MANAGER
, &bus
);
3499 r
= bus_call_method(bus
, bus_systemd_mgr
, "SetExitCode", &error
, NULL
, "y", code
);
3501 return log_error_errno(r
, "Failed to set exit code: %s", bus_error_message(&error
, r
));
3506 static int start_special(int argc
, char *argv
[], void *userdata
) {
3509 bool termination_action
; /* an action that terminates the manager,
3510 * can be performed also by signal. */
3514 a
= verb_to_action(argv
[0]);
3516 r
= logind_check_inhibitors(a
);
3520 if (arg_force
>= 2) {
3526 r
= prepare_firmware_setup();
3530 r
= prepare_boot_loader_menu();
3534 r
= prepare_boot_loader_entry();
3538 if (a
== ACTION_REBOOT
) {
3539 const char *arg
= NULL
;
3542 if (arg_reboot_argument
)
3543 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Both --reboot-argument= and positional argument passed to reboot command, refusing.");
3545 log_notice("Positional argument to reboot command is deprecated, please use --reboot-argument= instead. Accepting anyway.");
3548 arg
= arg_reboot_argument
;
3551 r
= update_reboot_parameter_and_warn(arg
, false);
3556 } else if (a
== ACTION_KEXEC
) {
3557 r
= load_kexec_kernel();
3558 if (r
< 0 && arg_force
>= 1)
3559 log_notice("Failed to load kexec kernel, continuing without.");
3563 } else if (a
== ACTION_EXIT
&& argc
> 1) {
3566 /* If the exit code is not given on the command line,
3567 * don't reset it to zero: just keep it as it might
3568 * have been set previously. */
3570 r
= safe_atou8(argv
[1], &code
);
3572 return log_error_errno(r
, "Invalid exit code.");
3574 r
= set_exit_code(code
);
3579 termination_action
= IN_SET(a
,
3583 if (termination_action
&& arg_force
>= 2)
3586 if (arg_force
>= 1 &&
3587 (termination_action
|| IN_SET(a
, ACTION_KEXEC
, ACTION_EXIT
)))
3588 r
= trivial_method(argc
, argv
, userdata
);
3590 /* First try logind, to allow authentication with polkit */
3597 ACTION_HYBRID_SLEEP
,
3598 ACTION_SUSPEND_THEN_HIBERNATE
)) {
3600 r
= logind_reboot(a
);
3603 if (IN_SET(r
, -EOPNOTSUPP
, -EINPROGRESS
))
3604 /* requested operation is not supported or already in progress */
3607 /* On all other errors, try low-level operation. In order to minimize the difference between
3608 * operation with and without logind, we explicitly enable non-blocking mode for this, as
3609 * logind's shutdown operations are always non-blocking. */
3611 arg_no_block
= true;
3613 } else if (IN_SET(a
, ACTION_EXIT
, ACTION_KEXEC
))
3614 /* Since exit/kexec are so close in behaviour to power-off/reboot, let's also make them
3615 * asynchronous, in order to not confuse the user needlessly with unexpected behaviour. */
3616 arg_no_block
= true;
3618 r
= start_unit(argc
, argv
, userdata
);
3621 if (termination_action
&& arg_force
< 2 &&
3622 IN_SET(r
, -ENOENT
, -ETIMEDOUT
))
3623 log_notice("It is possible to perform action directly, see discussion of --force --force in man:systemctl(1).");
3628 static int start_system_special(int argc
, char *argv
[], void *userdata
) {
3629 /* Like start_special above, but raises an error when running in user mode */
3631 if (arg_scope
!= UNIT_FILE_SYSTEM
)
3632 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3633 "Bad action for %s mode.",
3634 arg_scope
== UNIT_FILE_GLOBAL
? "--global" : "--user");
3636 return start_special(argc
, argv
, userdata
);
3639 static int check_unit_generic(int code
, const UnitActiveState good_states
[], int nb_states
, char **args
) {
3640 _cleanup_strv_free_
char **names
= NULL
;
3641 UnitActiveState active_state
;
3647 r
= acquire_bus(BUS_MANAGER
, &bus
);
3651 r
= expand_names(bus
, args
, NULL
, &names
, NULL
);
3653 return log_error_errno(r
, "Failed to expand names: %m");
3655 STRV_FOREACH(name
, names
) {
3656 r
= get_state_one_unit(bus
, *name
, &active_state
);
3661 puts(unit_active_state_to_string(active_state
));
3663 for (i
= 0; i
< nb_states
; ++i
)
3664 if (good_states
[i
] == active_state
)
3668 /* use the given return code for the case that we won't find
3669 * any unit which matches the list */
3670 return found
? 0 : code
;
3673 static int check_unit_active(int argc
, char *argv
[], void *userdata
) {
3674 static const UnitActiveState states
[] = {
3679 /* According to LSB: 3, "program is not running" */
3680 return check_unit_generic(EXIT_PROGRAM_NOT_RUNNING
, states
, ELEMENTSOF(states
), strv_skip(argv
, 1));
3683 static int check_unit_failed(int argc
, char *argv
[], void *userdata
) {
3684 static const UnitActiveState states
[] = {
3688 return check_unit_generic(EXIT_PROGRAM_DEAD_AND_PID_EXISTS
, states
, ELEMENTSOF(states
), strv_skip(argv
, 1));
3691 static int kill_unit(int argc
, char *argv
[], void *userdata
) {
3692 _cleanup_strv_free_
char **names
= NULL
;
3693 char *kill_who
= NULL
, **name
;
3697 r
= acquire_bus(BUS_MANAGER
, &bus
);
3701 polkit_agent_open_maybe();
3704 arg_kill_who
= "all";
3706 /* --fail was specified */
3707 if (streq(arg_job_mode
, "fail"))
3708 kill_who
= strjoina(arg_kill_who
, "-fail");
3710 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
3712 return log_error_errno(r
, "Failed to expand names: %m");
3714 STRV_FOREACH(name
, names
) {
3715 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3717 q
= bus_call_method(
3723 "ssi", *name
, kill_who
? kill_who
: arg_kill_who
, arg_signal
);
3725 log_error_errno(q
, "Failed to kill unit %s: %s", *name
, bus_error_message(&error
, q
));
3734 static int clean_or_freeze_unit(int argc
, char *argv
[], void *userdata
) {
3735 _cleanup_(bus_wait_for_units_freep
) BusWaitForUnits
*w
= NULL
;
3736 _cleanup_strv_free_
char **names
= NULL
;
3737 int r
, ret
= EXIT_SUCCESS
;
3742 r
= acquire_bus(BUS_FULL
, &bus
);
3746 polkit_agent_open_maybe();
3748 if (!arg_clean_what
) {
3749 arg_clean_what
= strv_new("cache", "runtime");
3750 if (!arg_clean_what
)
3754 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
3756 return log_error_errno(r
, "Failed to expand names: %m");
3758 if (!arg_no_block
) {
3759 r
= bus_wait_for_units_new(bus
, &w
);
3761 return log_error_errno(r
, "Failed to allocate unit waiter: %m");
3764 if (streq(argv
[0], "clean"))
3765 method
= "CleanUnit";
3766 else if (streq(argv
[0], "freeze"))
3767 method
= "FreezeUnit";
3768 else if (streq(argv
[0], "thaw"))
3769 method
= "ThawUnit";
3771 assert_not_reached("Unhandled method");
3773 STRV_FOREACH(name
, names
) {
3774 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3775 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
3778 /* If we shall wait for the cleaning to complete, let's add a ref on the unit first */
3779 r
= bus_call_method(bus
, bus_systemd_mgr
, "RefUnit", &error
, NULL
, "s", *name
);
3781 log_error_errno(r
, "Failed to add reference to unit %s: %s", *name
, bus_error_message(&error
, r
));
3782 if (ret
== EXIT_SUCCESS
)
3788 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, method
);
3790 return bus_log_create_error(r
);
3792 r
= sd_bus_message_append(m
, "s", *name
);
3794 return bus_log_create_error(r
);
3796 if (streq(method
, "CleanUnit")) {
3797 r
= sd_bus_message_append_strv(m
, arg_clean_what
);
3799 return bus_log_create_error(r
);
3802 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
3804 log_error_errno(r
, "Failed to %s unit %s: %s", argv
[0], *name
, bus_error_message(&error
, r
));
3805 if (ret
== EXIT_SUCCESS
) {
3812 r
= bus_wait_for_units_add_unit(w
, *name
, BUS_WAIT_REFFED
|BUS_WAIT_FOR_MAINTENANCE_END
, NULL
, NULL
);
3814 return log_error_errno(r
, "Failed to watch unit %s: %m", *name
);
3818 r
= bus_wait_for_units_run(w
);
3820 return log_error_errno(r
, "Failed to wait for units: %m");
3821 if (r
== BUS_WAIT_FAILURE
)
3827 typedef struct ExecStatusInfo
{
3835 usec_t start_timestamp
;
3836 usec_t exit_timestamp
;
3841 ExecCommandFlags flags
;
3843 LIST_FIELDS(struct ExecStatusInfo
, exec
);
3846 static void exec_status_info_free(ExecStatusInfo
*i
) {
3855 static int exec_status_info_deserialize(sd_bus_message
*m
, ExecStatusInfo
*i
, bool is_ex_prop
) {
3856 _cleanup_strv_free_
char **ex_opts
= NULL
;
3857 uint64_t start_timestamp
, exit_timestamp
, start_timestamp_monotonic
, exit_timestamp_monotonic
;
3860 int32_t code
, status
;
3866 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_STRUCT
, is_ex_prop
? "sasasttttuii" : "sasbttttuii");
3868 return bus_log_parse_error(r
);
3872 r
= sd_bus_message_read(m
, "s", &path
);
3874 return bus_log_parse_error(r
);
3876 i
->path
= strdup(path
);
3880 r
= sd_bus_message_read_strv(m
, &i
->argv
);
3882 return bus_log_parse_error(r
);
3884 r
= is_ex_prop
? sd_bus_message_read_strv(m
, &ex_opts
) : sd_bus_message_read(m
, "b", &ignore
);
3886 return bus_log_parse_error(r
);
3888 r
= sd_bus_message_read(m
,
3890 &start_timestamp
, &start_timestamp_monotonic
,
3891 &exit_timestamp
, &exit_timestamp_monotonic
,
3895 return bus_log_parse_error(r
);
3898 r
= exec_command_flags_from_strv(ex_opts
, &i
->flags
);
3900 return log_error_errno(r
, "Failed to convert strv to ExecCommandFlags: %m");
3902 i
->ignore
= FLAGS_SET(i
->flags
, EXEC_COMMAND_IGNORE_FAILURE
);
3906 i
->start_timestamp
= (usec_t
) start_timestamp
;
3907 i
->exit_timestamp
= (usec_t
) exit_timestamp
;
3908 i
->pid
= (pid_t
) pid
;
3912 r
= sd_bus_message_exit_container(m
);
3914 return bus_log_parse_error(r
);
3919 typedef struct UnitCondition
{
3926 LIST_FIELDS(struct UnitCondition
, conditions
);
3929 static void unit_condition_free(UnitCondition
*c
) {
3938 DEFINE_TRIVIAL_CLEANUP_FUNC(UnitCondition
*, unit_condition_free
);
3940 typedef struct UnitStatusInfo
{
3942 const char *load_state
;
3943 const char *active_state
;
3944 const char *freezer_state
;
3945 const char *sub_state
;
3946 const char *unit_file_state
;
3947 const char *unit_file_preset
;
3949 const char *description
;
3950 const char *following
;
3952 char **documentation
;
3954 const char *fragment_path
;
3955 const char *source_path
;
3956 const char *control_group
;
3958 char **dropin_paths
;
3960 char **triggered_by
;
3963 const char *load_error
;
3966 usec_t inactive_exit_timestamp
;
3967 usec_t inactive_exit_timestamp_monotonic
;
3968 usec_t active_enter_timestamp
;
3969 usec_t active_exit_timestamp
;
3970 usec_t inactive_enter_timestamp
;
3972 bool need_daemon_reload
;
3978 const char *status_text
;
3979 const char *pid_file
;
3983 usec_t start_timestamp
;
3984 usec_t exit_timestamp
;
3986 int exit_code
, exit_status
;
3988 const char *log_namespace
;
3990 usec_t condition_timestamp
;
3991 bool condition_result
;
3992 LIST_HEAD(UnitCondition
, conditions
);
3994 usec_t assert_timestamp
;
3996 bool failed_assert_trigger
;
3997 bool failed_assert_negate
;
3998 const char *failed_assert
;
3999 const char *failed_assert_parameter
;
4000 usec_t next_elapse_real
;
4001 usec_t next_elapse_monotonic
;
4004 unsigned n_accepted
;
4005 unsigned n_connections
;
4009 /* Pairs of type, path */
4013 const char *sysfs_path
;
4015 /* Mount, Automount */
4022 uint64_t memory_current
;
4023 uint64_t memory_min
;
4024 uint64_t memory_low
;
4025 uint64_t memory_high
;
4026 uint64_t memory_max
;
4027 uint64_t memory_swap_max
;
4028 uint64_t memory_limit
;
4029 uint64_t cpu_usage_nsec
;
4030 uint64_t tasks_current
;
4032 uint64_t ip_ingress_bytes
;
4033 uint64_t ip_egress_bytes
;
4034 uint64_t io_read_bytes
;
4035 uint64_t io_write_bytes
;
4037 uint64_t default_memory_min
;
4038 uint64_t default_memory_low
;
4040 LIST_HEAD(ExecStatusInfo
, exec
);
4043 static void unit_status_info_free(UnitStatusInfo
*info
) {
4047 strv_free(info
->documentation
);
4048 strv_free(info
->dropin_paths
);
4049 strv_free(info
->triggered_by
);
4050 strv_free(info
->triggers
);
4051 strv_free(info
->listen
);
4053 while ((c
= info
->conditions
)) {
4054 LIST_REMOVE(conditions
, info
->conditions
, c
);
4055 unit_condition_free(c
);
4058 while ((p
= info
->exec
)) {
4059 LIST_REMOVE(exec
, info
->exec
, p
);
4060 exec_status_info_free(p
);
4064 static void format_active_state(const char *active_state
, const char **active_on
, const char **active_off
) {
4065 if (streq_ptr(active_state
, "failed")) {
4066 *active_on
= ansi_highlight_red();
4067 *active_off
= ansi_normal();
4068 } else if (STRPTR_IN_SET(active_state
, "active", "reloading")) {
4069 *active_on
= ansi_highlight_green();
4070 *active_off
= ansi_normal();
4072 *active_on
= *active_off
= "";
4075 static void print_status_info(
4080 char since1
[FORMAT_TIMESTAMP_RELATIVE_MAX
], since2
[FORMAT_TIMESTAMP_MAX
];
4081 const char *s1
, *s2
, *active_on
, *active_off
, *on
, *off
, *ss
, *fs
;
4082 _cleanup_free_
char *formatted_path
= NULL
;
4091 /* This shows pretty information about a unit. See
4092 * print_property() for a low-level property printer */
4094 format_active_state(i
->active_state
, &active_on
, &active_off
);
4096 printf("%s%s%s %s", active_on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), active_off
, strna(i
->id
));
4098 if (i
->description
&& !streq_ptr(i
->id
, i
->description
))
4099 printf(" - %s", i
->description
);
4104 printf(" Follow: unit currently follows state of %s\n", i
->following
);
4106 if (STRPTR_IN_SET(i
->load_state
, "error", "not-found", "bad-setting")) {
4107 on
= ansi_highlight_red();
4108 off
= ansi_normal();
4112 path
= i
->source_path
?: i
->fragment_path
;
4113 if (path
&& terminal_urlify_path(path
, NULL
, &formatted_path
) >= 0)
4114 path
= formatted_path
;
4116 if (!isempty(i
->load_error
))
4117 printf(" Loaded: %s%s%s (Reason: %s)\n",
4118 on
, strna(i
->load_state
), off
, i
->load_error
);
4119 else if (path
&& !isempty(i
->unit_file_state
)) {
4120 bool show_preset
= !isempty(i
->unit_file_preset
) &&
4121 show_preset_for_state(unit_file_state_from_string(i
->unit_file_state
));
4123 printf(" Loaded: %s%s%s (%s; %s%s%s)\n",
4124 on
, strna(i
->load_state
), off
,
4127 show_preset
? "; vendor preset: " : "",
4128 show_preset
? i
->unit_file_preset
: "");
4131 printf(" Loaded: %s%s%s (%s)\n",
4132 on
, strna(i
->load_state
), off
, path
);
4134 printf(" Loaded: %s%s%s\n",
4135 on
, strna(i
->load_state
), off
);
4138 printf(" Transient: yes\n");
4140 if (!strv_isempty(i
->dropin_paths
)) {
4141 _cleanup_free_
char *dir
= NULL
;
4145 STRV_FOREACH(dropin
, i
->dropin_paths
) {
4146 _cleanup_free_
char *dropin_formatted
= NULL
;
4155 dir
= dirname_malloc(*dropin
);
4163 special_glyph(SPECIAL_GLYPH_TREE_RIGHT
));
4166 last
= ! (*(dropin
+ 1) && startswith(*(dropin
+ 1), dir
));
4168 if (terminal_urlify_path(*dropin
, basename(*dropin
), &dropin_formatted
) >= 0)
4169 df
= dropin_formatted
;
4173 printf("%s%s", df
, last
? "\n" : ", ");
4177 ss
= streq_ptr(i
->active_state
, i
->sub_state
) ? NULL
: i
->sub_state
;
4179 printf(" Active: %s%s (%s)%s",
4180 active_on
, strna(i
->active_state
), ss
, active_off
);
4182 printf(" Active: %s%s%s",
4183 active_on
, strna(i
->active_state
), active_off
);
4185 fs
= !isempty(i
->freezer_state
) && !streq(i
->freezer_state
, "running") ? i
->freezer_state
: NULL
;
4187 printf(" %s(%s)%s", ansi_highlight_yellow(), fs
, ansi_normal());
4189 if (!isempty(i
->result
) && !streq(i
->result
, "success"))
4190 printf(" (Result: %s)", i
->result
);
4192 timestamp
= STRPTR_IN_SET(i
->active_state
, "active", "reloading") ? i
->active_enter_timestamp
:
4193 STRPTR_IN_SET(i
->active_state
, "inactive", "failed") ? i
->inactive_enter_timestamp
:
4194 STRPTR_IN_SET(i
->active_state
, "activating") ? i
->inactive_exit_timestamp
:
4195 i
->active_exit_timestamp
;
4197 s1
= format_timestamp_relative(since1
, sizeof(since1
), timestamp
);
4198 s2
= format_timestamp(since2
, sizeof(since2
), timestamp
);
4201 printf(" since %s; %s\n", s2
, s1
);
4203 printf(" since %s\n", s2
);
4207 STRV_FOREACH(t
, i
->triggered_by
) {
4208 UnitActiveState state
= _UNIT_ACTIVE_STATE_INVALID
;
4210 (void) get_state_one_unit(bus
, *t
, &state
);
4211 format_active_state(unit_active_state_to_string(state
), &on
, &off
);
4213 printf("%s %s%s%s %s\n",
4214 t
== i
->triggered_by
? "TriggeredBy:" : " ",
4215 on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
,
4219 if (endswith(i
->id
, ".timer")) {
4220 char tstamp1
[FORMAT_TIMESTAMP_RELATIVE_MAX
],
4221 tstamp2
[FORMAT_TIMESTAMP_MAX
];
4222 const char *next_rel_time
, *next_time
;
4223 dual_timestamp nw
, next
= {i
->next_elapse_real
,
4224 i
->next_elapse_monotonic
};
4227 printf(" Trigger: ");
4229 dual_timestamp_get(&nw
);
4230 next_elapse
= calc_next_elapse(&nw
, &next
);
4231 next_rel_time
= format_timestamp_relative(tstamp1
, sizeof tstamp1
, next_elapse
);
4232 next_time
= format_timestamp(tstamp2
, sizeof tstamp2
, next_elapse
);
4234 if (next_time
&& next_rel_time
)
4235 printf("%s; %s\n", next_time
, next_rel_time
);
4240 STRV_FOREACH(t
, i
->triggers
) {
4241 UnitActiveState state
= _UNIT_ACTIVE_STATE_INVALID
;
4243 (void) get_state_one_unit(bus
, *t
, &state
);
4244 format_active_state(unit_active_state_to_string(state
), &on
, &off
);
4246 printf("%s %s%s%s %s\n",
4247 t
== i
->triggers
? " Triggers:" : " ",
4248 on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
,
4252 if (!i
->condition_result
&& i
->condition_timestamp
> 0) {
4256 s1
= format_timestamp_relative(since1
, sizeof(since1
), i
->condition_timestamp
);
4257 s2
= format_timestamp(since2
, sizeof(since2
), i
->condition_timestamp
);
4259 printf(" Condition: start %scondition failed%s at %s%s%s\n",
4260 ansi_highlight_yellow(), ansi_normal(),
4261 s2
, s1
? "; " : "", strempty(s1
));
4263 LIST_FOREACH(conditions
, c
, i
->conditions
)
4264 if (c
->tristate
< 0)
4267 LIST_FOREACH(conditions
, c
, i
->conditions
)
4268 if (c
->tristate
< 0)
4269 printf(" %s %s=%s%s%s was not met\n",
4270 --n
? special_glyph(SPECIAL_GLYPH_TREE_BRANCH
) : special_glyph(SPECIAL_GLYPH_TREE_RIGHT
),
4272 c
->trigger
? "|" : "",
4273 c
->negate
? "!" : "",
4277 if (!i
->assert_result
&& i
->assert_timestamp
> 0) {
4278 s1
= format_timestamp_relative(since1
, sizeof(since1
), i
->assert_timestamp
);
4279 s2
= format_timestamp(since2
, sizeof(since2
), i
->assert_timestamp
);
4281 printf(" Assert: start %sassertion failed%s at %s%s%s\n",
4282 ansi_highlight_red(), ansi_normal(),
4283 s2
, s1
? "; " : "", strempty(s1
));
4284 if (i
->failed_assert_trigger
)
4285 printf(" none of the trigger assertions were met\n");
4286 else if (i
->failed_assert
)
4287 printf(" %s=%s%s was not met\n",
4289 i
->failed_assert_negate
? "!" : "",
4290 i
->failed_assert_parameter
);
4294 printf(" Device: %s\n", i
->sysfs_path
);
4296 printf(" Where: %s\n", i
->where
);
4298 printf(" What: %s\n", i
->what
);
4300 STRV_FOREACH(t
, i
->documentation
) {
4301 _cleanup_free_
char *formatted
= NULL
;
4304 if (terminal_urlify(*t
, NULL
, &formatted
) >= 0)
4309 printf(" %*s %s\n", 9, t
== i
->documentation
? "Docs:" : "", q
);
4312 STRV_FOREACH_PAIR(t
, t2
, i
->listen
)
4313 printf(" %*s %s (%s)\n", 9, t
== i
->listen
? "Listen:" : "", *t2
, *t
);
4316 printf(" Accepted: %u; Connected: %u;", i
->n_accepted
, i
->n_connections
);
4318 printf(" Refused: %u", i
->n_refused
);
4322 LIST_FOREACH(exec
, p
, i
->exec
) {
4323 _cleanup_free_
char *argv
= NULL
;
4326 /* Only show exited processes here */
4330 /* Don't print ExecXYZEx= properties here since it will appear as a
4331 * duplicate of the non-Ex= variant. */
4332 if (endswith(p
->name
, "Ex"))
4335 argv
= strv_join(p
->argv
, " ");
4336 printf(" Process: "PID_FMT
" %s=%s ", p
->pid
, p
->name
, strna(argv
));
4338 good
= is_clean_exit(p
->code
, p
->status
, EXIT_CLEAN_DAEMON
, NULL
);
4340 on
= ansi_highlight_red();
4341 off
= ansi_normal();
4345 printf("%s(code=%s, ", on
, sigchld_code_to_string(p
->code
));
4347 if (p
->code
== CLD_EXITED
) {
4350 printf("status=%i", p
->status
);
4352 c
= exit_status_to_string(p
->status
, EXIT_STATUS_LIBC
| EXIT_STATUS_SYSTEMD
);
4357 printf("signal=%s", signal_to_string(p
->status
));
4359 printf(")%s\n", off
);
4361 if (i
->main_pid
== p
->pid
&&
4362 i
->start_timestamp
== p
->start_timestamp
&&
4363 i
->exit_timestamp
== p
->start_timestamp
)
4364 /* Let's not show this twice */
4367 if (p
->pid
== i
->control_pid
)
4371 if (i
->main_pid
> 0 || i
->control_pid
> 0) {
4372 if (i
->main_pid
> 0) {
4373 printf(" Main PID: "PID_FMT
, i
->main_pid
);
4377 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
4378 _cleanup_free_
char *comm
= NULL
;
4380 (void) get_process_comm(i
->main_pid
, &comm
);
4382 printf(" (%s)", comm
);
4385 } else if (i
->exit_code
> 0) {
4386 printf(" (code=%s, ", sigchld_code_to_string(i
->exit_code
));
4388 if (i
->exit_code
== CLD_EXITED
) {
4391 printf("status=%i", i
->exit_status
);
4393 c
= exit_status_to_string(i
->exit_status
,
4394 EXIT_STATUS_LIBC
| EXIT_STATUS_SYSTEMD
);
4399 printf("signal=%s", signal_to_string(i
->exit_status
));
4404 if (i
->control_pid
> 0) {
4405 _cleanup_free_
char *c
= NULL
;
4407 if (i
->main_pid
> 0)
4408 fputs("; Control PID: ", stdout
);
4410 fputs("Cntrl PID: ", stdout
); /* if first in column, abbreviated so it fits alignment */
4412 printf(PID_FMT
, i
->control_pid
);
4414 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
4415 (void) get_process_comm(i
->control_pid
, &c
);
4425 printf(" Status: \"%s\"\n", i
->status_text
);
4426 if (i
->status_errno
> 0)
4427 printf(" Error: %i (%s)\n", i
->status_errno
, strerror_safe(i
->status_errno
));
4429 if (i
->ip_ingress_bytes
!= (uint64_t) -1 && i
->ip_egress_bytes
!= (uint64_t) -1) {
4430 char buf_in
[FORMAT_BYTES_MAX
], buf_out
[FORMAT_BYTES_MAX
];
4432 printf(" IP: %s in, %s out\n",
4433 format_bytes(buf_in
, sizeof(buf_in
), i
->ip_ingress_bytes
),
4434 format_bytes(buf_out
, sizeof(buf_out
), i
->ip_egress_bytes
));
4437 if (i
->io_read_bytes
!= UINT64_MAX
&& i
->io_write_bytes
!= UINT64_MAX
) {
4438 char buf_in
[FORMAT_BYTES_MAX
], buf_out
[FORMAT_BYTES_MAX
];
4440 printf(" IO: %s read, %s written\n",
4441 format_bytes(buf_in
, sizeof(buf_in
), i
->io_read_bytes
),
4442 format_bytes(buf_out
, sizeof(buf_out
), i
->io_write_bytes
));
4445 if (i
->tasks_current
!= (uint64_t) -1) {
4446 printf(" Tasks: %" PRIu64
, i
->tasks_current
);
4448 if (i
->tasks_max
!= (uint64_t) -1)
4449 printf(" (limit: %" PRIu64
")\n", i
->tasks_max
);
4454 if (i
->memory_current
!= (uint64_t) -1) {
4455 char buf
[FORMAT_BYTES_MAX
];
4457 printf(" Memory: %s", format_bytes(buf
, sizeof(buf
), i
->memory_current
));
4459 if (i
->memory_min
> 0 || i
->memory_low
> 0 ||
4460 i
->memory_high
!= CGROUP_LIMIT_MAX
|| i
->memory_max
!= CGROUP_LIMIT_MAX
||
4461 i
->memory_swap_max
!= CGROUP_LIMIT_MAX
||
4462 i
->memory_limit
!= CGROUP_LIMIT_MAX
) {
4463 const char *prefix
= "";
4466 if (i
->memory_min
> 0) {
4467 printf("%smin: %s", prefix
, format_bytes_cgroup_protection(buf
, sizeof(buf
), i
->memory_min
));
4470 if (i
->memory_low
> 0) {
4471 printf("%slow: %s", prefix
, format_bytes_cgroup_protection(buf
, sizeof(buf
), i
->memory_low
));
4474 if (i
->memory_high
!= CGROUP_LIMIT_MAX
) {
4475 printf("%shigh: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_high
));
4478 if (i
->memory_max
!= CGROUP_LIMIT_MAX
) {
4479 printf("%smax: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_max
));
4482 if (i
->memory_swap_max
!= CGROUP_LIMIT_MAX
) {
4483 printf("%sswap max: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_swap_max
));
4486 if (i
->memory_limit
!= CGROUP_LIMIT_MAX
) {
4487 printf("%slimit: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_limit
));
4495 if (i
->cpu_usage_nsec
!= (uint64_t) -1) {
4496 char buf
[FORMAT_TIMESPAN_MAX
];
4497 printf(" CPU: %s\n", format_timespan(buf
, sizeof(buf
), i
->cpu_usage_nsec
/ NSEC_PER_USEC
, USEC_PER_MSEC
));
4500 if (i
->control_group
) {
4501 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
4502 static const char prefix
[] = " ";
4505 printf(" CGroup: %s\n", i
->control_group
);
4508 if (c
> sizeof(prefix
) - 1)
4509 c
-= sizeof(prefix
) - 1;
4513 r
= unit_show_processes(bus
, i
->id
, i
->control_group
, prefix
, c
, get_output_flags(), &error
);
4518 /* Fallback for older systemd versions where the GetUnitProcesses() call is not yet available */
4520 if (i
->main_pid
> 0)
4521 extra
[k
++] = i
->main_pid
;
4523 if (i
->control_pid
> 0)
4524 extra
[k
++] = i
->control_pid
;
4526 show_cgroup_and_extra(SYSTEMD_CGROUP_CONTROLLER
, i
->control_group
, prefix
, c
, extra
, k
, get_output_flags());
4528 log_warning_errno(r
, "Failed to dump process list for '%s', ignoring: %s",
4529 i
->id
, bus_error_message(&error
, r
));
4532 if (i
->id
&& arg_transport
== BUS_TRANSPORT_LOCAL
)
4533 show_journal_by_unit(
4539 i
->inactive_exit_timestamp_monotonic
,
4542 get_output_flags() | OUTPUT_BEGIN_NEWLINE
,
4543 SD_JOURNAL_LOCAL_ONLY
,
4544 arg_scope
== UNIT_FILE_SYSTEM
,
4547 if (i
->need_daemon_reload
)
4548 warn_unit_file_changed(i
->id
);
4551 static void show_unit_help(UnitStatusInfo
*i
) {
4556 if (!i
->documentation
) {
4557 log_info("Documentation for %s not known.", i
->id
);
4561 STRV_FOREACH(p
, i
->documentation
)
4562 if (startswith(*p
, "man:"))
4563 show_man_page(*p
+ 4, false);
4565 log_info("Can't show: %s", *p
);
4568 static int map_main_pid(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4569 UnitStatusInfo
*i
= userdata
;
4573 r
= sd_bus_message_read(m
, "u", &u
);
4577 i
->main_pid
= (pid_t
) u
;
4583 static int map_load_error(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4584 const char *message
, **p
= userdata
;
4587 r
= sd_bus_message_read(m
, "(ss)", NULL
, &message
);
4591 if (!isempty(message
))
4597 static int map_listen(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4598 const char *type
, *path
;
4599 char ***p
= userdata
;
4602 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
4606 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0) {
4608 r
= strv_extend(p
, type
);
4612 r
= strv_extend(p
, path
);
4619 r
= sd_bus_message_exit_container(m
);
4626 static int map_conditions(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4627 UnitStatusInfo
*i
= userdata
;
4628 const char *cond
, *param
;
4629 int trigger
, negate
;
4633 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sbbsi)");
4637 while ((r
= sd_bus_message_read(m
, "(sbbsi)", &cond
, &trigger
, &negate
, ¶m
, &state
)) > 0) {
4638 _cleanup_(unit_condition_freep
) UnitCondition
*c
= NULL
;
4640 c
= new(UnitCondition
, 1);
4644 *c
= (UnitCondition
) {
4645 .name
= strdup(cond
),
4646 .param
= strdup(param
),
4652 if (!c
->name
|| !c
->param
)
4655 LIST_PREPEND(conditions
, i
->conditions
, TAKE_PTR(c
));
4660 r
= sd_bus_message_exit_container(m
);
4667 static int map_asserts(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4668 UnitStatusInfo
*i
= userdata
;
4669 const char *cond
, *param
;
4670 int trigger
, negate
;
4674 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sbbsi)");
4678 while ((r
= sd_bus_message_read(m
, "(sbbsi)", &cond
, &trigger
, &negate
, ¶m
, &state
)) > 0) {
4679 if (state
< 0 && (!trigger
|| !i
->failed_assert
)) {
4680 i
->failed_assert
= cond
;
4681 i
->failed_assert_trigger
= trigger
;
4682 i
->failed_assert_negate
= negate
;
4683 i
->failed_assert_parameter
= param
;
4689 r
= sd_bus_message_exit_container(m
);
4696 static int map_exec(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4697 _cleanup_free_ ExecStatusInfo
*info
= NULL
;
4698 ExecStatusInfo
*last
;
4699 UnitStatusInfo
*i
= userdata
;
4700 bool is_ex_prop
= endswith(member
, "Ex");
4703 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, is_ex_prop
? "(sasasttttuii)" : "(sasbttttuii)");
4707 info
= new0(ExecStatusInfo
, 1);
4711 LIST_FIND_TAIL(exec
, i
->exec
, last
);
4713 while ((r
= exec_status_info_deserialize(m
, info
, is_ex_prop
)) > 0) {
4715 info
->name
= strdup(member
);
4719 LIST_INSERT_AFTER(exec
, i
->exec
, last
, info
);
4722 info
= new0(ExecStatusInfo
, 1);
4729 r
= sd_bus_message_exit_container(m
);
4736 static int print_property(const char *name
, const char *expected_value
, sd_bus_message
*m
, bool value
, bool all
) {
4738 const char *contents
;
4744 /* This is a low-level property printer, see
4745 * print_status_info() for the nicer output */
4747 r
= sd_bus_message_peek_type(m
, &bus_type
, &contents
);
4753 case SD_BUS_TYPE_INT32
:
4754 if (endswith(name
, "ActionExitStatus")) {
4757 r
= sd_bus_message_read_basic(m
, bus_type
, &i
);
4761 if (i
>= 0 && i
<= 255)
4762 bus_print_property_valuef(name
, expected_value
, value
, "%"PRIi32
, i
);
4764 bus_print_property_value(name
, expected_value
, value
, "[not set]");
4767 } else if (streq(name
, "NUMAPolicy")) {
4770 r
= sd_bus_message_read_basic(m
, bus_type
, &i
);
4774 bus_print_property_valuef(name
, expected_value
, value
, "%s", strna(mpol_to_string(i
)));
4780 case SD_BUS_TYPE_STRUCT
:
4782 if (contents
[0] == SD_BUS_TYPE_UINT32
&& streq(name
, "Job")) {
4785 r
= sd_bus_message_read(m
, "(uo)", &u
, NULL
);
4787 return bus_log_parse_error(r
);
4790 bus_print_property_valuef(name
, expected_value
, value
, "%"PRIu32
, u
);
4792 bus_print_property_value(name
, expected_value
, value
, "");
4796 } else if (contents
[0] == SD_BUS_TYPE_STRING
&& streq(name
, "Unit")) {
4799 r
= sd_bus_message_read(m
, "(so)", &s
, NULL
);
4801 return bus_log_parse_error(r
);
4803 if (all
|| !isempty(s
))
4804 bus_print_property_value(name
, expected_value
, value
, s
);
4808 } else if (contents
[0] == SD_BUS_TYPE_STRING
&& streq(name
, "LoadError")) {
4809 const char *a
= NULL
, *b
= NULL
;
4811 r
= sd_bus_message_read(m
, "(ss)", &a
, &b
);
4813 return bus_log_parse_error(r
);
4815 if (!isempty(a
) || !isempty(b
))
4816 bus_print_property_valuef(name
, expected_value
, value
, "%s \"%s\"", strempty(a
), strempty(b
));
4818 bus_print_property_value(name
, expected_value
, value
, "");
4822 } else if (STR_IN_SET(name
, "SystemCallFilter", "RestrictAddressFamilies")) {
4823 _cleanup_strv_free_
char **l
= NULL
;
4826 r
= sd_bus_message_enter_container(m
, 'r', "bas");
4828 return bus_log_parse_error(r
);
4830 r
= sd_bus_message_read(m
, "b", &allow_list
);
4832 return bus_log_parse_error(r
);
4834 r
= sd_bus_message_read_strv(m
, &l
);
4836 return bus_log_parse_error(r
);
4838 r
= sd_bus_message_exit_container(m
);
4840 return bus_log_parse_error(r
);
4842 if (all
|| allow_list
|| !strv_isempty(l
)) {
4847 fputs(name
, stdout
);
4854 STRV_FOREACH(i
, l
) {
4862 fputc('\n', stdout
);
4867 } else if (STR_IN_SET(name
, "SELinuxContext", "AppArmorProfile", "SmackProcessLabel")) {
4871 r
= sd_bus_message_read(m
, "(bs)", &ignore
, &s
);
4873 return bus_log_parse_error(r
);
4876 bus_print_property_valuef(name
, expected_value
, value
, "%s%s", ignore
? "-" : "", s
);
4878 bus_print_property_value(name
, expected_value
, value
, "");
4882 } else if (endswith(name
, "ExitStatus") && streq(contents
, "aiai")) {
4883 const int32_t *status
, *signal
;
4884 size_t n_status
, n_signal
, i
;
4886 r
= sd_bus_message_enter_container(m
, 'r', "aiai");
4888 return bus_log_parse_error(r
);
4890 r
= sd_bus_message_read_array(m
, 'i', (const void **) &status
, &n_status
);
4892 return bus_log_parse_error(r
);
4894 r
= sd_bus_message_read_array(m
, 'i', (const void **) &signal
, &n_signal
);
4896 return bus_log_parse_error(r
);
4898 r
= sd_bus_message_exit_container(m
);
4900 return bus_log_parse_error(r
);
4902 n_status
/= sizeof(int32_t);
4903 n_signal
/= sizeof(int32_t);
4905 if (all
|| n_status
> 0 || n_signal
> 0) {
4909 fputs(name
, stdout
);
4913 for (i
= 0; i
< n_status
; i
++) {
4919 printf("%"PRIi32
, status
[i
]);
4922 for (i
= 0; i
< n_signal
; i
++) {
4925 str
= signal_to_string((int) signal
[i
]);
4935 printf("%"PRIi32
, status
[i
]);
4938 fputc('\n', stdout
);
4945 case SD_BUS_TYPE_ARRAY
:
4947 if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "EnvironmentFiles")) {
4951 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sb)");
4953 return bus_log_parse_error(r
);
4955 while ((r
= sd_bus_message_read(m
, "(sb)", &path
, &ignore
)) > 0)
4956 bus_print_property_valuef(name
, expected_value
, value
, "%s (ignore_errors=%s)", path
, yes_no(ignore
));
4959 return bus_log_parse_error(r
);
4961 r
= sd_bus_message_exit_container(m
);
4963 return bus_log_parse_error(r
);
4967 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "Paths")) {
4968 const char *type
, *path
;
4970 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
4972 return bus_log_parse_error(r
);
4974 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0)
4975 bus_print_property_valuef(name
, expected_value
, value
, "%s (%s)", path
, type
);
4977 return bus_log_parse_error(r
);
4979 r
= sd_bus_message_exit_container(m
);
4981 return bus_log_parse_error(r
);
4985 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "Listen")) {
4986 const char *type
, *path
;
4988 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
4990 return bus_log_parse_error(r
);
4992 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0)
4993 bus_print_property_valuef(name
, expected_value
, value
, "%s (%s)", path
, type
);
4995 return bus_log_parse_error(r
);
4997 r
= sd_bus_message_exit_container(m
);
4999 return bus_log_parse_error(r
);
5003 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "TimersMonotonic")) {
5005 uint64_t v
, next_elapse
;
5007 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(stt)");
5009 return bus_log_parse_error(r
);
5011 while ((r
= sd_bus_message_read(m
, "(stt)", &base
, &v
, &next_elapse
)) > 0) {
5012 char timespan1
[FORMAT_TIMESPAN_MAX
] = "n/a", timespan2
[FORMAT_TIMESPAN_MAX
] = "n/a";
5014 (void) format_timespan(timespan1
, sizeof timespan1
, v
, 0);
5015 (void) format_timespan(timespan2
, sizeof timespan2
, next_elapse
, 0);
5017 bus_print_property_valuef(name
, expected_value
, value
,
5018 "{ %s=%s ; next_elapse=%s }", base
, timespan1
, timespan2
);
5021 return bus_log_parse_error(r
);
5023 r
= sd_bus_message_exit_container(m
);
5025 return bus_log_parse_error(r
);
5029 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "TimersCalendar")) {
5030 const char *base
, *spec
;
5031 uint64_t next_elapse
;
5033 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sst)");
5035 return bus_log_parse_error(r
);
5037 while ((r
= sd_bus_message_read(m
, "(sst)", &base
, &spec
, &next_elapse
)) > 0) {
5038 char timestamp
[FORMAT_TIMESTAMP_MAX
] = "n/a";
5040 (void) format_timestamp(timestamp
, sizeof(timestamp
), next_elapse
);
5041 bus_print_property_valuef(name
, expected_value
, value
,
5042 "{ %s=%s ; next_elapse=%s }", base
, spec
, timestamp
);
5045 return bus_log_parse_error(r
);
5047 r
= sd_bus_message_exit_container(m
);
5049 return bus_log_parse_error(r
);
5053 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& startswith(name
, "Exec")) {
5054 ExecStatusInfo info
= {};
5055 bool is_ex_prop
= endswith(name
, "Ex");
5057 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, is_ex_prop
? "(sasasttttuii)" : "(sasbttttuii)");
5059 return bus_log_parse_error(r
);
5061 while ((r
= exec_status_info_deserialize(m
, &info
, is_ex_prop
)) > 0) {
5062 char timestamp1
[FORMAT_TIMESTAMP_MAX
], timestamp2
[FORMAT_TIMESTAMP_MAX
];
5063 _cleanup_strv_free_
char **optv
= NULL
;
5064 _cleanup_free_
char *tt
, *o
= NULL
;
5066 tt
= strv_join(info
.argv
, " ");
5069 r
= exec_command_flags_to_strv(info
.flags
, &optv
);
5071 return log_error_errno(r
, "Failed to convert ExecCommandFlags to strv: %m");
5073 o
= strv_join(optv
, " ");
5075 bus_print_property_valuef(name
, expected_value
, value
,
5076 "{ path=%s ; argv[]=%s ; flags=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT
" ; code=%s ; status=%i%s%s }",
5080 strna(format_timestamp(timestamp1
, sizeof(timestamp1
), info
.start_timestamp
)),
5081 strna(format_timestamp(timestamp2
, sizeof(timestamp2
), info
.exit_timestamp
)),
5083 sigchld_code_to_string(info
.code
),
5085 info
.code
== CLD_EXITED
? "" : "/",
5086 strempty(info
.code
== CLD_EXITED
? NULL
: signal_to_string(info
.status
)));
5088 bus_print_property_valuef(name
, expected_value
, value
,
5089 "{ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT
" ; code=%s ; status=%i%s%s }",
5092 yes_no(info
.ignore
),
5093 strna(format_timestamp(timestamp1
, sizeof(timestamp1
), info
.start_timestamp
)),
5094 strna(format_timestamp(timestamp2
, sizeof(timestamp2
), info
.exit_timestamp
)),
5096 sigchld_code_to_string(info
.code
),
5098 info
.code
== CLD_EXITED
? "" : "/",
5099 strempty(info
.code
== CLD_EXITED
? NULL
: signal_to_string(info
.status
)));
5102 strv_free(info
.argv
);
5106 r
= sd_bus_message_exit_container(m
);
5108 return bus_log_parse_error(r
);
5112 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "DeviceAllow")) {
5113 const char *path
, *rwm
;
5115 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5117 return bus_log_parse_error(r
);
5119 while ((r
= sd_bus_message_read(m
, "(ss)", &path
, &rwm
)) > 0)
5120 bus_print_property_valuef(name
, expected_value
, value
, "%s %s", strna(path
), strna(rwm
));
5122 return bus_log_parse_error(r
);
5124 r
= sd_bus_message_exit_container(m
);
5126 return bus_log_parse_error(r
);
5130 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5131 STR_IN_SET(name
, "IODeviceWeight", "BlockIODeviceWeight")) {
5135 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5137 return bus_log_parse_error(r
);
5139 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &weight
)) > 0)
5140 bus_print_property_valuef(name
, expected_value
, value
, "%s %"PRIu64
, strna(path
), weight
);
5142 return bus_log_parse_error(r
);
5144 r
= sd_bus_message_exit_container(m
);
5146 return bus_log_parse_error(r
);
5150 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5151 (cgroup_io_limit_type_from_string(name
) >= 0 ||
5152 STR_IN_SET(name
, "BlockIOReadBandwidth", "BlockIOWriteBandwidth"))) {
5156 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5158 return bus_log_parse_error(r
);
5160 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &bandwidth
)) > 0)
5161 bus_print_property_valuef(name
, expected_value
, value
, "%s %"PRIu64
, strna(path
), bandwidth
);
5163 return bus_log_parse_error(r
);
5165 r
= sd_bus_message_exit_container(m
);
5167 return bus_log_parse_error(r
);
5171 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5172 streq(name
, "IODeviceLatencyTargetUSec")) {
5173 char ts
[FORMAT_TIMESPAN_MAX
];
5177 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5179 return bus_log_parse_error(r
);
5181 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &target
)) > 0)
5182 bus_print_property_valuef(name
, expected_value
, value
, "%s %s", strna(path
),
5183 format_timespan(ts
, sizeof(ts
), target
, 1));
5185 return bus_log_parse_error(r
);
5187 r
= sd_bus_message_exit_container(m
);
5189 return bus_log_parse_error(r
);
5193 } else if (contents
[0] == SD_BUS_TYPE_BYTE
&& STR_IN_SET(name
, "StandardInputData", "RootHashSignature")) {
5194 _cleanup_free_
char *h
= NULL
;
5199 r
= sd_bus_message_read_array(m
, 'y', &p
, &sz
);
5201 return bus_log_parse_error(r
);
5203 n
= base64mem(p
, sz
, &h
);
5207 bus_print_property_value(name
, expected_value
, value
, h
);
5211 } else if (STR_IN_SET(name
, "IPAddressAllow", "IPAddressDeny")) {
5212 _cleanup_free_
char *addresses
= NULL
;
5214 r
= sd_bus_message_enter_container(m
, 'a', "(iayu)");
5216 return bus_log_parse_error(r
);
5219 _cleanup_free_
char *str
= NULL
;
5225 r
= sd_bus_message_enter_container(m
, 'r', "iayu");
5227 return bus_log_parse_error(r
);
5231 r
= sd_bus_message_read(m
, "i", &family
);
5233 return bus_log_parse_error(r
);
5235 r
= sd_bus_message_read_array(m
, 'y', &ap
, &an
);
5237 return bus_log_parse_error(r
);
5239 r
= sd_bus_message_read(m
, "u", &prefixlen
);
5241 return bus_log_parse_error(r
);
5243 r
= sd_bus_message_exit_container(m
);
5245 return bus_log_parse_error(r
);
5247 if (!IN_SET(family
, AF_INET
, AF_INET6
))
5250 if (an
!= FAMILY_ADDRESS_SIZE(family
))
5253 if (prefixlen
> FAMILY_ADDRESS_SIZE(family
) * 8)
5256 if (in_addr_prefix_to_string(family
, (union in_addr_union
*) ap
, prefixlen
, &str
) < 0)
5259 if (!strextend_with_separator(&addresses
, " ", str
, NULL
))
5263 r
= sd_bus_message_exit_container(m
);
5265 return bus_log_parse_error(r
);
5267 if (all
|| !isempty(addresses
))
5268 bus_print_property_value(name
, expected_value
, value
, strempty(addresses
));
5272 } else if (STR_IN_SET(name
, "BindPaths", "BindReadOnlyPaths")) {
5273 _cleanup_free_
char *paths
= NULL
;
5274 const char *source
, *dest
;
5278 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ssbt)");
5280 return bus_log_parse_error(r
);
5282 while ((r
= sd_bus_message_read(m
, "(ssbt)", &source
, &dest
, &ignore_enoent
, &rbind
)) > 0) {
5283 _cleanup_free_
char *str
= NULL
;
5285 if (isempty(source
))
5288 if (asprintf(&str
, "%s%s%s%s%s",
5289 ignore_enoent
? "-" : "",
5291 isempty(dest
) ? "" : ":",
5293 rbind
== MS_REC
? ":rbind" : "") < 0)
5296 if (!strextend_with_separator(&paths
, " ", str
, NULL
))
5300 return bus_log_parse_error(r
);
5302 r
= sd_bus_message_exit_container(m
);
5304 return bus_log_parse_error(r
);
5306 if (all
|| !isempty(paths
))
5307 bus_print_property_value(name
, expected_value
, value
, strempty(paths
));
5311 } else if (streq(name
, "TemporaryFileSystem")) {
5312 _cleanup_free_
char *paths
= NULL
;
5313 const char *target
, *option
;
5315 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5317 return bus_log_parse_error(r
);
5319 while ((r
= sd_bus_message_read(m
, "(ss)", &target
, &option
)) > 0) {
5320 _cleanup_free_
char *str
= NULL
;
5322 if (isempty(target
))
5325 if (asprintf(&str
, "%s%s%s", target
, isempty(option
) ? "" : ":", strempty(option
)) < 0)
5328 if (!strextend_with_separator(&paths
, " ", str
, NULL
))
5332 return bus_log_parse_error(r
);
5334 r
= sd_bus_message_exit_container(m
);
5336 return bus_log_parse_error(r
);
5338 if (all
|| !isempty(paths
))
5339 bus_print_property_value(name
, expected_value
, value
, strempty(paths
));
5343 } else if (streq(name
, "LogExtraFields")) {
5344 _cleanup_free_
char *fields
= NULL
;
5348 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "ay");
5350 return bus_log_parse_error(r
);
5352 while ((r
= sd_bus_message_read_array(m
, 'y', &p
, &sz
)) > 0) {
5353 _cleanup_free_
char *str
= NULL
;
5356 if (memchr(p
, 0, sz
))
5359 eq
= memchr(p
, '=', sz
);
5363 if (!journal_field_valid(p
, eq
- (const char*) p
, false))
5366 str
= malloc(sz
+ 1);
5373 if (!utf8_is_valid(str
))
5376 if (!strextend_with_separator(&fields
, " ", str
, NULL
))
5380 return bus_log_parse_error(r
);
5382 r
= sd_bus_message_exit_container(m
);
5384 return bus_log_parse_error(r
);
5386 if (all
|| !isempty(fields
))
5387 bus_print_property_value(name
, expected_value
, value
, strempty(fields
));
5390 } else if (contents
[0] == SD_BUS_TYPE_BYTE
&& STR_IN_SET(name
, "CPUAffinity", "NUMAMask", "AllowedCPUs", "AllowedMemoryNodes", "EffectiveCPUs", "EffectiveMemoryNodes")) {
5391 _cleanup_free_
char *affinity
= NULL
;
5392 _cleanup_(cpu_set_reset
) CPUSet set
= {};
5396 r
= sd_bus_message_read_array(m
, 'y', &a
, &n
);
5398 return bus_log_parse_error(r
);
5400 r
= cpu_set_from_dbus(a
, n
, &set
);
5402 return log_error_errno(r
, "Failed to deserialize %s: %m", name
);
5404 affinity
= cpu_set_to_range_string(&set
);
5408 bus_print_property_value(name
, expected_value
, value
, affinity
);
5411 } else if (streq(name
, "MountImages")) {
5412 _cleanup_free_
char *paths
= NULL
;
5413 const char *source
, *dest
;
5416 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ssb)");
5418 return bus_log_parse_error(r
);
5420 while ((r
= sd_bus_message_read(m
, "(ssb)", &source
, &dest
, &ignore_enoent
)) > 0) {
5421 _cleanup_free_
char *str
= NULL
;
5423 if (isempty(source
))
5426 if (asprintf(&str
, "%s%s:%s", ignore_enoent
? "-" : "", source
, dest
) < 0)
5429 if (!strextend_with_separator(&paths
, " ", str
, NULL
))
5433 return bus_log_parse_error(r
);
5435 r
= sd_bus_message_exit_container(m
);
5437 return bus_log_parse_error(r
);
5439 if (all
|| !isempty(paths
))
5440 bus_print_property_value(name
, expected_value
, value
, strempty(paths
));
5452 typedef enum SystemctlShowMode
{
5453 SYSTEMCTL_SHOW_PROPERTIES
,
5454 SYSTEMCTL_SHOW_STATUS
,
5455 SYSTEMCTL_SHOW_HELP
,
5456 _SYSTEMCTL_SHOW_MODE_MAX
,
5457 _SYSTEMCTL_SHOW_MODE_INVALID
= -1,
5458 } SystemctlShowMode
;
5460 static const char* const systemctl_show_mode_table
[_SYSTEMCTL_SHOW_MODE_MAX
] = {
5461 [SYSTEMCTL_SHOW_PROPERTIES
] = "show",
5462 [SYSTEMCTL_SHOW_STATUS
] = "status",
5463 [SYSTEMCTL_SHOW_HELP
] = "help",
5466 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(systemctl_show_mode
, SystemctlShowMode
);
5468 static int show_one(
5472 SystemctlShowMode show_mode
,
5476 static const struct bus_properties_map property_map
[] = {
5477 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
5478 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
) },
5479 { "FreezerState", "s", NULL
, offsetof(UnitStatusInfo
, freezer_state
) },
5480 { "Documentation", "as", NULL
, offsetof(UnitStatusInfo
, documentation
) },
5483 { "Id", "s", NULL
, offsetof(UnitStatusInfo
, id
) },
5484 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
5485 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
) },
5486 { "FreezerState", "s", NULL
, offsetof(UnitStatusInfo
, freezer_state
) },
5487 { "SubState", "s", NULL
, offsetof(UnitStatusInfo
, sub_state
) },
5488 { "UnitFileState", "s", NULL
, offsetof(UnitStatusInfo
, unit_file_state
) },
5489 { "UnitFilePreset", "s", NULL
, offsetof(UnitStatusInfo
, unit_file_preset
) },
5490 { "Description", "s", NULL
, offsetof(UnitStatusInfo
, description
) },
5491 { "Following", "s", NULL
, offsetof(UnitStatusInfo
, following
) },
5492 { "Documentation", "as", NULL
, offsetof(UnitStatusInfo
, documentation
) },
5493 { "FragmentPath", "s", NULL
, offsetof(UnitStatusInfo
, fragment_path
) },
5494 { "SourcePath", "s", NULL
, offsetof(UnitStatusInfo
, source_path
) },
5495 { "ControlGroup", "s", NULL
, offsetof(UnitStatusInfo
, control_group
) },
5496 { "DropInPaths", "as", NULL
, offsetof(UnitStatusInfo
, dropin_paths
) },
5497 { "LoadError", "(ss)", map_load_error
, offsetof(UnitStatusInfo
, load_error
) },
5498 { "Result", "s", NULL
, offsetof(UnitStatusInfo
, result
) },
5499 { "TriggeredBy", "as", NULL
, offsetof(UnitStatusInfo
, triggered_by
) },
5500 { "Triggers", "as", NULL
, offsetof(UnitStatusInfo
, triggers
) },
5501 { "InactiveExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, inactive_exit_timestamp
) },
5502 { "InactiveExitTimestampMonotonic", "t", NULL
, offsetof(UnitStatusInfo
, inactive_exit_timestamp_monotonic
) },
5503 { "ActiveEnterTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, active_enter_timestamp
) },
5504 { "ActiveExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, active_exit_timestamp
) },
5505 { "InactiveEnterTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, inactive_enter_timestamp
) },
5506 { "NeedDaemonReload", "b", NULL
, offsetof(UnitStatusInfo
, need_daemon_reload
) },
5507 { "Transient", "b", NULL
, offsetof(UnitStatusInfo
, transient
) },
5508 { "ExecMainPID", "u", NULL
, offsetof(UnitStatusInfo
, main_pid
) },
5509 { "MainPID", "u", map_main_pid
, 0 },
5510 { "ControlPID", "u", NULL
, offsetof(UnitStatusInfo
, control_pid
) },
5511 { "StatusText", "s", NULL
, offsetof(UnitStatusInfo
, status_text
) },
5512 { "PIDFile", "s", NULL
, offsetof(UnitStatusInfo
, pid_file
) },
5513 { "StatusErrno", "i", NULL
, offsetof(UnitStatusInfo
, status_errno
) },
5514 { "ExecMainStartTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, start_timestamp
) },
5515 { "ExecMainExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, exit_timestamp
) },
5516 { "ExecMainCode", "i", NULL
, offsetof(UnitStatusInfo
, exit_code
) },
5517 { "ExecMainStatus", "i", NULL
, offsetof(UnitStatusInfo
, exit_status
) },
5518 { "LogNamespace", "s", NULL
, offsetof(UnitStatusInfo
, log_namespace
) },
5519 { "ConditionTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, condition_timestamp
) },
5520 { "ConditionResult", "b", NULL
, offsetof(UnitStatusInfo
, condition_result
) },
5521 { "Conditions", "a(sbbsi)", map_conditions
, 0 },
5522 { "AssertTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, assert_timestamp
) },
5523 { "AssertResult", "b", NULL
, offsetof(UnitStatusInfo
, assert_result
) },
5524 { "Asserts", "a(sbbsi)", map_asserts
, 0 },
5525 { "NextElapseUSecRealtime", "t", NULL
, offsetof(UnitStatusInfo
, next_elapse_real
) },
5526 { "NextElapseUSecMonotonic", "t", NULL
, offsetof(UnitStatusInfo
, next_elapse_monotonic
) },
5527 { "NAccepted", "u", NULL
, offsetof(UnitStatusInfo
, n_accepted
) },
5528 { "NConnections", "u", NULL
, offsetof(UnitStatusInfo
, n_connections
) },
5529 { "NRefused", "u", NULL
, offsetof(UnitStatusInfo
, n_refused
) },
5530 { "Accept", "b", NULL
, offsetof(UnitStatusInfo
, accept
) },
5531 { "Listen", "a(ss)", map_listen
, offsetof(UnitStatusInfo
, listen
) },
5532 { "SysFSPath", "s", NULL
, offsetof(UnitStatusInfo
, sysfs_path
) },
5533 { "Where", "s", NULL
, offsetof(UnitStatusInfo
, where
) },
5534 { "What", "s", NULL
, offsetof(UnitStatusInfo
, what
) },
5535 { "MemoryCurrent", "t", NULL
, offsetof(UnitStatusInfo
, memory_current
) },
5536 { "DefaultMemoryMin", "t", NULL
, offsetof(UnitStatusInfo
, default_memory_min
) },
5537 { "DefaultMemoryLow", "t", NULL
, offsetof(UnitStatusInfo
, default_memory_low
) },
5538 { "MemoryMin", "t", NULL
, offsetof(UnitStatusInfo
, memory_min
) },
5539 { "MemoryLow", "t", NULL
, offsetof(UnitStatusInfo
, memory_low
) },
5540 { "MemoryHigh", "t", NULL
, offsetof(UnitStatusInfo
, memory_high
) },
5541 { "MemoryMax", "t", NULL
, offsetof(UnitStatusInfo
, memory_max
) },
5542 { "MemorySwapMax", "t", NULL
, offsetof(UnitStatusInfo
, memory_swap_max
) },
5543 { "MemoryLimit", "t", NULL
, offsetof(UnitStatusInfo
, memory_limit
) },
5544 { "CPUUsageNSec", "t", NULL
, offsetof(UnitStatusInfo
, cpu_usage_nsec
) },
5545 { "TasksCurrent", "t", NULL
, offsetof(UnitStatusInfo
, tasks_current
) },
5546 { "TasksMax", "t", NULL
, offsetof(UnitStatusInfo
, tasks_max
) },
5547 { "IPIngressBytes", "t", NULL
, offsetof(UnitStatusInfo
, ip_ingress_bytes
) },
5548 { "IPEgressBytes", "t", NULL
, offsetof(UnitStatusInfo
, ip_egress_bytes
) },
5549 { "IOReadBytes", "t", NULL
, offsetof(UnitStatusInfo
, io_read_bytes
) },
5550 { "IOWriteBytes", "t", NULL
, offsetof(UnitStatusInfo
, io_write_bytes
) },
5551 { "ExecCondition", "a(sasbttttuii)", map_exec
, 0 },
5552 { "ExecConditionEx", "a(sasasttttuii)", map_exec
, 0 },
5553 { "ExecStartPre", "a(sasbttttuii)", map_exec
, 0 },
5554 { "ExecStartPreEx", "a(sasasttttuii)", map_exec
, 0 },
5555 { "ExecStart", "a(sasbttttuii)", map_exec
, 0 },
5556 { "ExecStartEx", "a(sasasttttuii)", map_exec
, 0 },
5557 { "ExecStartPost", "a(sasbttttuii)", map_exec
, 0 },
5558 { "ExecStartPostEx", "a(sasasttttuii)", map_exec
, 0 },
5559 { "ExecReload", "a(sasbttttuii)", map_exec
, 0 },
5560 { "ExecReloadEx", "a(sasasttttuii)", map_exec
, 0 },
5561 { "ExecStopPre", "a(sasbttttuii)", map_exec
, 0 },
5562 { "ExecStop", "a(sasbttttuii)", map_exec
, 0 },
5563 { "ExecStopEx", "a(sasasttttuii)", map_exec
, 0 },
5564 { "ExecStopPost", "a(sasbttttuii)", map_exec
, 0 },
5565 { "ExecStopPostEx", "a(sasasttttuii)", map_exec
, 0 },
5569 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5570 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5571 _cleanup_set_free_ Set
*found_properties
= NULL
;
5572 _cleanup_(unit_status_info_free
) UnitStatusInfo info
= {
5573 .memory_current
= (uint64_t) -1,
5574 .memory_high
= CGROUP_LIMIT_MAX
,
5575 .memory_max
= CGROUP_LIMIT_MAX
,
5576 .memory_swap_max
= CGROUP_LIMIT_MAX
,
5577 .memory_limit
= (uint64_t) -1,
5578 .cpu_usage_nsec
= (uint64_t) -1,
5579 .tasks_current
= (uint64_t) -1,
5580 .tasks_max
= (uint64_t) -1,
5581 .ip_ingress_bytes
= (uint64_t) -1,
5582 .ip_egress_bytes
= (uint64_t) -1,
5583 .io_read_bytes
= UINT64_MAX
,
5584 .io_write_bytes
= UINT64_MAX
,
5592 log_debug("Showing one %s", path
);
5594 r
= bus_map_all_properties(
5596 "org.freedesktop.systemd1",
5598 show_mode
== SYSTEMCTL_SHOW_STATUS
? status_map
: property_map
,
5599 BUS_MAP_BOOLEAN_AS_BOOL
,
5604 return log_error_errno(r
, "Failed to get properties: %s", bus_error_message(&error
, r
));
5606 if (unit
&& streq_ptr(info
.load_state
, "not-found") && streq_ptr(info
.active_state
, "inactive")) {
5607 log_full(show_mode
== SYSTEMCTL_SHOW_STATUS
? LOG_ERR
: LOG_DEBUG
,
5608 "Unit %s could not be found.", unit
);
5610 if (show_mode
== SYSTEMCTL_SHOW_STATUS
)
5611 return EXIT_PROGRAM_OR_SERVICES_STATUS_UNKNOWN
;
5612 else if (show_mode
== SYSTEMCTL_SHOW_HELP
)
5621 if (show_mode
== SYSTEMCTL_SHOW_STATUS
) {
5622 print_status_info(bus
, &info
, ellipsized
);
5624 if (info
.active_state
&& !STR_IN_SET(info
.active_state
, "active", "reloading"))
5625 return EXIT_PROGRAM_NOT_RUNNING
;
5627 return EXIT_PROGRAM_RUNNING_OR_SERVICE_OK
;
5629 } else if (show_mode
== SYSTEMCTL_SHOW_HELP
) {
5630 show_unit_help(&info
);
5634 r
= sd_bus_message_rewind(reply
, true);
5636 return log_error_errno(r
, "Failed to rewind: %s", bus_error_message(&error
, r
));
5638 r
= bus_message_print_all_properties(reply
, print_property
, arg_properties
, arg_value
, arg_all
, &found_properties
);
5640 return bus_log_parse_error(r
);
5642 STRV_FOREACH(pp
, arg_properties
)
5643 if (!set_contains(found_properties
, *pp
))
5644 log_debug("Property %s does not exist.", *pp
);
5649 static int get_unit_dbus_path_by_pid(
5654 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5655 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5659 r
= bus_call_method(bus
, bus_systemd_mgr
, "GetUnitByPID", &error
, &reply
, "u", pid
);
5661 return log_error_errno(r
, "Failed to get unit for PID %"PRIu32
": %s", pid
, bus_error_message(&error
, r
));
5663 r
= sd_bus_message_read(reply
, "o", &u
);
5665 return bus_log_parse_error(r
);
5675 static int show_all(
5680 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5681 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
5686 r
= get_unit_list(bus
, NULL
, NULL
, &unit_infos
, 0, &reply
);
5690 (void) pager_open(arg_pager_flags
);
5694 typesafe_qsort(unit_infos
, c
, compare_unit_info
);
5696 for (u
= unit_infos
; u
< unit_infos
+ c
; u
++) {
5697 _cleanup_free_
char *p
= NULL
;
5699 p
= unit_dbus_path_from_name(u
->id
);
5703 r
= show_one(bus
, p
, u
->id
, SYSTEMCTL_SHOW_STATUS
, new_line
, ellipsized
);
5706 else if (r
> 0 && ret
== 0)
5713 static int show_system_status(sd_bus
*bus
) {
5714 char since1
[FORMAT_TIMESTAMP_RELATIVE_MAX
], since2
[FORMAT_TIMESTAMP_MAX
];
5715 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5716 _cleanup_(machine_info_clear
) struct machine_info mi
= {};
5717 _cleanup_free_
char *hn
= NULL
;
5718 const char *on
, *off
;
5721 hn
= gethostname_malloc();
5725 r
= bus_map_all_properties(
5727 "org.freedesktop.systemd1",
5728 "/org/freedesktop/systemd1",
5729 machine_info_property_map
,
5735 return log_error_errno(r
, "Failed to read server status: %s", bus_error_message(&error
, r
));
5737 if (streq_ptr(mi
.state
, "degraded")) {
5738 on
= ansi_highlight_red();
5739 off
= ansi_normal();
5740 } else if (streq_ptr(mi
.state
, "running")) {
5741 on
= ansi_highlight_green();
5742 off
= ansi_normal();
5744 on
= ansi_highlight_yellow();
5745 off
= ansi_normal();
5748 printf("%s%s%s %s\n", on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
, arg_host
? arg_host
: hn
);
5750 printf(" State: %s%s%s\n",
5751 on
, strna(mi
.state
), off
);
5753 printf(" Jobs: %" PRIu32
" queued\n", mi
.n_jobs
);
5754 printf(" Failed: %" PRIu32
" units\n", mi
.n_failed_units
);
5756 printf(" Since: %s; %s\n",
5757 format_timestamp(since2
, sizeof(since2
), mi
.timestamp
),
5758 format_timestamp_relative(since1
, sizeof(since1
), mi
.timestamp
));
5760 printf(" CGroup: %s\n", mi
.control_group
?: "/");
5761 if (IN_SET(arg_transport
,
5762 BUS_TRANSPORT_LOCAL
,
5763 BUS_TRANSPORT_MACHINE
)) {
5764 static const char prefix
[] = " ";
5768 if (c
> sizeof(prefix
) - 1)
5769 c
-= sizeof(prefix
) - 1;
5773 show_cgroup(SYSTEMD_CGROUP_CONTROLLER
, strempty(mi
.control_group
), prefix
, c
, get_output_flags());
5779 static int show(int argc
, char *argv
[], void *userdata
) {
5780 bool new_line
= false, ellipsized
= false;
5781 SystemctlShowMode show_mode
;
5787 show_mode
= systemctl_show_mode_from_string(argv
[0]);
5789 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
5790 "Invalid argument.");
5792 if (show_mode
== SYSTEMCTL_SHOW_HELP
&& argc
<= 1)
5793 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
5794 "'help' command expects one or more unit names.\n"
5795 "(Alternatively, help for systemctl itself may be shown with --help)");
5797 r
= acquire_bus(BUS_MANAGER
, &bus
);
5801 (void) pager_open(arg_pager_flags
);
5803 /* If no argument is specified inspect the manager itself */
5804 if (show_mode
== SYSTEMCTL_SHOW_PROPERTIES
&& argc
<= 1)
5805 return show_one(bus
, "/org/freedesktop/systemd1", NULL
, show_mode
, &new_line
, &ellipsized
);
5807 if (show_mode
== SYSTEMCTL_SHOW_STATUS
&& argc
<= 1) {
5809 show_system_status(bus
);
5813 ret
= show_all(bus
, &new_line
, &ellipsized
);
5815 _cleanup_free_
char **patterns
= NULL
;
5818 STRV_FOREACH(name
, strv_skip(argv
, 1)) {
5819 _cleanup_free_
char *path
= NULL
, *unit
= NULL
;
5822 if (safe_atou32(*name
, &id
) < 0) {
5823 if (strv_push(&patterns
, *name
) < 0)
5827 } else if (show_mode
== SYSTEMCTL_SHOW_PROPERTIES
) {
5828 /* Interpret as job id */
5829 if (asprintf(&path
, "/org/freedesktop/systemd1/job/%u", id
) < 0)
5833 /* Interpret as PID */
5834 r
= get_unit_dbus_path_by_pid(bus
, id
, &path
);
5840 r
= unit_name_from_dbus_path(path
, &unit
);
5845 r
= show_one(bus
, path
, unit
, show_mode
, &new_line
, &ellipsized
);
5848 else if (r
> 0 && ret
== 0)
5852 if (!strv_isempty(patterns
)) {
5853 _cleanup_strv_free_
char **names
= NULL
;
5855 r
= expand_names(bus
, patterns
, NULL
, &names
, NULL
);
5857 return log_error_errno(r
, "Failed to expand names: %m");
5859 r
= maybe_extend_with_unit_dependencies(bus
, &names
);
5863 STRV_FOREACH(name
, names
) {
5864 _cleanup_free_
char *path
;
5866 path
= unit_dbus_path_from_name(*name
);
5870 r
= show_one(bus
, path
, *name
, show_mode
, &new_line
, &ellipsized
);
5873 if (r
> 0 && ret
== 0)
5879 if (ellipsized
&& !arg_quiet
)
5880 printf("Hint: Some lines were ellipsized, use -l to show in full.\n");
5885 static int cat(int argc
, char *argv
[], void *userdata
) {
5886 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
5887 _cleanup_strv_free_
char **names
= NULL
;
5893 /* Include all units by default — i.e. continue as if the --all
5894 * option was used */
5895 if (strv_isempty(arg_states
))
5898 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
5899 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot remotely cat units.");
5901 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
5903 return log_error_errno(r
, "Failed to determine unit paths: %m");
5905 r
= acquire_bus(BUS_MANAGER
, &bus
);
5909 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
5911 return log_error_errno(r
, "Failed to expand names: %m");
5913 r
= maybe_extend_with_unit_dependencies(bus
, &names
);
5917 (void) pager_open(arg_pager_flags
);
5919 STRV_FOREACH(name
, names
) {
5920 _cleanup_free_
char *fragment_path
= NULL
;
5921 _cleanup_strv_free_
char **dropin_paths
= NULL
;
5923 r
= unit_find_paths(bus
, *name
, &lp
, false, &fragment_path
, &dropin_paths
);
5924 if (r
== -ERFKILL
) {
5925 printf("%s# Unit %s is masked%s.\n",
5926 ansi_highlight_magenta(),
5931 if (r
== -EKEYREJECTED
) {
5932 printf("%s# Unit %s could not be loaded.%s\n",
5933 ansi_highlight_magenta(),
5941 /* Skip units which have no on-disk counterpart, but
5942 * propagate the error to the user */
5952 if (need_daemon_reload(bus
, *name
) > 0) /* ignore errors (<0), this is informational output */
5954 "%s# Warning: %s changed on disk, the version systemd has loaded is outdated.\n"
5955 "%s# This output shows the current version of the unit's original fragment and drop-in files.\n"
5956 "%s# If fragments or drop-ins were added or removed, they are not properly reflected in this output.\n"
5957 "%s# Run 'systemctl%s daemon-reload' to reload units.%s\n",
5958 ansi_highlight_red(),
5960 ansi_highlight_red(),
5961 ansi_highlight_red(),
5962 ansi_highlight_red(),
5963 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user",
5966 r
= cat_files(fragment_path
, dropin_paths
, 0);
5974 static int set_property(int argc
, char *argv
[], void *userdata
) {
5975 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
5976 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5977 _cleanup_free_
char *n
= NULL
;
5982 r
= acquire_bus(BUS_MANAGER
, &bus
);
5986 polkit_agent_open_maybe();
5988 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "SetUnitProperties");
5990 return bus_log_create_error(r
);
5992 r
= unit_name_mangle(argv
[1], arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, &n
);
5994 return log_error_errno(r
, "Failed to mangle unit name: %m");
5996 t
= unit_name_to_type(n
);
5998 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid unit type: %s", n
);
6000 r
= sd_bus_message_append(m
, "sb", n
, arg_runtime
);
6002 return bus_log_create_error(r
);
6004 r
= sd_bus_message_open_container(m
, SD_BUS_TYPE_ARRAY
, "(sv)");
6006 return bus_log_create_error(r
);
6008 r
= bus_append_unit_property_assignment_many(m
, t
, strv_skip(argv
, 2));
6012 r
= sd_bus_message_close_container(m
);
6014 return bus_log_create_error(r
);
6016 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6018 return log_error_errno(r
, "Failed to set unit properties on %s: %s", n
, bus_error_message(&error
, r
));
6023 static int daemon_reload(int argc
, char *argv
[], void *userdata
) {
6024 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6025 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6030 r
= acquire_bus(BUS_MANAGER
, &bus
);
6034 polkit_agent_open_maybe();
6036 switch (arg_action
) {
6043 method
= "Reexecute";
6046 case ACTION_SYSTEMCTL
:
6047 method
= streq(argv
[0], "daemon-reexec") ? "Reexecute" :
6048 /* "daemon-reload" */ "Reload";
6052 assert_not_reached("Unexpected action");
6055 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, method
);
6057 return bus_log_create_error(r
);
6059 /* Note we use an extra-long timeout here. This is because a reload or reexec means generators are rerun which
6060 * are timed out after DEFAULT_TIMEOUT_USEC. Let's use twice that time here, so that the generators can have
6061 * their timeout, and for everything else there's the same time budget in place. */
6063 r
= sd_bus_call(bus
, m
, DEFAULT_TIMEOUT_USEC
* 2, &error
, NULL
);
6065 /* On reexecution, we expect a disconnect, not a reply */
6066 if (IN_SET(r
, -ETIMEDOUT
, -ECONNRESET
) && streq(method
, "Reexecute"))
6069 if (r
< 0 && arg_action
== ACTION_SYSTEMCTL
)
6070 return log_error_errno(r
, "Failed to reload daemon: %s", bus_error_message(&error
, r
));
6072 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
6073 * old ways of doing things, hence don't log any error in that case here. */
6075 return r
< 0 ? r
: 0;
6078 static int trivial_method(int argc
, char *argv
[], void *userdata
) {
6079 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6087 r
= acquire_bus(BUS_MANAGER
, &bus
);
6091 polkit_agent_open_maybe();
6094 streq(argv
[0], "clear-jobs") ||
6095 streq(argv
[0], "cancel") ? "ClearJobs" :
6096 streq(argv
[0], "reset-failed") ? "ResetFailed" :
6097 streq(argv
[0], "halt") ? "Halt" :
6098 streq(argv
[0], "reboot") ? "Reboot" :
6099 streq(argv
[0], "kexec") ? "KExec" :
6100 streq(argv
[0], "exit") ? "Exit" :
6101 /* poweroff */ "PowerOff";
6103 r
= bus_call_method(bus
, bus_systemd_mgr
, method
, &error
, NULL
, NULL
);
6104 if (r
< 0 && arg_action
== ACTION_SYSTEMCTL
)
6105 return log_error_errno(r
, "Failed to execute operation: %s", bus_error_message(&error
, r
));
6107 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
6108 * old ways of doing things, hence don't log any error in that case here. */
6110 return r
< 0 ? r
: 0;
6113 static int reset_failed(int argc
, char *argv
[], void *userdata
) {
6114 _cleanup_strv_free_
char **names
= NULL
;
6120 return trivial_method(argc
, argv
, userdata
);
6122 r
= acquire_bus(BUS_MANAGER
, &bus
);
6126 polkit_agent_open_maybe();
6128 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
6130 return log_error_errno(r
, "Failed to expand names: %m");
6132 STRV_FOREACH(name
, names
) {
6133 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6135 q
= bus_call_method(bus
, bus_systemd_mgr
, "ResetFailedUnit", &error
, NULL
, "s", *name
);
6137 log_error_errno(q
, "Failed to reset failed state of unit %s: %s", *name
, bus_error_message(&error
, q
));
6146 static int print_variable(const char *s
) {
6148 _cleanup_free_
char *esc
= NULL
;
6150 sep
= strchr(s
, '=');
6152 return log_error_errno(SYNTHETIC_ERRNO(EUCLEAN
),
6153 "Invalid environment block");
6155 esc
= shell_maybe_quote(sep
+ 1, ESCAPE_POSIX
);
6159 printf("%.*s=%s\n", (int)(sep
-s
), s
, esc
);
6163 static int show_environment(int argc
, char *argv
[], void *userdata
) {
6164 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6165 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
6170 r
= acquire_bus(BUS_MANAGER
, &bus
);
6174 (void) pager_open(arg_pager_flags
);
6176 r
= bus_get_property(bus
, bus_systemd_mgr
, "Environment", &error
, &reply
, "as");
6178 return log_error_errno(r
, "Failed to get environment: %s", bus_error_message(&error
, r
));
6180 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "s");
6182 return bus_log_parse_error(r
);
6184 while ((r
= sd_bus_message_read_basic(reply
, SD_BUS_TYPE_STRING
, &text
)) > 0) {
6185 r
= print_variable(text
);
6190 return bus_log_parse_error(r
);
6192 r
= sd_bus_message_exit_container(reply
);
6194 return bus_log_parse_error(r
);
6199 static int switch_root(int argc
, char *argv
[], void *userdata
) {
6200 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6201 _cleanup_free_
char *cmdline_init
= NULL
;
6202 const char *root
, *init
;
6206 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
6207 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot switch root remotely.");
6209 if (argc
< 2 || argc
> 3)
6210 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Wrong number of arguments.");
6217 r
= proc_cmdline_get_key("init", 0, &cmdline_init
);
6219 log_debug_errno(r
, "Failed to parse /proc/cmdline: %m");
6221 init
= cmdline_init
;
6224 init
= empty_to_null(init
);
6226 const char *root_systemd_path
= NULL
, *root_init_path
= NULL
;
6228 root_systemd_path
= prefix_roota(root
, "/" SYSTEMD_BINARY_PATH
);
6229 root_init_path
= prefix_roota(root
, init
);
6231 /* If the passed init is actually the same as the
6232 * systemd binary, then let's suppress it. */
6233 if (files_same(root_init_path
, root_systemd_path
, 0) > 0)
6237 /* Instruct PID1 to exclude us from its killing spree applied during the transition. Otherwise we
6238 * would exit with a failure status even though the switch to the new root has succeed. */
6240 assert(saved_argv
[0]);
6241 saved_argv
[0][0] = '@';
6243 r
= acquire_bus(BUS_MANAGER
, &bus
);
6247 /* If we are slow to exit after the root switch, the new systemd instance
6248 * will send us a signal to terminate. Just ignore it and exit normally.
6249 * This way the unit does not end up as failed.
6251 r
= ignore_signals(SIGTERM
, -1);
6253 log_warning_errno(r
, "Failed to change disposition of SIGTERM to ignore: %m");
6255 log_debug("Switching root - root: %s; init: %s", root
, strna(init
));
6257 r
= bus_call_method(bus
, bus_systemd_mgr
, "SwitchRoot", &error
, NULL
, "ss", root
, init
);
6259 (void) default_signals(SIGTERM
, -1);
6261 return log_error_errno(r
, "Failed to switch root: %s", bus_error_message(&error
, r
));
6267 static int log_level(int argc
, char *argv
[], void *userdata
) {
6269 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6272 r
= acquire_bus(BUS_MANAGER
, &bus
);
6277 _cleanup_free_
char *level
= NULL
;
6279 r
= bus_get_property_string(bus
, bus_systemd_mgr
, "LogLevel", &error
, &level
);
6281 return log_error_errno(r
, "Failed to get log level: %s", bus_error_message(&error
, r
));
6288 r
= bus_set_property(bus
, bus_systemd_mgr
, "LogLevel", &error
, "s", argv
[1]);
6290 return log_error_errno(r
, "Failed to set log level: %s", bus_error_message(&error
, r
));
6296 static int log_target(int argc
, char *argv
[], void *userdata
) {
6298 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6301 r
= acquire_bus(BUS_MANAGER
, &bus
);
6306 _cleanup_free_
char *target
= NULL
;
6308 r
= bus_get_property_string(bus
, bus_systemd_mgr
, "LogTarget", &error
, &target
);
6310 return log_error_errno(r
, "Failed to get log target: %s", bus_error_message(&error
, r
));
6317 r
= bus_set_property(bus
, bus_systemd_mgr
, "LogTarget", &error
, "s", argv
[1]);
6319 return log_error_errno(r
, "Failed to set log target: %s", bus_error_message(&error
, r
));
6325 static int service_watchdogs(int argc
, char *argv
[], void *userdata
) {
6327 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6332 r
= acquire_bus(BUS_MANAGER
, &bus
);
6337 /* get ServiceWatchdogs */
6338 r
= bus_get_property_trivial(bus
, bus_systemd_mgr
, "ServiceWatchdogs", &error
, 'b', &b
);
6340 return log_error_errno(r
, "Failed to get service-watchdog state: %s", bus_error_message(&error
, r
));
6342 printf("%s\n", yes_no(!!b
));
6345 /* set ServiceWatchdogs */
6348 b
= parse_boolean(argv
[1]);
6350 return log_error_errno(b
, "Failed to parse service-watchdogs argument: %m");
6352 r
= bus_set_property(bus
, bus_systemd_mgr
, "ServiceWatchdogs", &error
, "b", b
);
6354 return log_error_errno(r
, "Failed to set service-watchdog state: %s", bus_error_message(&error
, r
));
6360 static int set_environment(int argc
, char *argv
[], void *userdata
) {
6361 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6362 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6370 r
= acquire_bus(BUS_MANAGER
, &bus
);
6374 polkit_agent_open_maybe();
6376 method
= streq(argv
[0], "set-environment")
6378 : "UnsetEnvironment";
6380 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, method
);
6382 return bus_log_create_error(r
);
6384 r
= sd_bus_message_append_strv(m
, strv_skip(argv
, 1));
6386 return bus_log_create_error(r
);
6388 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6390 return log_error_errno(r
, "Failed to set environment: %s", bus_error_message(&error
, r
));
6395 static int import_environment(int argc
, char *argv
[], void *userdata
) {
6396 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6397 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6401 r
= acquire_bus(BUS_MANAGER
, &bus
);
6405 polkit_agent_open_maybe();
6407 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "SetEnvironment");
6409 return bus_log_create_error(r
);
6412 r
= sd_bus_message_append_strv(m
, environ
);
6416 r
= sd_bus_message_open_container(m
, 'a', "s");
6418 return bus_log_create_error(r
);
6420 STRV_FOREACH(a
, strv_skip(argv
, 1)) {
6422 if (!env_name_is_valid(*a
))
6423 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Not a valid environment variable name: %s", *a
);
6425 STRV_FOREACH(b
, environ
) {
6428 eq
= startswith(*b
, *a
);
6429 if (eq
&& *eq
== '=') {
6431 r
= sd_bus_message_append(m
, "s", *b
);
6433 return bus_log_create_error(r
);
6440 r
= sd_bus_message_close_container(m
);
6443 return bus_log_create_error(r
);
6445 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6447 return log_error_errno(r
, "Failed to import environment: %s", bus_error_message(&error
, r
));
6452 static int enable_sysv_units(const char *verb
, char **args
) {
6455 #if HAVE_SYSV_COMPAT
6456 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
6459 /* Processes all SysV units, and reshuffles the array so that afterwards only the native units remain */
6461 if (arg_scope
!= UNIT_FILE_SYSTEM
)
6464 if (getenv_bool("SYSTEMCTL_SKIP_SYSV") > 0)
6467 if (!STR_IN_SET(verb
,
6473 r
= lookup_paths_init(&paths
, arg_scope
, LOOKUP_PATHS_EXCLUDE_GENERATED
, arg_root
);
6480 const char *argv
[] = {
6481 ROOTLIBEXECDIR
"/systemd-sysv-install",
6488 _cleanup_free_
char *p
= NULL
, *q
= NULL
, *l
= NULL
, *v
= NULL
;
6489 bool found_native
= false, found_sysv
;
6497 if (!endswith(name
, ".service"))
6500 if (path_is_absolute(name
))
6503 j
= unit_file_exists(arg_scope
, &paths
, name
);
6504 if (j
< 0 && !IN_SET(j
, -ELOOP
, -ERFKILL
, -EADDRNOTAVAIL
))
6505 return log_error_errno(j
, "Failed to look up unit file state: %m");
6506 found_native
= j
!= 0;
6508 /* If we have both a native unit and a SysV script, enable/disable them both (below); for is-enabled,
6509 * prefer the native unit */
6510 if (found_native
&& streq(verb
, "is-enabled"))
6513 p
= path_join(arg_root
, SYSTEM_SYSVINIT_PATH
, name
);
6517 p
[strlen(p
) - STRLEN(".service")] = 0;
6518 found_sysv
= access(p
, F_OK
) >= 0;
6524 log_info("Synchronizing state of %s with SysV service script with %s.", name
, argv
[0]);
6526 log_info("%s is not a native service, redirecting to systemd-sysv-install.", name
);
6529 if (!isempty(arg_root
)) {
6530 q
= strjoin("--root=", arg_root
);
6537 /* Let's copy the verb, since it's still pointing directly into the original argv[] array we
6538 * got passed, but safe_fork() is likely going to rewrite that for the new child */
6544 argv
[c
++] = basename(p
);
6547 l
= strv_join((char**)argv
, " ");
6552 log_info("Executing: %s", l
);
6554 j
= safe_fork("(sysv-install)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
, &pid
);
6559 execv(argv
[0], (char**) argv
);
6560 log_error_errno(errno
, "Failed to execute %s: %m", argv
[0]);
6561 _exit(EXIT_FAILURE
);
6564 j
= wait_for_terminate_and_check("sysv-install", pid
, WAIT_LOG_ABNORMAL
);
6567 if (streq(verb
, "is-enabled")) {
6568 if (j
== EXIT_SUCCESS
) {
6577 } else if (j
!= EXIT_SUCCESS
)
6578 return -EBADE
; /* We don't warn here, under the assumption the script already showed an explanation */
6583 /* Remove this entry, so that we don't try enabling it as native unit */
6586 assert(args
[f
] == name
);
6587 strv_remove(args
+ f
, name
);
6594 static int mangle_names(const char *operation
, char **original_names
, char ***mangled_names
) {
6595 char **i
, **l
, **name
;
6598 l
= i
= new(char*, strv_length(original_names
) + 1);
6602 STRV_FOREACH(name
, original_names
) {
6604 /* When enabling units qualified path names are OK,
6605 * too, hence allow them explicitly. */
6607 if (is_path(*name
)) {
6614 r
= unit_name_mangle_with_suffix(*name
, operation
,
6615 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
6620 return log_error_errno(r
, "Failed to mangle unit name: %m");
6633 static int normalize_filenames(char **names
) {
6637 STRV_FOREACH(u
, names
)
6638 if (!path_is_absolute(*u
)) {
6639 char* normalized_path
;
6641 if (!isempty(arg_root
))
6642 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6643 "Non-absolute paths are not allowed when --root is used: %s",
6646 if (!strchr(*u
,'/'))
6647 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6648 "Link argument does contain at least one directory separator: %s",
6651 r
= path_make_absolute_cwd(*u
, &normalized_path
);
6655 free_and_replace(*u
, normalized_path
);
6661 static int normalize_names(char **names
, bool warn_if_path
) {
6663 bool was_path
= false;
6665 STRV_FOREACH(u
, names
) {
6671 r
= free_and_strdup(u
, basename(*u
));
6673 return log_error_errno(r
, "Failed to normalize unit file path: %m");
6678 if (warn_if_path
&& was_path
)
6679 log_warning("Warning: Can't execute disable on the unit file path. Proceeding with the unit name.");
6684 static int unit_exists(LookupPaths
*lp
, const char *unit
) {
6685 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6686 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6687 _cleanup_free_
char *path
= NULL
;
6688 static const struct bus_properties_map property_map
[] = {
6689 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
6690 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
)},
6693 UnitStatusInfo info
= {};
6697 if (unit_name_is_valid(unit
, UNIT_NAME_TEMPLATE
))
6698 return unit_find_template_path(unit
, lp
, NULL
, NULL
);
6700 path
= unit_dbus_path_from_name(unit
);
6704 r
= acquire_bus(BUS_MANAGER
, &bus
);
6708 r
= bus_map_all_properties(bus
, "org.freedesktop.systemd1", path
, property_map
, 0, &error
, &m
, &info
);
6710 return log_error_errno(r
, "Failed to get properties: %s", bus_error_message(&error
, r
));
6712 return !streq_ptr(info
.load_state
, "not-found") || !streq_ptr(info
.active_state
, "inactive");
6715 static int enable_unit(int argc
, char *argv
[], void *userdata
) {
6716 _cleanup_strv_free_
char **names
= NULL
;
6717 const char *verb
= argv
[0];
6718 UnitFileChange
*changes
= NULL
;
6719 size_t n_changes
= 0;
6720 int carries_install_info
= -1;
6721 bool ignore_carries_install_info
= arg_quiet
;
6727 r
= mangle_names("to enable", strv_skip(argv
, 1), &names
);
6731 r
= enable_sysv_units(verb
, names
);
6735 /* If the operation was fully executed by the SysV compat, let's finish early */
6736 if (strv_isempty(names
)) {
6737 if (arg_no_reload
|| install_client_side())
6739 return daemon_reload(argc
, argv
, userdata
);
6742 if (streq(verb
, "disable")) {
6743 r
= normalize_names(names
, true);
6748 if (streq(verb
, "link")) {
6749 r
= normalize_filenames(names
);
6754 if (install_client_side()) {
6755 UnitFileFlags flags
;
6757 flags
= args_to_flags();
6758 if (streq(verb
, "enable")) {
6759 r
= unit_file_enable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6760 carries_install_info
= r
;
6761 } else if (streq(verb
, "disable"))
6762 r
= unit_file_disable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6763 else if (streq(verb
, "reenable")) {
6764 r
= unit_file_reenable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6765 carries_install_info
= r
;
6766 } else if (streq(verb
, "link"))
6767 r
= unit_file_link(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6768 else if (streq(verb
, "preset")) {
6769 r
= unit_file_preset(arg_scope
, flags
, arg_root
, names
, arg_preset_mode
, &changes
, &n_changes
);
6770 } else if (streq(verb
, "mask"))
6771 r
= unit_file_mask(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6772 else if (streq(verb
, "unmask"))
6773 r
= unit_file_unmask(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6774 else if (streq(verb
, "revert"))
6775 r
= unit_file_revert(arg_scope
, arg_root
, names
, &changes
, &n_changes
);
6777 assert_not_reached("Unknown verb");
6779 unit_file_dump_changes(r
, verb
, changes
, n_changes
, arg_quiet
);
6784 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
, *m
= NULL
;
6785 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6786 bool expect_carries_install_info
= false;
6787 bool send_runtime
= true, send_force
= true, send_preset_mode
= false;
6791 if (STR_IN_SET(verb
, "mask", "unmask")) {
6793 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
6795 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
6799 STRV_FOREACH(name
, names
) {
6800 r
= unit_exists(&lp
, *name
);
6804 log_notice("Unit %s does not exist, proceeding anyway.", *name
);
6808 r
= acquire_bus(BUS_MANAGER
, &bus
);
6812 polkit_agent_open_maybe();
6814 if (streq(verb
, "enable")) {
6815 method
= "EnableUnitFiles";
6816 expect_carries_install_info
= true;
6817 } else if (streq(verb
, "disable")) {
6818 method
= "DisableUnitFiles";
6820 } else if (streq(verb
, "reenable")) {
6821 method
= "ReenableUnitFiles";
6822 expect_carries_install_info
= true;
6823 } else if (streq(verb
, "link"))
6824 method
= "LinkUnitFiles";
6825 else if (streq(verb
, "preset")) {
6827 if (arg_preset_mode
!= UNIT_FILE_PRESET_FULL
) {
6828 method
= "PresetUnitFilesWithMode";
6829 send_preset_mode
= true;
6831 method
= "PresetUnitFiles";
6833 expect_carries_install_info
= true;
6834 ignore_carries_install_info
= true;
6835 } else if (streq(verb
, "mask"))
6836 method
= "MaskUnitFiles";
6837 else if (streq(verb
, "unmask")) {
6838 method
= "UnmaskUnitFiles";
6840 } else if (streq(verb
, "revert")) {
6841 method
= "RevertUnitFiles";
6842 send_runtime
= send_force
= false;
6844 assert_not_reached("Unknown verb");
6846 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, method
);
6848 return bus_log_create_error(r
);
6850 r
= sd_bus_message_append_strv(m
, names
);
6852 return bus_log_create_error(r
);
6854 if (send_preset_mode
) {
6855 r
= sd_bus_message_append(m
, "s", unit_file_preset_mode_to_string(arg_preset_mode
));
6857 return bus_log_create_error(r
);
6861 r
= sd_bus_message_append(m
, "b", arg_runtime
);
6863 return bus_log_create_error(r
);
6867 r
= sd_bus_message_append(m
, "b", arg_force
);
6869 return bus_log_create_error(r
);
6872 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
6874 return log_error_errno(r
, "Failed to %s unit: %s", verb
, bus_error_message(&error
, r
));
6876 if (expect_carries_install_info
) {
6877 r
= sd_bus_message_read(reply
, "b", &carries_install_info
);
6879 return bus_log_parse_error(r
);
6882 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
6886 /* Try to reload if enabled */
6888 r
= daemon_reload(argc
, argv
, userdata
);
6893 if (carries_install_info
== 0 && !ignore_carries_install_info
)
6894 log_notice("The unit files have no installation config (WantedBy=, RequiredBy=, Also=,\n"
6895 "Alias= settings in the [Install] section, and DefaultInstance= for template\n"
6896 "units). This means they are not meant to be enabled using systemctl.\n"
6897 " \n" /* trick: the space is needed so that the line does not get stripped from output */
6898 "Possible reasons for having this kind of units are:\n"
6899 "%1$s A unit may be statically enabled by being symlinked from another unit's\n"
6900 " .wants/ or .requires/ directory.\n"
6901 "%1$s A unit's purpose may be to act as a helper for some other unit which has\n"
6902 " a requirement dependency on it.\n"
6903 "%1$s A unit may be started when needed via activation (socket, path, timer,\n"
6904 " D-Bus, udev, scripted systemctl call, ...).\n"
6905 "%1$s In case of template units, the unit is meant to be enabled with some\n"
6906 " instance name specified.",
6907 special_glyph(SPECIAL_GLYPH_BULLET
));
6909 if (arg_now
&& STR_IN_SET(argv
[0], "enable", "disable", "mask")) {
6913 r
= acquire_bus(BUS_MANAGER
, &bus
);
6917 len
= strv_length(names
);
6919 char *new_args
[len
+ 2];
6921 new_args
[0] = (char*) (streq(argv
[0], "enable") ? "start" : "stop");
6922 for (i
= 0; i
< len
; i
++)
6923 new_args
[i
+ 1] = basename(names
[i
]);
6924 new_args
[i
+ 1] = NULL
;
6926 r
= start_unit(len
+ 1, new_args
, userdata
);
6931 unit_file_changes_free(changes
, n_changes
);
6936 static int add_dependency(int argc
, char *argv
[], void *userdata
) {
6937 _cleanup_strv_free_
char **names
= NULL
;
6938 _cleanup_free_
char *target
= NULL
;
6939 const char *verb
= argv
[0];
6940 UnitFileChange
*changes
= NULL
;
6941 size_t n_changes
= 0;
6948 r
= unit_name_mangle_with_suffix(argv
[1], "as target",
6949 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
6950 ".target", &target
);
6952 return log_error_errno(r
, "Failed to mangle unit name: %m");
6954 r
= mangle_names("as dependency", strv_skip(argv
, 2), &names
);
6958 if (streq(verb
, "add-wants"))
6960 else if (streq(verb
, "add-requires"))
6961 dep
= UNIT_REQUIRES
;
6963 assert_not_reached("Unknown verb");
6965 if (install_client_side()) {
6966 r
= unit_file_add_dependency(arg_scope
, args_to_flags(), arg_root
, names
, target
, dep
, &changes
, &n_changes
);
6967 unit_file_dump_changes(r
, "add dependency on", changes
, n_changes
, arg_quiet
);
6972 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
, *m
= NULL
;
6973 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6976 r
= acquire_bus(BUS_MANAGER
, &bus
);
6980 polkit_agent_open_maybe();
6982 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "AddDependencyUnitFiles");
6984 return bus_log_create_error(r
);
6986 r
= sd_bus_message_append_strv(m
, names
);
6988 return bus_log_create_error(r
);
6990 r
= sd_bus_message_append(m
, "ssbb", target
, unit_dependency_to_string(dep
), arg_runtime
, arg_force
);
6992 return bus_log_create_error(r
);
6994 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
6996 return log_error_errno(r
, "Failed to add dependency: %s", bus_error_message(&error
, r
));
6998 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
7002 if (arg_no_reload
) {
7007 r
= daemon_reload(argc
, argv
, userdata
);
7011 unit_file_changes_free(changes
, n_changes
);
7016 static int preset_all(int argc
, char *argv
[], void *userdata
) {
7017 UnitFileChange
*changes
= NULL
;
7018 size_t n_changes
= 0;
7021 if (install_client_side()) {
7022 r
= unit_file_preset_all(arg_scope
, args_to_flags(), arg_root
, arg_preset_mode
, &changes
, &n_changes
);
7023 unit_file_dump_changes(r
, "preset", changes
, n_changes
, arg_quiet
);
7028 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7029 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7032 r
= acquire_bus(BUS_MANAGER
, &bus
);
7036 polkit_agent_open_maybe();
7038 r
= bus_call_method(
7041 "PresetAllUnitFiles",
7045 unit_file_preset_mode_to_string(arg_preset_mode
),
7049 return log_error_errno(r
, "Failed to preset all units: %s", bus_error_message(&error
, r
));
7051 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
7055 if (arg_no_reload
) {
7060 r
= daemon_reload(argc
, argv
, userdata
);
7064 unit_file_changes_free(changes
, n_changes
);
7069 static int show_installation_targets_client_side(const char *name
) {
7070 UnitFileChange
*changes
= NULL
;
7071 size_t n_changes
= 0, i
;
7072 UnitFileFlags flags
;
7076 p
= STRV_MAKE(name
);
7077 flags
= UNIT_FILE_DRY_RUN
|
7078 (arg_runtime
? UNIT_FILE_RUNTIME
: 0);
7080 r
= unit_file_disable(UNIT_FILE_SYSTEM
, flags
, NULL
, p
, &changes
, &n_changes
);
7082 return log_error_errno(r
, "Failed to get file links for %s: %m", name
);
7084 for (i
= 0; i
< n_changes
; i
++)
7085 if (changes
[i
].type
== UNIT_FILE_UNLINK
)
7086 printf(" %s\n", changes
[i
].path
);
7091 static int show_installation_targets(sd_bus
*bus
, const char *name
) {
7092 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7093 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7097 r
= bus_call_method(bus
, bus_systemd_mgr
, "GetUnitFileLinks", &error
, &reply
, "sb", name
, arg_runtime
);
7099 return log_error_errno(r
, "Failed to get unit file links for %s: %s", name
, bus_error_message(&error
, r
));
7101 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "s");
7103 return bus_log_parse_error(r
);
7105 while ((r
= sd_bus_message_read(reply
, "s", &link
)) > 0)
7106 printf(" %s\n", link
);
7109 return bus_log_parse_error(r
);
7111 r
= sd_bus_message_exit_container(reply
);
7113 return bus_log_parse_error(r
);
7118 static int unit_is_enabled(int argc
, char *argv
[], void *userdata
) {
7119 _cleanup_strv_free_
char **names
= NULL
;
7124 r
= mangle_names("to check", strv_skip(argv
, 1), &names
);
7128 r
= enable_sysv_units(argv
[0], names
);
7134 if (install_client_side()) {
7135 STRV_FOREACH(name
, names
) {
7136 UnitFileState state
;
7138 r
= unit_file_get_state(arg_scope
, arg_root
, *name
, &state
);
7140 return log_error_errno(r
, "Failed to get unit file state for %s: %m", *name
);
7144 UNIT_FILE_ENABLED_RUNTIME
,
7148 UNIT_FILE_GENERATED
))
7152 puts(unit_file_state_to_string(state
));
7154 r
= show_installation_targets_client_side(*name
);
7163 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7166 r
= acquire_bus(BUS_MANAGER
, &bus
);
7170 STRV_FOREACH(name
, names
) {
7171 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7174 r
= bus_call_method(bus
, bus_systemd_mgr
, "GetUnitFileState", &error
, &reply
, "s", *name
);
7176 return log_error_errno(r
, "Failed to get unit file state for %s: %s", *name
, bus_error_message(&error
, r
));
7178 r
= sd_bus_message_read(reply
, "s", &s
);
7180 return bus_log_parse_error(r
);
7182 if (STR_IN_SET(s
, "enabled", "enabled-runtime", "static", "indirect", "generated"))
7188 r
= show_installation_targets(bus
, *name
);
7196 return enabled
? EXIT_SUCCESS
: EXIT_FAILURE
;
7199 static int match_startup_finished(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
7200 char **state
= userdata
;
7205 r
= bus_get_property_string(sd_bus_message_get_bus(m
), bus_systemd_mgr
, "SystemState", NULL
, state
);
7207 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m
)), r
);
7211 static int is_system_running(int argc
, char *argv
[], void *userdata
) {
7212 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7213 _cleanup_(sd_bus_slot_unrefp
) sd_bus_slot
*slot_startup_finished
= NULL
;
7214 _cleanup_(sd_event_unrefp
) sd_event
* event
= NULL
;
7215 _cleanup_free_
char *state
= NULL
;
7219 if (running_in_chroot() > 0 || (arg_transport
== BUS_TRANSPORT_LOCAL
&& !sd_booted())) {
7222 return EXIT_FAILURE
;
7225 r
= acquire_bus(BUS_MANAGER
, &bus
);
7230 r
= sd_event_default(&event
);
7232 r
= sd_bus_attach_event(bus
, event
, 0);
7234 r
= bus_match_signal_async(
7236 &slot_startup_finished
,
7239 match_startup_finished
, NULL
, &state
);
7241 log_warning_errno(r
, "Failed to request match for StartupFinished: %m");
7246 r
= bus_get_property_string(bus
, bus_systemd_mgr
, "SystemState", &error
, &state
);
7248 log_warning_errno(r
, "Failed to query system state: %s", bus_error_message(&error
, r
));
7252 return EXIT_FAILURE
;
7255 if (arg_wait
&& STR_IN_SET(state
, "initializing", "starting")) {
7256 r
= sd_event_loop(event
);
7258 log_warning_errno(r
, "Failed to get property from event loop: %m");
7261 return EXIT_FAILURE
;
7268 return streq(state
, "running") ? EXIT_SUCCESS
: EXIT_FAILURE
;
7271 static int create_edit_temp_file(const char *new_path
, const char *original_path
, char **ret_tmp_fn
) {
7272 _cleanup_free_
char *t
= NULL
;
7276 assert(original_path
);
7279 r
= tempfn_random(new_path
, NULL
, &t
);
7281 return log_error_errno(r
, "Failed to determine temporary filename for \"%s\": %m", new_path
);
7283 r
= mkdir_parents(new_path
, 0755);
7285 return log_error_errno(r
, "Failed to create directories for \"%s\": %m", new_path
);
7287 r
= copy_file(original_path
, t
, 0, 0644, 0, 0, COPY_REFLINK
);
7292 return log_error_errno(r
, "Failed to create temporary file \"%s\": %m", t
);
7295 return log_error_errno(r
, "Failed to create temporary file for \"%s\": %m", new_path
);
7297 *ret_tmp_fn
= TAKE_PTR(t
);
7302 static int get_file_to_edit(
7303 const LookupPaths
*paths
,
7307 _cleanup_free_
char *path
= NULL
, *run
= NULL
;
7312 path
= path_join(paths
->persistent_config
, name
);
7317 run
= path_join(paths
->runtime_config
, name
);
7323 if (access(path
, F_OK
) >= 0)
7324 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
7325 "Refusing to create \"%s\" because it would be overridden by \"%s\" anyway.",
7328 *ret_path
= TAKE_PTR(run
);
7330 *ret_path
= TAKE_PTR(path
);
7335 static int unit_file_create_new(
7336 const LookupPaths
*paths
,
7337 const char *unit_name
,
7339 char **ret_new_path
,
7340 char **ret_tmp_path
) {
7342 _cleanup_free_
char *new_path
= NULL
, *tmp_path
= NULL
;
7347 assert(ret_new_path
);
7348 assert(ret_tmp_path
);
7350 ending
= strjoina(unit_name
, suffix
);
7351 r
= get_file_to_edit(paths
, ending
, &new_path
);
7355 r
= create_edit_temp_file(new_path
, new_path
, &tmp_path
);
7359 *ret_new_path
= TAKE_PTR(new_path
);
7360 *ret_tmp_path
= TAKE_PTR(tmp_path
);
7365 static int unit_file_create_copy(
7366 const LookupPaths
*paths
,
7367 const char *unit_name
,
7368 const char *fragment_path
,
7369 char **ret_new_path
,
7370 char **ret_tmp_path
) {
7372 _cleanup_free_
char *new_path
= NULL
, *tmp_path
= NULL
;
7375 assert(fragment_path
);
7377 assert(ret_new_path
);
7378 assert(ret_tmp_path
);
7380 r
= get_file_to_edit(paths
, unit_name
, &new_path
);
7384 if (!path_equal(fragment_path
, new_path
) && access(new_path
, F_OK
) >= 0) {
7387 r
= ask_char(&response
, "yn", "\"%s\" already exists. Overwrite with \"%s\"? [(y)es, (n)o] ", new_path
, fragment_path
);
7390 if (response
!= 'y')
7391 return log_warning_errno(SYNTHETIC_ERRNO(EKEYREJECTED
), "%s skipped.", unit_name
);
7394 r
= create_edit_temp_file(new_path
, fragment_path
, &tmp_path
);
7398 *ret_new_path
= TAKE_PTR(new_path
);
7399 *ret_tmp_path
= TAKE_PTR(tmp_path
);
7404 static int run_editor(char **paths
) {
7409 r
= safe_fork("(editor)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
|FORK_WAIT
, NULL
);
7413 char **editor_args
= NULL
, **tmp_path
, **original_path
;
7414 size_t n_editor_args
= 0, i
= 1, argc
;
7415 const char **args
, *editor
, *p
;
7417 argc
= strv_length(paths
)/2 + 1;
7419 /* SYSTEMD_EDITOR takes precedence over EDITOR which takes precedence over VISUAL
7420 * If neither SYSTEMD_EDITOR nor EDITOR nor VISUAL are present,
7421 * we try to execute well known editors
7423 editor
= getenv("SYSTEMD_EDITOR");
7425 editor
= getenv("EDITOR");
7427 editor
= getenv("VISUAL");
7429 if (!isempty(editor
)) {
7430 editor_args
= strv_split(editor
, WHITESPACE
);
7433 _exit(EXIT_FAILURE
);
7435 n_editor_args
= strv_length(editor_args
);
7436 argc
+= n_editor_args
- 1;
7439 args
= newa(const char*, argc
+ 1);
7441 if (n_editor_args
> 0) {
7442 args
[0] = editor_args
[0];
7443 for (; i
< n_editor_args
; i
++)
7444 args
[i
] = editor_args
[i
];
7447 STRV_FOREACH_PAIR(original_path
, tmp_path
, paths
)
7448 args
[i
++] = *tmp_path
;
7451 if (n_editor_args
> 0)
7452 execvp(args
[0], (char* const*) args
);
7454 FOREACH_STRING(p
, "editor", "nano", "vim", "vi") {
7456 execvp(p
, (char* const*) args
);
7457 /* We do not fail if the editor doesn't exist
7458 * because we want to try each one of them before
7461 if (errno
!= ENOENT
) {
7462 log_error_errno(errno
, "Failed to execute %s: %m", editor
);
7463 _exit(EXIT_FAILURE
);
7467 log_error("Cannot edit unit(s), no editor available. Please set either $SYSTEMD_EDITOR, $EDITOR or $VISUAL.");
7468 _exit(EXIT_FAILURE
);
7474 static int find_paths_to_edit(sd_bus
*bus
, char **names
, char ***paths
) {
7475 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
7482 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
7486 STRV_FOREACH(name
, names
) {
7487 _cleanup_free_
char *path
= NULL
, *new_path
= NULL
, *tmp_path
= NULL
, *tmp_name
= NULL
;
7488 const char *unit_name
;
7490 r
= unit_find_paths(bus
, *name
, &lp
, false, &path
, NULL
);
7491 if (r
== -EKEYREJECTED
) {
7492 /* If loading of the unit failed server side complete, then the server won't tell us the unit
7493 * file path. In that case, find the file client side. */
7494 log_debug_errno(r
, "Unit '%s' was not loaded correctly, retrying client-side.", *name
);
7495 r
= unit_find_paths(bus
, *name
, &lp
, true, &path
, NULL
);
7498 return log_error_errno(r
, "Unit '%s' masked, cannot edit.", *name
);
7506 log_info("Run 'systemctl edit%s --force --full %s' to create a new unit.",
7507 arg_scope
== UNIT_FILE_GLOBAL
? " --global" :
7508 arg_scope
== UNIT_FILE_USER
? " --user" : "",
7513 /* Create a new unit from scratch */
7515 r
= unit_file_create_new(&lp
, unit_name
,
7516 arg_full
? NULL
: ".d/override.conf",
7517 &new_path
, &tmp_path
);
7521 unit_name
= basename(path
);
7522 /* We follow unit aliases, but we need to propagate the instance */
7523 if (unit_name_is_valid(*name
, UNIT_NAME_INSTANCE
) &&
7524 unit_name_is_valid(unit_name
, UNIT_NAME_TEMPLATE
)) {
7525 _cleanup_free_
char *instance
= NULL
;
7527 r
= unit_name_to_instance(*name
, &instance
);
7531 r
= unit_name_replace_instance(unit_name
, instance
, &tmp_name
);
7535 unit_name
= tmp_name
;
7539 r
= unit_file_create_copy(&lp
, unit_name
, path
, &new_path
, &tmp_path
);
7541 r
= unit_file_create_new(&lp
, unit_name
, ".d/override.conf", &new_path
, &tmp_path
);
7546 r
= strv_push_pair(paths
, new_path
, tmp_path
);
7550 new_path
= tmp_path
= NULL
;
7556 static int edit(int argc
, char *argv
[], void *userdata
) {
7557 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
7558 _cleanup_strv_free_
char **names
= NULL
;
7559 _cleanup_strv_free_
char **paths
= NULL
;
7560 char **original
, **tmp
;
7565 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit units if not on a tty.");
7567 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
7568 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit units remotely.");
7570 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
7572 return log_error_errno(r
, "Failed to determine unit paths: %m");
7574 r
= acquire_bus(BUS_MANAGER
, &bus
);
7578 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
7580 return log_error_errno(r
, "Failed to expand names: %m");
7582 STRV_FOREACH(tmp
, names
) {
7583 r
= unit_is_masked(bus
, &lp
, *tmp
);
7587 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit %s: unit is masked.", *tmp
);
7590 r
= find_paths_to_edit(bus
, names
, &paths
);
7594 if (strv_isempty(paths
))
7597 r
= run_editor(paths
);
7601 STRV_FOREACH_PAIR(original
, tmp
, paths
) {
7602 /* If the temporary file is empty we ignore it.
7603 * This allows the user to cancel the modification.
7605 if (null_or_empty_path(*tmp
)) {
7606 log_warning("Editing \"%s\" canceled: temporary file is empty.", *original
);
7610 r
= rename(*tmp
, *original
);
7612 r
= log_error_errno(errno
, "Failed to rename \"%s\" to \"%s\": %m", *tmp
, *original
);
7619 if (!arg_no_reload
&& !install_client_side())
7620 r
= daemon_reload(argc
, argv
, userdata
);
7623 STRV_FOREACH_PAIR(original
, tmp
, paths
) {
7624 (void) unlink(*tmp
);
7626 /* Removing empty dropin dirs */
7628 _cleanup_free_
char *dir
;
7630 dir
= dirname_malloc(*original
);
7634 /* no need to check if the dir is empty, rmdir
7635 * does nothing if it is not the case.
7644 static int systemctl_help(void) {
7645 _cleanup_free_
char *link
= NULL
;
7648 (void) pager_open(arg_pager_flags
);
7650 r
= terminal_urlify_man("systemctl", "1", &link
);
7654 printf("%1$s [OPTIONS...] COMMAND ...\n\n"
7655 "%5$sQuery or send control commands to the system manager.%6$s\n"
7656 "\n%3$sUnit Commands:%4$s\n"
7657 " list-units [PATTERN...] List units currently in memory\n"
7658 " list-sockets [PATTERN...] List socket units currently in memory,\n"
7659 " ordered by address\n"
7660 " list-timers [PATTERN...] List timer units currently in memory,\n"
7661 " ordered by next elapse\n"
7662 " start UNIT... Start (activate) one or more units\n"
7663 " stop UNIT... Stop (deactivate) one or more units\n"
7664 " reload UNIT... Reload one or more units\n"
7665 " restart UNIT... Start or restart one or more units\n"
7666 " try-restart UNIT... Restart one or more units if active\n"
7667 " reload-or-restart UNIT... Reload one or more units if possible,\n"
7668 " otherwise start or restart\n"
7669 " try-reload-or-restart UNIT... If active, reload one or more units,\n"
7670 " if supported, otherwise restart\n"
7671 " isolate UNIT Start one unit and stop all others\n"
7672 " kill UNIT... Send signal to processes of a unit\n"
7673 " clean UNIT... Clean runtime, cache, state, logs or\n"
7674 " configuration of unit\n"
7675 " freeze PATTERN... Freeze execution of unit processes\n"
7676 " thaw PATTERN... Resume execution of a frozen unit\n"
7677 " is-active PATTERN... Check whether units are active\n"
7678 " is-failed PATTERN... Check whether units are failed\n"
7679 " status [PATTERN...|PID...] Show runtime status of one or more units\n"
7680 " show [PATTERN...|JOB...] Show properties of one or more\n"
7681 " units/jobs or the manager\n"
7682 " cat PATTERN... Show files and drop-ins of specified units\n"
7683 " set-property UNIT PROPERTY=VALUE... Sets one or more properties of a unit\n"
7684 " help PATTERN...|PID... Show manual for one or more units\n"
7685 " reset-failed [PATTERN...] Reset failed state for all, one, or more\n"
7687 " list-dependencies [UNIT...] Recursively show units which are required\n"
7688 " or wanted by the units or by which those\n"
7689 " units are required or wanted"
7690 "\n%3$sUnit File Commands:%4$s\n"
7691 " list-unit-files [PATTERN...] List installed unit files\n"
7692 " enable [UNIT...|PATH...] Enable one or more unit files\n"
7693 " disable UNIT... Disable one or more unit files\n"
7694 " reenable UNIT... Reenable one or more unit files\n"
7695 " preset UNIT... Enable/disable one or more unit files\n"
7696 " based on preset configuration\n"
7697 " preset-all Enable/disable all unit files based on\n"
7698 " preset configuration\n"
7699 " is-enabled UNIT... Check whether unit files are enabled\n"
7700 " mask UNIT... Mask one or more units\n"
7701 " unmask UNIT... Unmask one or more units\n"
7702 " link PATH... Link one or more units files into\n"
7703 " the search path\n"
7704 " revert UNIT... Revert one or more unit files to vendor\n"
7706 " add-wants TARGET UNIT... Add 'Wants' dependency for the target\n"
7707 " on specified one or more units\n"
7708 " add-requires TARGET UNIT... Add 'Requires' dependency for the target\n"
7709 " on specified one or more units\n"
7710 " edit UNIT... Edit one or more unit files\n"
7711 " get-default Get the name of the default target\n"
7712 " set-default TARGET Set the default target\n"
7713 "\n%3$sMachine Commands:%4$s\n"
7714 " list-machines [PATTERN...] List local containers and host\n"
7715 "\n%3$sJob Commands:%4$s\n"
7716 " list-jobs [PATTERN...] List jobs\n"
7717 " cancel [JOB...] Cancel all, one, or more jobs\n"
7718 "\n%3$sEnvironment Commands:%4$s\n"
7719 " show-environment Dump environment\n"
7720 " set-environment VARIABLE=VALUE... Set one or more environment variables\n"
7721 " unset-environment VARIABLE... Unset one or more environment variables\n"
7722 " import-environment [VARIABLE...] Import all or some environment variables\n"
7723 "\n%3$sManager State Commands:%4$s\n"
7724 " daemon-reload Reload systemd manager configuration\n"
7725 " daemon-reexec Reexecute systemd manager\n"
7726 " log-level [LEVEL] Get/set logging threshold for manager\n"
7727 " log-target [TARGET] Get/set logging target for manager\n"
7728 " service-watchdogs [BOOL] Get/set service watchdog state\n"
7729 "\n%3$sSystem Commands:%4$s\n"
7730 " is-system-running Check whether system is fully running\n"
7731 " default Enter system default mode\n"
7732 " rescue Enter system rescue mode\n"
7733 " emergency Enter system emergency mode\n"
7734 " halt Shut down and halt the system\n"
7735 " poweroff Shut down and power-off the system\n"
7736 " reboot Shut down and reboot the system\n"
7737 " kexec Shut down and reboot the system with kexec\n"
7738 " exit [EXIT_CODE] Request user instance or container exit\n"
7739 " switch-root ROOT [INIT] Change to a different root file system\n"
7740 " suspend Suspend the system\n"
7741 " hibernate Hibernate the system\n"
7742 " hybrid-sleep Hibernate and suspend the system\n"
7743 " suspend-then-hibernate Suspend the system, wake after a period of\n"
7744 " time, and hibernate"
7745 "\n%3$sOptions:%4$s\n"
7746 " -h --help Show this help\n"
7747 " --version Show package version\n"
7748 " --system Connect to system manager\n"
7749 " --user Connect to user service manager\n"
7750 " -H --host=[USER@]HOST Operate on remote host\n"
7751 " -M --machine=CONTAINER Operate on a local container\n"
7752 " -t --type=TYPE List units of a particular type\n"
7753 " --state=STATE List units with particular LOAD or SUB or ACTIVE state\n"
7754 " --failed Shortcut for --state=failed\n"
7755 " -p --property=NAME Show only properties by this name\n"
7756 " -P NAME Equivalent to --value --property=NAME\n"
7757 " -a --all Show all properties/all units currently in memory,\n"
7758 " including dead/empty ones. To list all units installed\n"
7759 " on the system, use 'list-unit-files' instead.\n"
7760 " -l --full Don't ellipsize unit names on output\n"
7761 " -r --recursive Show unit list of host and local containers\n"
7762 " --reverse Show reverse dependencies with 'list-dependencies'\n"
7763 " --with-dependencies Show unit dependencies with 'status', 'cat',\n"
7764 " 'list-units', and 'list-unit-files'.\n"
7765 " --job-mode=MODE Specify how to deal with already queued jobs, when\n"
7766 " queueing a new job\n"
7767 " -T --show-transaction When enqueuing a unit job, show full transaction\n"
7768 " --show-types When showing sockets, explicitly show their type\n"
7769 " --value When showing properties, only print the value\n"
7770 " -i --ignore-inhibitors When shutting down or sleeping, ignore inhibitors\n"
7771 " --kill-who=WHO Whom to send signal to\n"
7772 " -s --signal=SIGNAL Which signal to send\n"
7773 " --what=RESOURCES Which types of resources to remove\n"
7774 " --now Start or stop unit after enabling or disabling it\n"
7775 " --dry-run Only print what would be done\n"
7776 " Currently supported by verbs: halt, poweroff, reboot,\n"
7777 " kexec, suspend, hibernate, suspend-then-hibernate,\n"
7778 " hybrid-sleep, default, rescue, emergency, and exit.\n"
7779 " -q --quiet Suppress output\n"
7780 " --wait For (re)start, wait until service stopped again\n"
7781 " For is-system-running, wait until startup is completed\n"
7782 " --no-block Do not wait until operation finished\n"
7783 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7784 " --no-reload Don't reload daemon after en-/dis-abling unit files\n"
7785 " --no-legend Do not print a legend (column headers and hints)\n"
7786 " --no-pager Do not pipe output into a pager\n"
7787 " --no-ask-password Do not ask for system passwords\n"
7788 " --global Enable/disable/mask unit files globally\n"
7789 " --runtime Enable/disable/mask unit files temporarily until next\n"
7791 " -f --force When enabling unit files, override existing symlinks\n"
7792 " When shutting down, execute action immediately\n"
7793 " --preset-mode= Apply only enable, only disable, or all presets\n"
7794 " --root=PATH Enable/disable/mask unit files in the specified root\n"
7796 " -n --lines=INTEGER Number of journal entries to show\n"
7797 " -o --output=STRING Change journal output mode (short, short-precise,\n"
7798 " short-iso, short-iso-precise, short-full,\n"
7799 " short-monotonic, short-unix,\n"
7800 " verbose, export, json, json-pretty, json-sse, cat)\n"
7801 " --firmware-setup Tell the firmware to show the setup menu on next boot\n"
7802 " --boot-loader-menu=TIME\n"
7803 " Boot into boot loader menu on next boot\n"
7804 " --boot-loader-entry=NAME\n"
7805 " Boot into a specific boot loader entry on next boot\n"
7806 " --plain Print unit dependencies as a list instead of a tree\n"
7807 "\nSee the %2$s for details.\n"
7808 , program_invocation_short_name
7810 , ansi_underline(), ansi_normal()
7811 , ansi_highlight(), ansi_normal()
7817 static int halt_help(void) {
7818 _cleanup_free_
char *link
= NULL
;
7821 r
= terminal_urlify_man("halt", "8", &link
);
7825 printf("%s [OPTIONS...]%s\n"
7826 "\n%s%s the system.%s\n"
7828 " --help Show this help\n"
7829 " --halt Halt the machine\n"
7830 " -p --poweroff Switch off the machine\n"
7831 " --reboot Reboot the machine\n"
7832 " -f --force Force immediate halt/power-off/reboot\n"
7833 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
7834 " -d --no-wtmp Don't write wtmp record\n"
7835 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7836 "\nSee the %s for details.\n"
7837 , program_invocation_short_name
7838 , arg_action
== ACTION_REBOOT
? " [ARG]" : ""
7840 , arg_action
== ACTION_REBOOT
? "Reboot" :
7841 arg_action
== ACTION_POWEROFF
? "Power off" :
7850 static int shutdown_help(void) {
7851 _cleanup_free_
char *link
= NULL
;
7854 r
= terminal_urlify_man("shutdown", "8", &link
);
7858 printf("%s [OPTIONS...] [TIME] [WALL...]\n"
7859 "\n%sShut down the system.%s\n"
7861 " --help Show this help\n"
7862 " -H --halt Halt the machine\n"
7863 " -P --poweroff Power-off the machine\n"
7864 " -r --reboot Reboot the machine\n"
7865 " -h Equivalent to --poweroff, overridden by --halt\n"
7866 " -k Don't halt/power-off/reboot, just send warnings\n"
7867 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7868 " -c Cancel a pending shutdown\n"
7869 "\nSee the %s for details.\n"
7870 , program_invocation_short_name
7871 , ansi_highlight(), ansi_normal()
7878 static int telinit_help(void) {
7879 _cleanup_free_
char *link
= NULL
;
7882 r
= terminal_urlify_man("telinit", "8", &link
);
7886 printf("%s [OPTIONS...] COMMAND\n\n"
7887 "%sSend control commands to the init daemon.%s\n"
7889 " 0 Power-off the machine\n"
7890 " 6 Reboot the machine\n"
7891 " 2, 3, 4, 5 Start runlevelX.target unit\n"
7892 " 1, s, S Enter rescue mode\n"
7893 " q, Q Reload init daemon configuration\n"
7894 " u, U Reexecute init daemon\n"
7896 " --help Show this help\n"
7897 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7898 "\nSee the %s for details.\n"
7899 , program_invocation_short_name
7900 , ansi_highlight(), ansi_normal()
7907 static int runlevel_help(void) {
7908 _cleanup_free_
char *link
= NULL
;
7911 r
= terminal_urlify_man("runlevel", "8", &link
);
7915 printf("%s [OPTIONS...]\n"
7916 "\n%sPrints the previous and current runlevel of the init system.%s\n"
7918 " --help Show this help\n"
7919 "\nSee the %s for details.\n"
7920 , program_invocation_short_name
7921 , ansi_highlight(), ansi_normal()
7928 static void help_types(void) {
7930 puts("Available unit types:");
7932 DUMP_STRING_TABLE(unit_type
, UnitType
, _UNIT_TYPE_MAX
);
7935 static void help_states(void) {
7937 puts("Available unit load states:");
7938 DUMP_STRING_TABLE(unit_load_state
, UnitLoadState
, _UNIT_LOAD_STATE_MAX
);
7941 puts("\nAvailable unit active states:");
7942 DUMP_STRING_TABLE(unit_active_state
, UnitActiveState
, _UNIT_ACTIVE_STATE_MAX
);
7945 puts("\nAvailable unit file states:");
7946 DUMP_STRING_TABLE(unit_file_state
, UnitFileState
, _UNIT_FILE_STATE_MAX
);
7949 puts("\nAvailable automount unit substates:");
7950 DUMP_STRING_TABLE(automount_state
, AutomountState
, _AUTOMOUNT_STATE_MAX
);
7953 puts("\nAvailable device unit substates:");
7954 DUMP_STRING_TABLE(device_state
, DeviceState
, _DEVICE_STATE_MAX
);
7957 puts("\nAvailable mount unit substates:");
7958 DUMP_STRING_TABLE(mount_state
, MountState
, _MOUNT_STATE_MAX
);
7961 puts("\nAvailable path unit substates:");
7962 DUMP_STRING_TABLE(path_state
, PathState
, _PATH_STATE_MAX
);
7965 puts("\nAvailable scope unit substates:");
7966 DUMP_STRING_TABLE(scope_state
, ScopeState
, _SCOPE_STATE_MAX
);
7969 puts("\nAvailable service unit substates:");
7970 DUMP_STRING_TABLE(service_state
, ServiceState
, _SERVICE_STATE_MAX
);
7973 puts("\nAvailable slice unit substates:");
7974 DUMP_STRING_TABLE(slice_state
, SliceState
, _SLICE_STATE_MAX
);
7977 puts("\nAvailable socket unit substates:");
7978 DUMP_STRING_TABLE(socket_state
, SocketState
, _SOCKET_STATE_MAX
);
7981 puts("\nAvailable swap unit substates:");
7982 DUMP_STRING_TABLE(swap_state
, SwapState
, _SWAP_STATE_MAX
);
7985 puts("\nAvailable target unit substates:");
7986 DUMP_STRING_TABLE(target_state
, TargetState
, _TARGET_STATE_MAX
);
7989 puts("\nAvailable timer unit substates:");
7990 DUMP_STRING_TABLE(timer_state
, TimerState
, _TIMER_STATE_MAX
);
7993 static int help_boot_loader_entry(void) {
7994 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7995 _cleanup_strv_free_
char **l
= NULL
;
8000 r
= acquire_bus(BUS_FULL
, &bus
);
8004 r
= bus_get_property_strv(bus
, bus_login_mgr
, "BootLoaderEntries", &error
, &l
);
8006 return log_error_errno(r
, "Failed to enumerate boot loader entries: %s", bus_error_message(&error
, r
));
8008 if (strv_isempty(l
))
8009 return log_error_errno(SYNTHETIC_ERRNO(ENODATA
), "No boot loader entries discovered.");
8017 static int systemctl_parse_argv(int argc
, char *argv
[]) {
8026 ARG_IGNORE_DEPENDENCIES
,
8039 ARG_NO_ASK_PASSWORD
,
8047 ARG_BOOT_LOADER_MENU
,
8048 ARG_BOOT_LOADER_ENTRY
,
8051 ARG_WITH_DEPENDENCIES
,
8057 static const struct option options
[] = {
8058 { "help", no_argument
, NULL
, 'h' },
8059 { "version", no_argument
, NULL
, ARG_VERSION
},
8060 { "type", required_argument
, NULL
, 't' },
8061 { "property", required_argument
, NULL
, 'p' },
8062 { "all", no_argument
, NULL
, 'a' },
8063 { "reverse", no_argument
, NULL
, ARG_REVERSE
},
8064 { "after", no_argument
, NULL
, ARG_AFTER
},
8065 { "before", no_argument
, NULL
, ARG_BEFORE
},
8066 { "show-types", no_argument
, NULL
, ARG_SHOW_TYPES
},
8067 { "failed", no_argument
, NULL
, ARG_FAILED
}, /* compatibility only */
8068 { "full", no_argument
, NULL
, 'l' },
8069 { "job-mode", required_argument
, NULL
, ARG_JOB_MODE
},
8070 { "fail", no_argument
, NULL
, ARG_FAIL
}, /* compatibility only */
8071 { "irreversible", no_argument
, NULL
, ARG_IRREVERSIBLE
}, /* compatibility only */
8072 { "ignore-dependencies", no_argument
, NULL
, ARG_IGNORE_DEPENDENCIES
}, /* compatibility only */
8073 { "ignore-inhibitors", no_argument
, NULL
, 'i' },
8074 { "value", no_argument
, NULL
, ARG_VALUE
},
8075 { "user", no_argument
, NULL
, ARG_USER
},
8076 { "system", no_argument
, NULL
, ARG_SYSTEM
},
8077 { "global", no_argument
, NULL
, ARG_GLOBAL
},
8078 { "wait", no_argument
, NULL
, ARG_WAIT
},
8079 { "no-block", no_argument
, NULL
, ARG_NO_BLOCK
},
8080 { "no-legend", no_argument
, NULL
, ARG_NO_LEGEND
},
8081 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
8082 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8083 { "dry-run", no_argument
, NULL
, ARG_DRY_RUN
},
8084 { "quiet", no_argument
, NULL
, 'q' },
8085 { "root", required_argument
, NULL
, ARG_ROOT
},
8086 { "force", no_argument
, NULL
, 'f' },
8087 { "no-reload", no_argument
, NULL
, ARG_NO_RELOAD
},
8088 { "kill-who", required_argument
, NULL
, ARG_KILL_WHO
},
8089 { "signal", required_argument
, NULL
, 's' },
8090 { "no-ask-password", no_argument
, NULL
, ARG_NO_ASK_PASSWORD
},
8091 { "host", required_argument
, NULL
, 'H' },
8092 { "machine", required_argument
, NULL
, 'M' },
8093 { "runtime", no_argument
, NULL
, ARG_RUNTIME
},
8094 { "lines", required_argument
, NULL
, 'n' },
8095 { "output", required_argument
, NULL
, 'o' },
8096 { "plain", no_argument
, NULL
, ARG_PLAIN
},
8097 { "state", required_argument
, NULL
, ARG_STATE
},
8098 { "recursive", no_argument
, NULL
, 'r' },
8099 { "with-dependencies", no_argument
, NULL
, ARG_WITH_DEPENDENCIES
},
8100 { "preset-mode", required_argument
, NULL
, ARG_PRESET_MODE
},
8101 { "firmware-setup", no_argument
, NULL
, ARG_FIRMWARE_SETUP
},
8102 { "boot-loader-menu", required_argument
, NULL
, ARG_BOOT_LOADER_MENU
},
8103 { "boot-loader-entry", required_argument
, NULL
, ARG_BOOT_LOADER_ENTRY
},
8104 { "now", no_argument
, NULL
, ARG_NOW
},
8105 { "message", required_argument
, NULL
, ARG_MESSAGE
},
8106 { "show-transaction", no_argument
, NULL
, 'T' },
8107 { "what", required_argument
, NULL
, ARG_WHAT
},
8108 { "reboot-argument", required_argument
, NULL
, ARG_REBOOT_ARG
},
8117 /* we default to allowing interactive authorization only in systemctl (not in the legacy commands) */
8118 arg_ask_password
= true;
8120 while ((c
= getopt_long(argc
, argv
, "ht:p:P:alqfs:H:M:n:o:iTr.::", options
, NULL
)) >= 0)
8125 return systemctl_help();
8133 if (isempty(optarg
))
8134 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8135 "--type= requires arguments.");
8137 for (p
= optarg
;;) {
8138 _cleanup_free_
char *type
= NULL
;
8140 r
= extract_first_word(&p
, &type
, ",", 0);
8142 return log_error_errno(r
, "Failed to parse type: %s", optarg
);
8146 if (streq(type
, "help")) {
8151 if (unit_type_from_string(type
) >= 0) {
8152 if (strv_consume(&arg_types
, TAKE_PTR(type
)) < 0)
8157 /* It's much nicer to use --state= for
8158 * load states, but let's support this
8159 * in --types= too for compatibility
8160 * with old versions */
8161 if (unit_load_state_from_string(type
) >= 0) {
8162 if (strv_consume(&arg_states
, TAKE_PTR(type
)) < 0)
8167 log_error("Unknown unit type or load state '%s'.", type
);
8168 return log_info_errno(SYNTHETIC_ERRNO(EINVAL
),
8169 "Use -t help to see a list of allowed values.");
8180 /* Make sure that if the empty property list was specified, we won't show any
8182 if (isempty(optarg
) && !arg_properties
) {
8183 arg_properties
= new0(char*, 1);
8184 if (!arg_properties
)
8189 for (p
= optarg
;;) {
8190 _cleanup_free_
char *prop
= NULL
;
8192 r
= extract_first_word(&p
, &prop
, ",", 0);
8194 return log_error_errno(r
, "Failed to parse property: %s", optarg
);
8198 if (strv_consume(&arg_properties
, TAKE_PTR(prop
)) < 0)
8203 /* If the user asked for a particular property, show it, even if it is empty. */
8213 arg_dependency
= DEPENDENCY_REVERSE
;
8217 arg_dependency
= DEPENDENCY_AFTER
;
8218 arg_jobs_after
= true;
8222 arg_dependency
= DEPENDENCY_BEFORE
;
8223 arg_jobs_before
= true;
8226 case ARG_SHOW_TYPES
:
8227 arg_show_types
= true;
8235 arg_job_mode
= optarg
;
8239 arg_job_mode
= "fail";
8242 case ARG_IRREVERSIBLE
:
8243 arg_job_mode
= "replace-irreversibly";
8246 case ARG_IGNORE_DEPENDENCIES
:
8247 arg_job_mode
= "ignore-dependencies";
8251 arg_scope
= UNIT_FILE_USER
;
8255 arg_scope
= UNIT_FILE_SYSTEM
;
8259 arg_scope
= UNIT_FILE_GLOBAL
;
8267 arg_no_block
= true;
8271 arg_no_legend
= true;
8275 arg_pager_flags
|= PAGER_DISABLE
;
8283 r
= parse_path_argument_and_warn(optarg
, false, &arg_root
);
8293 if (strv_extend(&arg_states
, "failed") < 0)
8311 arg_no_reload
= true;
8315 arg_kill_who
= optarg
;
8319 if (streq(optarg
, "help")) {
8320 DUMP_STRING_TABLE(signal
, int, _NSIG
);
8324 arg_signal
= signal_from_string(optarg
);
8326 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8327 "Failed to parse signal string %s.",
8331 case ARG_NO_ASK_PASSWORD
:
8332 arg_ask_password
= false;
8336 arg_transport
= BUS_TRANSPORT_REMOTE
;
8341 arg_transport
= BUS_TRANSPORT_MACHINE
;
8350 if (safe_atou(optarg
, &arg_lines
) < 0)
8351 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8352 "Failed to parse lines '%s'",
8357 if (streq(optarg
, "help")) {
8358 DUMP_STRING_TABLE(output_mode
, OutputMode
, _OUTPUT_MODE_MAX
);
8362 arg_output
= output_mode_from_string(optarg
);
8364 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8365 "Unknown output '%s'.",
8368 if (OUTPUT_MODE_IS_JSON(arg_output
)) {
8369 arg_no_legend
= true;
8375 arg_ignore_inhibitors
= true;
8382 case ARG_FIRMWARE_SETUP
:
8383 arg_firmware_setup
= true;
8386 case ARG_BOOT_LOADER_MENU
:
8388 r
= parse_sec(optarg
, &arg_boot_loader_menu
);
8390 return log_error_errno(r
, "Failed to parse --boot-loader-menu= argument '%s': %m", optarg
);
8394 case ARG_BOOT_LOADER_ENTRY
:
8396 if (streq(optarg
, "help")) { /* Yes, this means, "help" is not a valid boot loader entry name we can deal with */
8397 r
= help_boot_loader_entry();
8404 arg_boot_loader_entry
= empty_to_null(optarg
);
8410 if (isempty(optarg
))
8411 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8412 "--state= requires arguments.");
8414 for (p
= optarg
;;) {
8415 _cleanup_free_
char *s
= NULL
;
8417 r
= extract_first_word(&p
, &s
, ",", 0);
8419 return log_error_errno(r
, "Failed to parse state: %s", optarg
);
8423 if (streq(s
, "help")) {
8428 if (strv_consume(&arg_states
, TAKE_PTR(s
)) < 0)
8436 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
8437 "--recursive requires root privileges.");
8439 arg_recursive
= true;
8442 case ARG_PRESET_MODE
:
8443 if (streq(optarg
, "help")) {
8444 DUMP_STRING_TABLE(unit_file_preset_mode
, UnitFilePresetMode
, _UNIT_FILE_PRESET_MAX
);
8448 arg_preset_mode
= unit_file_preset_mode_from_string(optarg
);
8449 if (arg_preset_mode
< 0)
8450 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8451 "Failed to parse preset mode: %s.", optarg
);
8460 if (strv_extend(&arg_wall
, optarg
) < 0)
8465 arg_show_transaction
= true;
8468 case ARG_WITH_DEPENDENCIES
:
8469 arg_with_dependencies
= true;
8475 if (isempty(optarg
))
8476 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "--what= requires arguments.");
8478 for (p
= optarg
;;) {
8479 _cleanup_free_
char *k
= NULL
;
8481 r
= extract_first_word(&p
, &k
, ",", 0);
8483 return log_error_errno(r
, "Failed to parse directory type: %s", optarg
);
8487 if (streq(k
, "help")) {
8496 r
= strv_consume(&arg_clean_what
, TAKE_PTR(k
));
8504 case ARG_REBOOT_ARG
:
8505 arg_reboot_argument
= optarg
;
8509 /* Output an error mimicking getopt, and print a hint afterwards */
8510 log_error("%s: invalid option -- '.'", program_invocation_name
);
8511 log_notice("Hint: to specify units starting with a dash, use \"--\":\n"
8512 " %s [OPTIONS...] COMMAND -- -.%s ...",
8513 program_invocation_name
, optarg
?: "mount");
8520 assert_not_reached("Unhandled option");
8523 if (arg_transport
!= BUS_TRANSPORT_LOCAL
&& arg_scope
!= UNIT_FILE_SYSTEM
)
8524 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8525 "Cannot access user instance remotely.");
8527 if (arg_wait
&& arg_no_block
)
8528 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8529 "--wait may not be combined with --no-block.");
8534 static int halt_parse_argv(int argc
, char *argv
[]) {
8542 static const struct option options
[] = {
8543 { "help", no_argument
, NULL
, ARG_HELP
},
8544 { "halt", no_argument
, NULL
, ARG_HALT
},
8545 { "poweroff", no_argument
, NULL
, 'p' },
8546 { "reboot", no_argument
, NULL
, ARG_REBOOT
},
8547 { "force", no_argument
, NULL
, 'f' },
8548 { "wtmp-only", no_argument
, NULL
, 'w' },
8549 { "no-wtmp", no_argument
, NULL
, 'd' },
8550 { "no-sync", no_argument
, NULL
, 'n' },
8551 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8560 if (utmp_get_runlevel(&runlevel
, NULL
) >= 0)
8561 if (IN_SET(runlevel
, '0', '6'))
8564 while ((c
= getopt_long(argc
, argv
, "pfwdnih", options
, NULL
)) >= 0)
8571 arg_action
= ACTION_HALT
;
8575 if (arg_action
!= ACTION_REBOOT
)
8576 arg_action
= ACTION_POWEROFF
;
8580 arg_action
= ACTION_REBOOT
;
8605 /* Compatibility nops */
8612 assert_not_reached("Unhandled option");
8615 if (arg_action
== ACTION_REBOOT
&& (argc
== optind
|| argc
== optind
+ 1)) {
8616 r
= update_reboot_parameter_and_warn(argc
== optind
+ 1 ? argv
[optind
] : NULL
, false);
8619 } else if (optind
< argc
)
8620 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8621 "Too many arguments.");
8626 static int shutdown_parse_argv(int argc
, char *argv
[]) {
8632 static const struct option options
[] = {
8633 { "help", no_argument
, NULL
, ARG_HELP
},
8634 { "halt", no_argument
, NULL
, 'H' },
8635 { "poweroff", no_argument
, NULL
, 'P' },
8636 { "reboot", no_argument
, NULL
, 'r' },
8637 { "kexec", no_argument
, NULL
, 'K' }, /* not documented extension */
8638 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8648 while ((c
= getopt_long(argc
, argv
, "HPrhkKat:fFc", options
, NULL
)) >= 0)
8652 return shutdown_help();
8655 arg_action
= ACTION_HALT
;
8659 arg_action
= ACTION_POWEROFF
;
8664 arg_action
= ACTION_KEXEC
;
8666 arg_action
= ACTION_REBOOT
;
8670 arg_action
= ACTION_KEXEC
;
8674 if (arg_action
!= ACTION_HALT
)
8675 arg_action
= ACTION_POWEROFF
;
8687 case 't': /* Note that we also ignore any passed argument to -t, not just the -t itself */
8690 /* Compatibility nops */
8694 arg_action
= ACTION_CANCEL_SHUTDOWN
;
8701 assert_not_reached("Unhandled option");
8704 if (argc
> optind
&& arg_action
!= ACTION_CANCEL_SHUTDOWN
) {
8705 r
= parse_shutdown_time_spec(argv
[optind
], &arg_when
);
8707 log_error("Failed to parse time specification: %s", argv
[optind
]);
8711 arg_when
= now(CLOCK_REALTIME
) + USEC_PER_MINUTE
;
8713 if (argc
> optind
&& arg_action
== ACTION_CANCEL_SHUTDOWN
)
8714 /* No time argument for shutdown cancel */
8715 wall
= argv
+ optind
;
8716 else if (argc
> optind
+ 1)
8717 /* We skip the time argument */
8718 wall
= argv
+ optind
+ 1;
8721 arg_wall
= strv_copy(wall
);
8731 static int telinit_parse_argv(int argc
, char *argv
[]) {
8737 static const struct option options
[] = {
8738 { "help", no_argument
, NULL
, ARG_HELP
},
8739 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8743 static const struct {
8747 { '0', ACTION_POWEROFF
},
8748 { '6', ACTION_REBOOT
},
8749 { '1', ACTION_RESCUE
},
8750 { '2', ACTION_RUNLEVEL2
},
8751 { '3', ACTION_RUNLEVEL3
},
8752 { '4', ACTION_RUNLEVEL4
},
8753 { '5', ACTION_RUNLEVEL5
},
8754 { 's', ACTION_RESCUE
},
8755 { 'S', ACTION_RESCUE
},
8756 { 'q', ACTION_RELOAD
},
8757 { 'Q', ACTION_RELOAD
},
8758 { 'u', ACTION_REEXEC
},
8759 { 'U', ACTION_REEXEC
}
8768 while ((c
= getopt_long(argc
, argv
, "", options
, NULL
)) >= 0)
8772 return telinit_help();
8782 assert_not_reached("Unhandled option");
8786 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8787 "%s: required argument missing.",
8788 program_invocation_short_name
);
8790 if (optind
+ 1 < argc
)
8791 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8792 "Too many arguments.");
8794 if (strlen(argv
[optind
]) != 1)
8795 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8796 "Expected single character argument.");
8798 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
8799 if (table
[i
].from
== argv
[optind
][0])
8802 if (i
>= ELEMENTSOF(table
))
8803 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8804 "Unknown command '%s'.", argv
[optind
]);
8806 arg_action
= table
[i
].to
;
8813 static int runlevel_parse_argv(int argc
, char *argv
[]) {
8818 static const struct option options
[] = {
8819 { "help", no_argument
, NULL
, ARG_HELP
},
8828 while ((c
= getopt_long(argc
, argv
, "", options
, NULL
)) >= 0)
8832 return runlevel_help();
8838 assert_not_reached("Unhandled option");
8842 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8843 "Too many arguments.");
8848 static int parse_argv(int argc
, char *argv
[]) {
8852 if (program_invocation_short_name
) {
8854 if (strstr(program_invocation_short_name
, "halt")) {
8855 arg_action
= ACTION_HALT
;
8856 return halt_parse_argv(argc
, argv
);
8858 } else if (strstr(program_invocation_short_name
, "poweroff")) {
8859 arg_action
= ACTION_POWEROFF
;
8860 return halt_parse_argv(argc
, argv
);
8862 } else if (strstr(program_invocation_short_name
, "reboot")) {
8864 arg_action
= ACTION_KEXEC
;
8866 arg_action
= ACTION_REBOOT
;
8867 return halt_parse_argv(argc
, argv
);
8869 } else if (strstr(program_invocation_short_name
, "shutdown")) {
8870 arg_action
= ACTION_POWEROFF
;
8871 return shutdown_parse_argv(argc
, argv
);
8873 } else if (strstr(program_invocation_short_name
, "init")) {
8875 /* Matches invocations as "init" as well as "telinit", which are synonymous when run as PID !=
8878 * On SysV "telinit" was the official command to communicate with PID 1, but "init" would
8879 * redirect itself to "telinit" if called with PID != 1. We follow the same logic here still,
8880 * though we add one level of indirection, as we implement "telinit" in "systemctl". Hence, for
8881 * us if you invoke "init" you get "systemd", but it will execve() "systemctl" immediately with
8882 * argv[] unmodified if PID is != 1. If you invoke "telinit" you directly get "systemctl". In
8883 * both cases we shall do the same thing, which is why we do strstr(p_i_s_n, "init") here, as a
8884 * quick way to match both.
8886 * Also see redirect_telinit() in src/core/main.c. */
8888 if (sd_booted() > 0) {
8889 arg_action
= _ACTION_INVALID
;
8890 return telinit_parse_argv(argc
, argv
);
8892 /* Hmm, so some other init system is running, we need to forward this request to
8893 * it. For now we simply guess that it is Upstart. */
8895 (void) rlimit_nofile_safe();
8896 execv(TELINIT
, argv
);
8898 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
8899 "Couldn't find an alternative telinit implementation to spawn.");
8902 } else if (strstr(program_invocation_short_name
, "runlevel")) {
8903 arg_action
= ACTION_RUNLEVEL
;
8904 return runlevel_parse_argv(argc
, argv
);
8908 arg_action
= ACTION_SYSTEMCTL
;
8909 return systemctl_parse_argv(argc
, argv
);
8912 #if HAVE_SYSV_COMPAT
8913 _pure_
static int action_to_runlevel(void) {
8914 static const char table
[_ACTION_MAX
] = {
8915 [ACTION_HALT
] = '0',
8916 [ACTION_POWEROFF
] = '0',
8917 [ACTION_REBOOT
] = '6',
8918 [ACTION_RUNLEVEL2
] = '2',
8919 [ACTION_RUNLEVEL3
] = '3',
8920 [ACTION_RUNLEVEL4
] = '4',
8921 [ACTION_RUNLEVEL5
] = '5',
8922 [ACTION_RESCUE
] = '1'
8925 assert(arg_action
>= 0 && arg_action
< _ACTION_MAX
);
8926 return table
[arg_action
];
8930 static int systemctl_main(int argc
, char *argv
[]) {
8931 static const Verb verbs
[] = {
8932 { "list-units", VERB_ANY
, VERB_ANY
, VERB_DEFAULT
|VERB_ONLINE_ONLY
, list_units
},
8933 { "list-unit-files", VERB_ANY
, VERB_ANY
, 0, list_unit_files
},
8934 { "list-sockets", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_sockets
},
8935 { "list-timers", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_timers
},
8936 { "list-jobs", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_jobs
},
8937 { "list-machines", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_machines
},
8938 { "clear-jobs", VERB_ANY
, 1, VERB_ONLINE_ONLY
, trivial_method
},
8939 { "cancel", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, cancel_job
},
8940 { "start", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
8941 { "stop", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
8942 { "condstop", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with ALTLinux */
8943 { "reload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
8944 { "restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
8945 { "try-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
8946 { "reload-or-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
8947 { "reload-or-try-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with old systemctl <= 228 */
8948 { "try-reload-or-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
8949 { "force-reload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with SysV */
8950 { "condreload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with ALTLinux */
8951 { "condrestart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with RH */
8952 { "isolate", 2, 2, VERB_ONLINE_ONLY
, start_unit
},
8953 { "kill", 2, VERB_ANY
, VERB_ONLINE_ONLY
, kill_unit
},
8954 { "clean", 2, VERB_ANY
, VERB_ONLINE_ONLY
, clean_or_freeze_unit
},
8955 { "freeze", 2, VERB_ANY
, VERB_ONLINE_ONLY
, clean_or_freeze_unit
},
8956 { "thaw", 2, VERB_ANY
, VERB_ONLINE_ONLY
, clean_or_freeze_unit
},
8957 { "is-active", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_active
},
8958 { "check", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_active
}, /* deprecated alias of is-active */
8959 { "is-failed", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_failed
},
8960 { "show", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
8961 { "cat", 2, VERB_ANY
, VERB_ONLINE_ONLY
, cat
},
8962 { "status", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
8963 { "help", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
8964 { "daemon-reload", VERB_ANY
, 1, VERB_ONLINE_ONLY
, daemon_reload
},
8965 { "daemon-reexec", VERB_ANY
, 1, VERB_ONLINE_ONLY
, daemon_reload
},
8966 { "log-level", VERB_ANY
, 2, VERB_ONLINE_ONLY
, log_level
},
8967 { "log-target", VERB_ANY
, 2, VERB_ONLINE_ONLY
, log_target
},
8968 { "service-watchdogs", VERB_ANY
, 2, VERB_ONLINE_ONLY
, service_watchdogs
},
8969 { "show-environment", VERB_ANY
, 1, VERB_ONLINE_ONLY
, show_environment
},
8970 { "set-environment", 2, VERB_ANY
, VERB_ONLINE_ONLY
, set_environment
},
8971 { "unset-environment", 2, VERB_ANY
, VERB_ONLINE_ONLY
, set_environment
},
8972 { "import-environment", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, import_environment
},
8973 { "halt", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
8974 { "poweroff", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
8975 { "reboot", VERB_ANY
, 2, VERB_ONLINE_ONLY
, start_system_special
},
8976 { "kexec", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
8977 { "suspend", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
8978 { "hibernate", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
8979 { "hybrid-sleep", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
8980 { "suspend-then-hibernate",VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
8981 { "default", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_special
},
8982 { "rescue", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
8983 { "emergency", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
8984 { "exit", VERB_ANY
, 2, VERB_ONLINE_ONLY
, start_special
},
8985 { "reset-failed", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, reset_failed
},
8986 { "enable", 2, VERB_ANY
, 0, enable_unit
},
8987 { "disable", 2, VERB_ANY
, 0, enable_unit
},
8988 { "is-enabled", 2, VERB_ANY
, 0, unit_is_enabled
},
8989 { "reenable", 2, VERB_ANY
, 0, enable_unit
},
8990 { "preset", 2, VERB_ANY
, 0, enable_unit
},
8991 { "preset-all", VERB_ANY
, 1, 0, preset_all
},
8992 { "mask", 2, VERB_ANY
, 0, enable_unit
},
8993 { "unmask", 2, VERB_ANY
, 0, enable_unit
},
8994 { "link", 2, VERB_ANY
, 0, enable_unit
},
8995 { "revert", 2, VERB_ANY
, 0, enable_unit
},
8996 { "switch-root", 2, VERB_ANY
, VERB_ONLINE_ONLY
, switch_root
},
8997 { "list-dependencies", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_dependencies
},
8998 { "set-default", 2, 2, 0, set_default
},
8999 { "get-default", VERB_ANY
, 1, 0, get_default
},
9000 { "set-property", 3, VERB_ANY
, VERB_ONLINE_ONLY
, set_property
},
9001 { "is-system-running", VERB_ANY
, 1, 0, is_system_running
},
9002 { "add-wants", 3, VERB_ANY
, 0, add_dependency
},
9003 { "add-requires", 3, VERB_ANY
, 0, add_dependency
},
9004 { "edit", 2, VERB_ANY
, VERB_ONLINE_ONLY
, edit
},
9008 const Verb
*verb
= verbs_find_verb(argv
[optind
], verbs
);
9009 if (verb
&& (verb
->flags
& VERB_ONLINE_ONLY
) && arg_root
)
9010 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
9011 "Verb '%s' cannot be used with --root=.",
9012 argv
[optind
] ?: verb
->verb
);
9014 return dispatch_verb(argc
, argv
, verbs
, NULL
);
9017 static int reload_with_fallback(void) {
9018 /* First, try systemd via D-Bus. */
9019 if (daemon_reload(0, NULL
, NULL
) >= 0)
9022 /* Nothing else worked, so let's try signals */
9023 assert(IN_SET(arg_action
, ACTION_RELOAD
, ACTION_REEXEC
));
9025 if (kill(1, arg_action
== ACTION_RELOAD
? SIGHUP
: SIGTERM
) < 0)
9026 return log_error_errno(errno
, "kill() failed: %m");
9031 static int start_with_fallback(void) {
9032 /* First, try systemd via D-Bus. */
9033 if (start_unit(0, NULL
, NULL
) == 0)
9036 #if HAVE_SYSV_COMPAT
9037 /* Nothing else worked, so let's try /dev/initctl */
9038 if (talk_initctl(action_to_runlevel()) > 0)
9042 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
9043 "Failed to talk to init daemon.");
9046 static int halt_now(enum action a
) {
9047 /* The kernel will automatically flush ATA disks and suchlike on reboot(), but the file systems need to be
9048 * synced explicitly in advance. */
9049 if (!arg_no_sync
&& !arg_dry_run
)
9052 /* Make sure C-A-D is handled by the kernel from this point on... */
9054 (void) reboot(RB_ENABLE_CAD
);
9060 log_info("Halting.");
9063 (void) reboot(RB_HALT_SYSTEM
);
9066 case ACTION_POWEROFF
:
9068 log_info("Powering off.");
9071 (void) reboot(RB_POWER_OFF
);
9076 return reboot_with_parameter(REBOOT_FALLBACK
|
9077 (arg_quiet
? 0 : REBOOT_LOG
) |
9078 (arg_dry_run
? REBOOT_DRY_RUN
: 0));
9081 assert_not_reached("Unknown action.");
9085 static int logind_schedule_shutdown(void) {
9088 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
9089 char date
[FORMAT_TIMESTAMP_MAX
];
9091 const char *log_action
;
9095 r
= acquire_bus(BUS_FULL
, &bus
);
9099 switch (arg_action
) {
9102 log_action
= "Shutdown";
9104 case ACTION_POWEROFF
:
9105 action
= "poweroff";
9106 log_action
= "Shutdown";
9110 log_action
= "Reboot via kexec";
9114 log_action
= "Shutdown";
9119 log_action
= "Reboot";
9124 action
= strjoina("dry-", action
);
9126 (void) logind_set_wall_message();
9128 r
= bus_call_method(bus
, bus_login_mgr
, "ScheduleShutdown", &error
, NULL
, "st", action
, arg_when
);
9130 return log_warning_errno(r
, "Failed to call ScheduleShutdown in logind, proceeding with immediate shutdown: %s", bus_error_message(&error
, r
));
9133 log_info("%s scheduled for %s, use 'shutdown -c' to cancel.", log_action
, format_timestamp(date
, sizeof(date
), arg_when
));
9136 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
9137 "Cannot schedule shutdown without logind support, proceeding with immediate shutdown.");
9141 static int halt_main(void) {
9144 r
= logind_check_inhibitors(arg_action
);
9148 /* Delayed shutdown requested, and was successful */
9149 if (arg_when
> 0 && logind_schedule_shutdown() == 0)
9151 /* no delay, or logind failed or is not at all available */
9153 if (geteuid() != 0) {
9154 if (arg_dry_run
|| arg_force
> 0) {
9155 (void) must_be_root();
9159 /* Try logind if we are a normal user and no special
9160 * mode applies. Maybe polkit allows us to shutdown
9162 if (IN_SET(arg_action
, ACTION_POWEROFF
, ACTION_REBOOT
, ACTION_HALT
)) {
9163 r
= logind_reboot(arg_action
);
9166 if (IN_SET(r
, -EOPNOTSUPP
, -EINPROGRESS
))
9167 /* requested operation is not
9168 * supported on the local system or
9169 * already in progress */
9171 /* on all other errors, try low-level operation */
9175 /* In order to minimize the difference between operation with and
9176 * without logind, we explicitly enable non-blocking mode for this,
9177 * as logind's shutdown operations are always non-blocking. */
9178 arg_no_block
= true;
9180 if (!arg_dry_run
&& !arg_force
)
9181 return start_with_fallback();
9183 assert(geteuid() == 0);
9186 if (sd_booted() > 0)
9187 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
9189 r
= utmp_put_shutdown();
9191 log_warning_errno(r
, "Failed to write utmp record: %m");
9198 r
= halt_now(arg_action
);
9199 return log_error_errno(r
, "Failed to reboot: %m");
9202 static int runlevel_main(void) {
9203 int r
, runlevel
, previous
;
9205 r
= utmp_get_runlevel(&runlevel
, &previous
);
9212 previous
<= 0 ? 'N' : previous
,
9213 runlevel
<= 0 ? 'N' : runlevel
);
9218 static int logind_cancel_shutdown(void) {
9220 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
9224 r
= acquire_bus(BUS_FULL
, &bus
);
9228 (void) logind_set_wall_message();
9230 r
= bus_call_method(bus
, bus_login_mgr
, "CancelScheduledShutdown", &error
, NULL
, NULL
);
9232 return log_warning_errno(r
, "Failed to talk to logind, shutdown hasn't been cancelled: %s", bus_error_message(&error
, r
));
9236 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
9237 "Not compiled with logind support, cannot cancel scheduled shutdowns.");
9241 static int run(int argc
, char *argv
[]) {
9244 setlocale(LC_ALL
, "");
9245 log_parse_environment_cli();
9248 /* The journal merging logic potentially needs a lot of fds. */
9249 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE
);
9253 /* Explicitly not on_tty() to avoid setting cached value.
9254 * This becomes relevant for piping output which might be
9256 original_stdout_is_tty
= isatty(STDOUT_FILENO
);
9258 r
= parse_argv(argc
, argv
);
9262 if (arg_action
!= ACTION_SYSTEMCTL
&& running_in_chroot() > 0) {
9264 log_info("Running in chroot, ignoring request.");
9269 /* systemctl_main() will print an error message for the bus
9270 * connection, but only if it needs to */
9272 switch (arg_action
) {
9274 case ACTION_SYSTEMCTL
:
9275 r
= systemctl_main(argc
, argv
);
9278 /* Legacy command aliases set arg_action. They provide some fallbacks,
9279 * e.g. to tell sysvinit to reboot after you have installed systemd
9283 case ACTION_POWEROFF
:
9289 case ACTION_RUNLEVEL2
:
9290 case ACTION_RUNLEVEL3
:
9291 case ACTION_RUNLEVEL4
:
9292 case ACTION_RUNLEVEL5
:
9294 r
= start_with_fallback();
9299 r
= reload_with_fallback();
9302 case ACTION_CANCEL_SHUTDOWN
:
9303 r
= logind_cancel_shutdown();
9306 case ACTION_RUNLEVEL
:
9307 r
= runlevel_main();
9311 case ACTION_SUSPEND
:
9312 case ACTION_HIBERNATE
:
9313 case ACTION_HYBRID_SLEEP
:
9314 case ACTION_SUSPEND_THEN_HIBERNATE
:
9315 case ACTION_EMERGENCY
:
9316 case ACTION_DEFAULT
:
9317 /* systemctl verbs with no equivalent in the legacy commands.
9318 * These cannot appear in arg_action. Fall through. */
9320 case _ACTION_INVALID
:
9322 assert_not_reached("Unknown action");
9328 /* Note that we return r here, not 0, so that we can implement the LSB-like return codes */
9332 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);