1 /* SPDX-License-Identifier: LGPL-2.1+ */
10 #include <sys/prctl.h>
11 #include <sys/reboot.h>
15 #include "sd-daemon.h"
19 #include "alloc-util.h"
21 #include "bus-common-errors.h"
22 #include "bus-error.h"
23 #include "bus-message.h"
24 #include "bus-unit-procs.h"
25 #include "bus-unit-util.h"
27 #include "bus-wait-for-jobs.h"
28 #include "bus-wait-for-units.h"
29 #include "cgroup-show.h"
30 #include "cgroup-util.h"
32 #include "cpu-set-util.h"
33 #include "dirent-util.h"
35 #include "efi-loader.h"
39 #include "exec-util.h"
40 #include "exit-status.h"
42 #include "format-table.h"
43 #include "format-util.h"
45 #include "glob-util.h"
46 #include "hexdecoct.h"
47 #include "hostname-util.h"
48 #include "in-addr-util.h"
52 #include "journal-util.h"
54 #include "locale-util.h"
56 #include "logs-show.h"
58 #include "main-func.h"
59 #include "memory-util.h"
61 #include "numa-util.h"
63 #include "parse-util.h"
64 #include "path-lookup.h"
65 #include "path-util.h"
66 #include "pretty-print.h"
67 #include "proc-cmdline.h"
68 #include "process-util.h"
69 #include "reboot-util.h"
70 #include "rlimit-util.h"
73 #include "signal-util.h"
74 #include "socket-util.h"
75 #include "sort-util.h"
76 #include "spawn-ask-password-agent.h"
77 #include "spawn-polkit-agent.h"
79 #include "stat-util.h"
80 #include "string-table.h"
82 #include "sysv-compat.h"
83 #include "terminal-util.h"
84 #include "tmpfile-util.h"
86 #include "unit-file.h"
87 #include "unit-name.h"
88 #include "user-util.h"
90 #include "utmp-wtmp.h"
94 static char **arg_types
= NULL
;
95 static char **arg_states
= NULL
;
96 static char **arg_properties
= NULL
;
97 static bool arg_all
= false;
98 static enum dependency
{
104 } arg_dependency
= DEPENDENCY_FORWARD
;
105 static const char *arg_job_mode
= "replace";
106 static UnitFileScope arg_scope
= UNIT_FILE_SYSTEM
;
107 static bool arg_wait
= false;
108 static bool arg_no_block
= false;
109 static bool arg_no_legend
= false;
110 static PagerFlags arg_pager_flags
= 0;
111 static bool arg_no_wtmp
= false;
112 static bool arg_no_sync
= false;
113 static bool arg_no_wall
= false;
114 static bool arg_no_reload
= false;
115 static bool arg_value
= false;
116 static bool arg_show_types
= false;
117 static bool arg_ignore_inhibitors
= false;
118 static bool arg_dry_run
= false;
119 static bool arg_quiet
= false;
120 static bool arg_full
= false;
121 static bool arg_recursive
= false;
122 static bool arg_with_dependencies
= false;
123 static bool arg_show_transaction
= false;
124 static int arg_force
= 0;
125 static bool arg_ask_password
= false;
126 static bool arg_runtime
= false;
127 static UnitFilePresetMode arg_preset_mode
= UNIT_FILE_PRESET_FULL
;
128 static char **arg_wall
= NULL
;
129 static const char *arg_kill_who
= NULL
;
130 static int arg_signal
= SIGTERM
;
131 static char *arg_root
= NULL
;
132 static usec_t arg_when
= 0;
143 ACTION_SUSPEND_THEN_HIBERNATE
,
154 ACTION_CANCEL_SHUTDOWN
,
157 } arg_action
= ACTION_SYSTEMCTL
;
158 static BusTransport arg_transport
= BUS_TRANSPORT_LOCAL
;
159 static const char *arg_host
= NULL
;
160 static unsigned arg_lines
= 10;
161 static OutputMode arg_output
= OUTPUT_SHORT
;
162 static bool arg_plain
= false;
163 static bool arg_firmware_setup
= false;
164 static usec_t arg_boot_loader_menu
= USEC_INFINITY
;
165 static const char *arg_boot_loader_entry
= NULL
;
166 static bool arg_now
= false;
167 static bool arg_jobs_before
= false;
168 static bool arg_jobs_after
= false;
169 static char **arg_clean_what
= NULL
;
171 /* This is a global cache that will be constructed on first use. */
172 static Hashmap
*cached_id_map
= NULL
;
173 static Hashmap
*cached_name_map
= NULL
;
175 STATIC_DESTRUCTOR_REGISTER(arg_wall
, strv_freep
);
176 STATIC_DESTRUCTOR_REGISTER(arg_root
, freep
);
177 STATIC_DESTRUCTOR_REGISTER(arg_types
, strv_freep
);
178 STATIC_DESTRUCTOR_REGISTER(arg_states
, strv_freep
);
179 STATIC_DESTRUCTOR_REGISTER(arg_properties
, strv_freep
);
180 STATIC_DESTRUCTOR_REGISTER(arg_clean_what
, strv_freep
);
181 STATIC_DESTRUCTOR_REGISTER(cached_id_map
, hashmap_freep
);
182 STATIC_DESTRUCTOR_REGISTER(cached_name_map
, hashmap_freep
);
184 static int daemon_reload(int argc
, char *argv
[], void* userdata
);
185 static int trivial_method(int argc
, char *argv
[], void *userdata
);
186 static int halt_now(enum action a
);
187 static int get_state_one_unit(sd_bus
*bus
, const char *name
, UnitActiveState
*active_state
);
189 static bool original_stdout_is_tty
;
191 typedef enum BusFocus
{
192 BUS_FULL
, /* The full bus indicated via --system or --user */
193 BUS_MANAGER
, /* The manager itself, possibly directly, possibly via the bus */
197 static sd_bus
*buses
[_BUS_FOCUS_MAX
] = {};
199 static UnitFileFlags
args_to_flags(void) {
200 return (arg_runtime
? UNIT_FILE_RUNTIME
: 0) |
201 (arg_force
? UNIT_FILE_FORCE
: 0);
204 static int acquire_bus(BusFocus focus
, sd_bus
**ret
) {
207 assert(focus
< _BUS_FOCUS_MAX
);
210 /* We only go directly to the manager, if we are using a local transport */
211 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
214 if (getenv_bool("SYSTEMCTL_FORCE_BUS") > 0)
220 user
= arg_scope
!= UNIT_FILE_SYSTEM
;
222 if (focus
== BUS_MANAGER
)
223 r
= bus_connect_transport_systemd(arg_transport
, arg_host
, user
, &buses
[focus
]);
225 r
= bus_connect_transport(arg_transport
, arg_host
, user
, &buses
[focus
]);
227 return log_error_errno(r
, "Failed to connect to bus: %m");
229 (void) sd_bus_set_allow_interactive_authorization(buses
[focus
], arg_ask_password
);
236 static void release_busses(void) {
239 for (w
= 0; w
< _BUS_FOCUS_MAX
; w
++)
240 buses
[w
] = sd_bus_flush_close_unref(buses
[w
]);
243 static void ask_password_agent_open_maybe(void) {
244 /* Open the password agent as a child process if necessary */
249 if (arg_scope
!= UNIT_FILE_SYSTEM
)
252 ask_password_agent_open_if_enabled(arg_transport
, arg_ask_password
);
255 static void polkit_agent_open_maybe(void) {
256 /* Open the polkit agent as a child process if necessary */
258 if (arg_scope
!= UNIT_FILE_SYSTEM
)
261 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
264 static OutputFlags
get_output_flags(void) {
266 arg_all
* OUTPUT_SHOW_ALL
|
267 (arg_full
|| !on_tty() || pager_have()) * OUTPUT_FULL_WIDTH
|
268 colors_enabled() * OUTPUT_COLOR
|
269 !arg_quiet
* OUTPUT_WARN_CUTOFF
;
272 static int translate_bus_error_to_exit_status(int r
, const sd_bus_error
*error
) {
275 if (!sd_bus_error_is_set(error
))
278 if (sd_bus_error_has_name(error
, SD_BUS_ERROR_ACCESS_DENIED
) ||
279 sd_bus_error_has_name(error
, BUS_ERROR_ONLY_BY_DEPENDENCY
) ||
280 sd_bus_error_has_name(error
, BUS_ERROR_NO_ISOLATION
) ||
281 sd_bus_error_has_name(error
, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE
))
282 return EXIT_NOPERMISSION
;
284 if (sd_bus_error_has_name(error
, BUS_ERROR_NO_SUCH_UNIT
))
285 return EXIT_NOTINSTALLED
;
287 if (sd_bus_error_has_name(error
, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE
) ||
288 sd_bus_error_has_name(error
, SD_BUS_ERROR_NOT_SUPPORTED
))
289 return EXIT_NOTIMPLEMENTED
;
291 if (sd_bus_error_has_name(error
, BUS_ERROR_LOAD_FAILED
))
292 return EXIT_NOTCONFIGURED
;
300 static bool install_client_side(void) {
301 /* Decides when to execute enable/disable/... operations
302 * client-side rather than server-side. */
304 if (running_in_chroot_or_offline())
307 if (sd_booted() <= 0)
310 if (!isempty(arg_root
))
313 if (arg_scope
== UNIT_FILE_GLOBAL
)
316 /* Unsupported environment variable, mostly for debugging purposes */
317 if (getenv_bool("SYSTEMCTL_INSTALL_CLIENT_SIDE") > 0)
323 static int compare_unit_info(const UnitInfo
*a
, const UnitInfo
*b
) {
327 /* First, order by machine */
328 if (!a
->machine
&& b
->machine
)
330 if (a
->machine
&& !b
->machine
)
332 if (a
->machine
&& b
->machine
) {
333 r
= strcasecmp(a
->machine
, b
->machine
);
338 /* Second, order by unit type */
339 d1
= strrchr(a
->id
, '.');
340 d2
= strrchr(b
->id
, '.');
342 r
= strcasecmp(d1
, d2
);
347 /* Third, order by name */
348 return strcasecmp(a
->id
, b
->id
);
351 static const char* unit_type_suffix(const char *name
) {
354 dot
= strrchr(name
, '.');
361 static bool output_show_unit(const UnitInfo
*u
, char **patterns
) {
364 if (!strv_fnmatch_or_empty(patterns
, u
->id
, FNM_NOESCAPE
))
367 if (arg_types
&& !strv_find(arg_types
, unit_type_suffix(u
->id
)))
373 /* Note that '--all' is not purely a state filter, but also a
374 * filter that hides units that "follow" other units (which is
375 * used for device units that appear under different names). */
376 if (!isempty(u
->following
))
379 if (!strv_isempty(arg_states
))
382 /* By default show all units except the ones in inactive
383 * state and with no pending job */
387 if (streq(u
->active_state
, "inactive"))
393 static int output_table(Table
*table
) {
398 if (OUTPUT_MODE_IS_JSON(arg_output
))
399 r
= table_print_json(table
, NULL
, output_mode_to_json_format_flags(arg_output
) | JSON_FORMAT_COLOR_AUTO
);
401 r
= table_print(table
, NULL
);
403 return log_error_errno(r
, "Failed to show table: %m");
408 static int output_units_list(const UnitInfo
*unit_infos
, unsigned c
) {
409 _cleanup_(table_unrefp
) Table
*table
= NULL
;
414 table
= table_new("", "unit", "load", "active", "sub", "job", "description");
418 table_set_header(table
, !arg_no_legend
);
420 /* Hide the 'glyph' column when --plain is requested */
421 r
= table_hide_column_from_display(table
, 0);
423 return log_error_errno(r
, "Failed to hide column: %m");
426 table_set_width(table
, 0);
428 for (u
= unit_infos
; unit_infos
&& u
< unit_infos
+ c
; u
++) {
429 _cleanup_free_
char *j
= NULL
;
430 const char *on_underline
= "", *on_loaded
= "", *on_active
= "";
431 const char *on_circle
= "", *id
;
432 bool circle
= false, underline
= false;
434 if (u
+ 1 < unit_infos
+ c
&&
435 !streq(unit_type_suffix(u
->id
), unit_type_suffix((u
+ 1)->id
))) {
436 on_underline
= ansi_underline();
440 if (STR_IN_SET(u
->load_state
, "error", "not-found", "bad-setting", "masked") && !arg_plain
) {
441 on_circle
= ansi_highlight_yellow();
443 on_loaded
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
444 } else if (streq(u
->active_state
, "failed") && !arg_plain
) {
445 on_circle
= ansi_highlight_red();
447 on_active
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
449 on_active
= on_underline
;
450 on_loaded
= on_underline
;
454 j
= strjoin(u
->machine
, ":", u
->id
);
462 r
= table_add_many(table
,
463 TABLE_STRING
, circle
? special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
) : " ",
464 TABLE_SET_COLOR
, on_circle
,
466 TABLE_SET_COLOR
, on_active
,
467 TABLE_STRING
, u
->load_state
,
468 TABLE_SET_COLOR
, on_loaded
,
469 TABLE_STRING
, u
->active_state
,
470 TABLE_SET_COLOR
, on_active
,
471 TABLE_STRING
, u
->sub_state
,
472 TABLE_SET_COLOR
, on_active
,
473 TABLE_STRING
, u
->job_id
? u
->job_type
: "",
474 TABLE_SET_COLOR
, u
->job_id
? on_underline
: "",
475 TABLE_STRING
, u
->description
,
476 TABLE_SET_COLOR
, on_underline
);
478 return table_log_add_error(r
);
484 if (job_count
== 0) {
485 /* There's no data in the JOB column, so let's hide it */
486 r
= table_hide_column_from_display(table
, 5);
488 return log_error_errno(r
, "Failed to hide column: %m");
491 r
= output_table(table
);
495 if (!arg_no_legend
) {
496 const char *on
, *off
;
497 size_t records
= table_get_rows(table
) - 1;
501 "LOAD = Reflects whether the unit definition was properly loaded.\n"
502 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
503 "SUB = The low-level unit activation state, values depend on unit type.");
504 puts(job_count
? "JOB = Pending job for the unit.\n" : "");
505 on
= ansi_highlight();
508 on
= ansi_highlight_red();
512 if (arg_all
|| strv_contains(arg_states
, "inactive"))
513 printf("%s%zu loaded units listed.%s\n"
514 "To show all installed unit files use 'systemctl list-unit-files'.\n",
516 else if (!arg_states
)
517 printf("%s%zu loaded units listed.%s Pass --all to see loaded but inactive units, too.\n"
518 "To show all installed unit files use 'systemctl list-unit-files'.\n",
521 printf("%zu loaded units listed.\n", records
);
527 static int get_unit_list(
531 UnitInfo
**unit_infos
,
533 sd_bus_message
**_reply
) {
535 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
536 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
537 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
541 bool fallback
= false;
547 r
= sd_bus_message_new_method_call(
550 "org.freedesktop.systemd1",
551 "/org/freedesktop/systemd1",
552 "org.freedesktop.systemd1.Manager",
553 "ListUnitsByPatterns");
555 return bus_log_create_error(r
);
557 r
= sd_bus_message_append_strv(m
, arg_states
);
559 return bus_log_create_error(r
);
561 r
= sd_bus_message_append_strv(m
, patterns
);
563 return bus_log_create_error(r
);
565 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
566 if (r
< 0 && (sd_bus_error_has_name(&error
, SD_BUS_ERROR_UNKNOWN_METHOD
) ||
567 sd_bus_error_has_name(&error
, SD_BUS_ERROR_ACCESS_DENIED
))) {
568 /* Fallback to legacy ListUnitsFiltered method */
570 log_debug_errno(r
, "Failed to list units: %s Falling back to ListUnitsFiltered method.", bus_error_message(&error
, r
));
571 m
= sd_bus_message_unref(m
);
572 sd_bus_error_free(&error
);
574 r
= sd_bus_message_new_method_call(
577 "org.freedesktop.systemd1",
578 "/org/freedesktop/systemd1",
579 "org.freedesktop.systemd1.Manager",
580 "ListUnitsFiltered");
582 return bus_log_create_error(r
);
584 r
= sd_bus_message_append_strv(m
, arg_states
);
586 return bus_log_create_error(r
);
588 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
591 return log_error_errno(r
, "Failed to list units: %s", bus_error_message(&error
, r
));
593 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssssouso)");
595 return bus_log_parse_error(r
);
597 while ((r
= bus_parse_unit_info(reply
, &u
)) > 0) {
600 if (!output_show_unit(&u
, fallback
? patterns
: NULL
))
603 if (!GREEDY_REALLOC(*unit_infos
, size
, c
+1))
606 (*unit_infos
)[c
++] = u
;
609 return bus_log_parse_error(r
);
611 r
= sd_bus_message_exit_container(reply
);
613 return bus_log_parse_error(r
);
615 *_reply
= TAKE_PTR(reply
);
620 static void message_set_freep(Set
**set
) {
621 set_free_with_destructor(*set
, sd_bus_message_unref
);
624 static int get_unit_list_recursive(
627 UnitInfo
**_unit_infos
,
631 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
632 _cleanup_(message_set_freep
) Set
*replies
;
633 sd_bus_message
*reply
;
641 replies
= set_new(NULL
);
645 c
= get_unit_list(bus
, NULL
, patterns
, &unit_infos
, 0, &reply
);
649 r
= set_put(replies
, reply
);
651 sd_bus_message_unref(reply
);
656 _cleanup_strv_free_
char **machines
= NULL
;
659 r
= sd_get_machine_names(&machines
);
661 return log_error_errno(r
, "Failed to get machine names: %m");
663 STRV_FOREACH(i
, machines
) {
664 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*container
= NULL
;
667 r
= sd_bus_open_system_machine(&container
, *i
);
669 log_warning_errno(r
, "Failed to connect to container %s, ignoring: %m", *i
);
673 k
= get_unit_list(container
, *i
, patterns
, &unit_infos
, c
, &reply
);
679 r
= set_put(replies
, reply
);
681 sd_bus_message_unref(reply
);
686 *_machines
= TAKE_PTR(machines
);
690 *_unit_infos
= TAKE_PTR(unit_infos
);
691 *_replies
= TAKE_PTR(replies
);
696 static int expand_names(sd_bus
*bus
, char **names
, const char* suffix
, char ***ret
, bool *ret_expanded
) {
697 _cleanup_strv_free_
char **mangled
= NULL
, **globs
= NULL
;
704 STRV_FOREACH(name
, names
) {
706 UnitNameMangle options
= UNIT_NAME_MANGLE_GLOB
| (arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
);
708 r
= unit_name_mangle_with_suffix(*name
, NULL
, options
, suffix
?: ".service", &t
);
710 return log_error_errno(r
, "Failed to mangle name: %m");
712 if (string_is_glob(t
))
713 r
= strv_consume(&globs
, t
);
715 r
= strv_consume(&mangled
, t
);
720 /* Query the manager only if any of the names are a glob, since
721 * this is fairly expensive */
722 bool expanded
= !strv_isempty(globs
);
724 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
725 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
728 r
= get_unit_list(bus
, NULL
, globs
, &unit_infos
, 0, &reply
);
732 n
= strv_length(mangled
);
735 for (i
= 0; i
< r
; i
++) {
736 if (!GREEDY_REALLOC(mangled
, allocated
, n
+2))
739 mangled
[n
] = strdup(unit_infos
[i
].id
);
748 *ret_expanded
= expanded
;
750 *ret
= TAKE_PTR(mangled
);
754 static int list_dependencies_get_dependencies(sd_bus
*bus
, const char *name
, char ***ret
) {
755 _cleanup_strv_free_
char **deps
= NULL
;
757 static const struct bus_properties_map map
[_DEPENDENCY_MAX
][6] = {
758 [DEPENDENCY_FORWARD
] = {
759 { "Requires", "as", NULL
, 0 },
760 { "Requisite", "as", NULL
, 0 },
761 { "Wants", "as", NULL
, 0 },
762 { "ConsistsOf", "as", NULL
, 0 },
763 { "BindsTo", "as", NULL
, 0 },
766 [DEPENDENCY_REVERSE
] = {
767 { "RequiredBy", "as", NULL
, 0 },
768 { "RequisiteOf", "as", NULL
, 0 },
769 { "WantedBy", "as", NULL
, 0 },
770 { "PartOf", "as", NULL
, 0 },
771 { "BoundBy", "as", NULL
, 0 },
774 [DEPENDENCY_AFTER
] = {
775 { "After", "as", NULL
, 0 },
778 [DEPENDENCY_BEFORE
] = {
779 { "Before", "as", NULL
, 0 },
784 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
785 _cleanup_free_
char *dbus_path
= NULL
;
792 dbus_path
= unit_dbus_path_from_name(name
);
796 r
= bus_map_all_properties(bus
,
797 "org.freedesktop.systemd1",
805 return log_error_errno(r
, "Failed to get properties of %s: %s", name
, bus_error_message(&error
, r
));
807 strv_uniq(deps
); /* Sometimes a unit might have multiple deps on the other unit,
808 * but we still want to show it just once. */
809 *ret
= TAKE_PTR(deps
);
814 static int append_unit_dependencies(sd_bus
*bus
, char **names
, char ***ret
) {
815 _cleanup_strv_free_
char **with_deps
= NULL
;
821 STRV_FOREACH(name
, names
) {
822 _cleanup_strv_free_
char **deps
= NULL
;
824 if (strv_extend(&with_deps
, *name
) < 0)
827 (void) list_dependencies_get_dependencies(bus
, *name
, &deps
);
829 if (strv_extend_strv(&with_deps
, deps
, true) < 0)
833 *ret
= TAKE_PTR(with_deps
);
838 static int maybe_extend_with_unit_dependencies(sd_bus
*bus
, char ***list
) {
842 if (arg_with_dependencies
) {
844 _cleanup_strv_free_
char **list_with_deps
= NULL
;
846 r
= append_unit_dependencies(bus
, *list
, &list_with_deps
);
848 return log_error_errno(r
, "Failed to append unit dependencies: %m");
851 *list
= TAKE_PTR(list_with_deps
);
857 static int list_units(int argc
, char *argv
[], void *userdata
) {
858 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
859 _cleanup_(message_set_freep
) Set
*replies
= NULL
;
860 _cleanup_strv_free_
char **machines
= NULL
;
864 r
= acquire_bus(BUS_MANAGER
, &bus
);
868 (void) pager_open(arg_pager_flags
);
870 if (arg_with_dependencies
) {
871 _cleanup_strv_free_
char **names
= NULL
;
873 r
= append_unit_dependencies(bus
, strv_skip(argv
, 1), &names
);
877 r
= get_unit_list_recursive(bus
, names
, &unit_infos
, &replies
, &machines
);
881 r
= get_unit_list_recursive(bus
, strv_skip(argv
, 1), &unit_infos
, &replies
, &machines
);
886 typesafe_qsort(unit_infos
, r
, compare_unit_info
);
887 return output_units_list(unit_infos
, r
);
890 static int get_triggered_units(
895 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
902 r
= sd_bus_get_property_strv(
904 "org.freedesktop.systemd1",
906 "org.freedesktop.systemd1.Unit",
911 return log_error_errno(r
, "Failed to determine triggers: %s", bus_error_message(&error
, r
));
916 static int get_listening(
918 const char* unit_path
,
921 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
922 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
923 const char *type
, *path
;
926 r
= sd_bus_get_property(
928 "org.freedesktop.systemd1",
930 "org.freedesktop.systemd1.Socket",
936 return log_error_errno(r
, "Failed to get list of listening sockets: %s", bus_error_message(&error
, r
));
938 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ss)");
940 return bus_log_parse_error(r
);
942 while ((r
= sd_bus_message_read(reply
, "(ss)", &type
, &path
)) > 0) {
944 r
= strv_extend(listening
, type
);
948 r
= strv_extend(listening
, path
);
955 return bus_log_parse_error(r
);
957 r
= sd_bus_message_exit_container(reply
);
959 return bus_log_parse_error(r
);
971 /* Note: triggered is a list here, although it almost certainly
972 * will always be one unit. Nevertheless, dbus API allows for multiple
973 * values, so let's follow that. */
976 /* The strv above is shared. free is set only in the first one. */
980 static int socket_info_compare(const struct socket_info
*a
, const struct socket_info
*b
) {
986 if (!a
->machine
&& b
->machine
)
988 if (a
->machine
&& !b
->machine
)
990 if (a
->machine
&& b
->machine
) {
991 r
= strcasecmp(a
->machine
, b
->machine
);
996 r
= strcmp(a
->path
, b
->path
);
998 r
= strcmp(a
->type
, b
->type
);
1003 static int output_sockets_list(struct socket_info
*socket_infos
, unsigned cs
) {
1004 _cleanup_(table_unrefp
) Table
*table
= NULL
;
1005 struct socket_info
*s
;
1006 const char *on
, *off
;
1009 table
= table_new("listen", "type", "units", "activates");
1013 if (!arg_show_types
) {
1014 /* Hide the second (TYPE) column */
1015 r
= table_set_display(table
, (size_t) 0, (size_t) 2, (size_t) 3, (size_t) -1);
1017 return log_error_errno(r
, "Failed to set columns to display: %m");
1020 table_set_header(table
, !arg_no_legend
);
1022 table_set_width(table
, 0);
1025 for (s
= socket_infos
; s
< socket_infos
+ cs
; s
++) {
1026 _cleanup_free_
char *j
= NULL
, *activates
= NULL
;
1030 j
= strjoin(s
->machine
, ":", s
->path
);
1037 activates
= strv_join(s
->triggered
, ", ");
1041 r
= table_add_many(table
,
1043 TABLE_STRING
, s
->type
,
1044 TABLE_STRING
, s
->id
,
1045 TABLE_STRING
, activates
);
1047 return table_log_add_error(r
);
1050 on
= ansi_highlight();
1051 off
= ansi_normal();
1053 on
= ansi_highlight_red();
1054 off
= ansi_normal();
1057 r
= output_table(table
);
1061 if (!arg_no_legend
) {
1062 printf("\n%s%u sockets listed.%s\n", on
, cs
, off
);
1064 printf("Pass --all to see loaded but inactive sockets, too.\n");
1070 static int list_sockets(int argc
, char *argv
[], void *userdata
) {
1071 _cleanup_(message_set_freep
) Set
*replies
= NULL
;
1072 _cleanup_strv_free_
char **machines
= NULL
;
1073 _cleanup_strv_free_
char **sockets_with_suffix
= NULL
;
1074 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
1075 _cleanup_free_
struct socket_info
*socket_infos
= NULL
;
1077 struct socket_info
*s
;
1083 r
= acquire_bus(BUS_MANAGER
, &bus
);
1087 (void) pager_open(arg_pager_flags
);
1089 r
= expand_names(bus
, strv_skip(argv
, 1), ".socket", &sockets_with_suffix
, NULL
);
1093 if (argc
== 1 || sockets_with_suffix
) {
1094 n
= get_unit_list_recursive(bus
, sockets_with_suffix
, &unit_infos
, &replies
, &machines
);
1098 for (u
= unit_infos
; u
< unit_infos
+ n
; u
++) {
1099 _cleanup_strv_free_
char **listening
= NULL
, **triggered
= NULL
;
1102 if (!endswith(u
->id
, ".socket"))
1105 r
= get_triggered_units(bus
, u
->unit_path
, &triggered
);
1109 c
= get_listening(bus
, u
->unit_path
, &listening
);
1115 if (!GREEDY_REALLOC(socket_infos
, size
, cs
+ c
)) {
1120 for (i
= 0; i
< c
; i
++)
1121 socket_infos
[cs
+ i
] = (struct socket_info
) {
1122 .machine
= u
->machine
,
1124 .type
= listening
[i
*2],
1125 .path
= listening
[i
*2 + 1],
1126 .triggered
= triggered
,
1127 .own_triggered
= i
==0,
1130 /* from this point on we will cleanup those socket_infos */
1133 listening
= triggered
= NULL
; /* avoid cleanup */
1136 typesafe_qsort(socket_infos
, cs
, socket_info_compare
);
1139 output_sockets_list(socket_infos
, cs
);
1142 assert(cs
== 0 || socket_infos
);
1143 for (s
= socket_infos
; s
< socket_infos
+ cs
; s
++) {
1146 if (s
->own_triggered
)
1147 strv_free(s
->triggered
);
1153 static int get_next_elapse(
1156 dual_timestamp
*next
) {
1158 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1166 r
= sd_bus_get_property_trivial(
1168 "org.freedesktop.systemd1",
1170 "org.freedesktop.systemd1.Timer",
1171 "NextElapseUSecMonotonic",
1176 return log_error_errno(r
, "Failed to get next elapse time: %s", bus_error_message(&error
, r
));
1178 r
= sd_bus_get_property_trivial(
1180 "org.freedesktop.systemd1",
1182 "org.freedesktop.systemd1.Timer",
1183 "NextElapseUSecRealtime",
1188 return log_error_errno(r
, "Failed to get next elapse time: %s", bus_error_message(&error
, r
));
1194 static int get_last_trigger(
1199 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1206 r
= sd_bus_get_property_trivial(
1208 "org.freedesktop.systemd1",
1210 "org.freedesktop.systemd1.Timer",
1216 return log_error_errno(r
, "Failed to get last trigger time: %s", bus_error_message(&error
, r
));
1222 const char* machine
;
1225 usec_t last_trigger
;
1229 static int timer_info_compare(const struct timer_info
*a
, const struct timer_info
*b
) {
1235 if (!a
->machine
&& b
->machine
)
1237 if (a
->machine
&& !b
->machine
)
1239 if (a
->machine
&& b
->machine
) {
1240 r
= strcasecmp(a
->machine
, b
->machine
);
1245 r
= CMP(a
->next_elapse
, b
->next_elapse
);
1249 return strcmp(a
->id
, b
->id
);
1252 static int output_timers_list(struct timer_info
*timer_infos
, unsigned n
) {
1253 _cleanup_(table_unrefp
) Table
*table
= NULL
;
1254 struct timer_info
*t
;
1255 const char *on
, *off
;
1258 assert(timer_infos
|| n
== 0);
1260 table
= table_new("next", "left", "last", "passed", "unit", "activates");
1264 table_set_header(table
, !arg_no_legend
);
1266 table_set_width(table
, 0);
1269 for (t
= timer_infos
; t
< timer_infos
+ n
; t
++) {
1270 _cleanup_free_
char *j
= NULL
, *activates
= NULL
;
1274 j
= strjoin(t
->machine
, ":", t
->id
);
1281 activates
= strv_join(t
->triggered
, ", ");
1285 r
= table_add_many(table
,
1286 TABLE_TIMESTAMP
, t
->next_elapse
,
1287 TABLE_TIMESTAMP_RELATIVE
, t
->next_elapse
,
1288 TABLE_TIMESTAMP
, t
->last_trigger
,
1289 TABLE_TIMESTAMP_RELATIVE
, t
->last_trigger
,
1291 TABLE_STRING
, activates
);
1293 return table_log_add_error(r
);
1296 on
= ansi_highlight();
1297 off
= ansi_normal();
1299 on
= ansi_highlight_red();
1300 off
= ansi_normal();
1303 r
= output_table(table
);
1307 if (!arg_no_legend
) {
1308 printf("\n%s%u timers listed.%s\n", on
, n
, off
);
1310 printf("Pass --all to see loaded but inactive timers, too.\n");
1316 static usec_t
calc_next_elapse(dual_timestamp
*nw
, dual_timestamp
*next
) {
1322 if (timestamp_is_set(next
->monotonic
)) {
1325 if (next
->monotonic
> nw
->monotonic
)
1326 converted
= nw
->realtime
+ (next
->monotonic
- nw
->monotonic
);
1328 converted
= nw
->realtime
- (nw
->monotonic
- next
->monotonic
);
1330 if (timestamp_is_set(next
->realtime
))
1331 next_elapse
= MIN(converted
, next
->realtime
);
1333 next_elapse
= converted
;
1336 next_elapse
= next
->realtime
;
1341 static int list_timers(int argc
, char *argv
[], void *userdata
) {
1342 _cleanup_(message_set_freep
) Set
*replies
= NULL
;
1343 _cleanup_strv_free_
char **machines
= NULL
;
1344 _cleanup_strv_free_
char **timers_with_suffix
= NULL
;
1345 _cleanup_free_
struct timer_info
*timer_infos
= NULL
;
1346 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
1347 struct timer_info
*t
;
1355 r
= acquire_bus(BUS_MANAGER
, &bus
);
1359 (void) pager_open(arg_pager_flags
);
1361 r
= expand_names(bus
, strv_skip(argv
, 1), ".timer", &timers_with_suffix
, NULL
);
1365 if (argc
== 1 || timers_with_suffix
) {
1366 n
= get_unit_list_recursive(bus
, timers_with_suffix
, &unit_infos
, &replies
, &machines
);
1370 dual_timestamp_get(&nw
);
1372 for (u
= unit_infos
; u
< unit_infos
+ n
; u
++) {
1373 _cleanup_strv_free_
char **triggered
= NULL
;
1374 dual_timestamp next
= DUAL_TIMESTAMP_NULL
;
1377 if (!endswith(u
->id
, ".timer"))
1380 r
= get_triggered_units(bus
, u
->unit_path
, &triggered
);
1384 r
= get_next_elapse(bus
, u
->unit_path
, &next
);
1388 get_last_trigger(bus
, u
->unit_path
, &last
);
1390 if (!GREEDY_REALLOC(timer_infos
, size
, c
+1)) {
1395 m
= calc_next_elapse(&nw
, &next
);
1397 timer_infos
[c
++] = (struct timer_info
) {
1398 .machine
= u
->machine
,
1401 .last_trigger
= last
,
1402 .triggered
= TAKE_PTR(triggered
),
1406 typesafe_qsort(timer_infos
, c
, timer_info_compare
);
1409 output_timers_list(timer_infos
, c
);
1412 for (t
= timer_infos
; t
< timer_infos
+ c
; t
++)
1413 strv_free(t
->triggered
);
1418 static int compare_unit_file_list(const UnitFileList
*a
, const UnitFileList
*b
) {
1419 const char *d1
, *d2
;
1421 d1
= strrchr(a
->path
, '.');
1422 d2
= strrchr(b
->path
, '.');
1427 r
= strcasecmp(d1
, d2
);
1432 return strcasecmp(basename(a
->path
), basename(b
->path
));
1435 static bool output_show_unit_file(const UnitFileList
*u
, char **states
, char **patterns
) {
1438 if (!strv_fnmatch_or_empty(patterns
, basename(u
->path
), FNM_NOESCAPE
))
1441 if (!strv_isempty(arg_types
)) {
1444 dot
= strrchr(u
->path
, '.');
1448 if (!strv_find(arg_types
, dot
+1))
1452 if (!strv_isempty(states
) &&
1453 !strv_find(states
, unit_file_state_to_string(u
->state
)))
1459 static bool show_preset_for_state(UnitFileState state
) {
1460 /* Don't show preset state in those unit file states, it'll only confuse users. */
1461 return !IN_SET(state
,
1464 UNIT_FILE_GENERATED
,
1465 UNIT_FILE_TRANSIENT
);
1468 static int output_unit_file_list(const UnitFileList
*units
, unsigned c
) {
1469 _cleanup_(table_unrefp
) Table
*table
= NULL
;
1470 _cleanup_(unit_file_presets_freep
) UnitFilePresets presets
= {};
1473 table
= table_new("unit file", "state", "vendor preset");
1477 table_set_header(table
, !arg_no_legend
);
1479 table_set_width(table
, 0);
1481 for (const UnitFileList
*u
= units
; u
< units
+ c
; u
++) {
1482 const char *on_underline
= NULL
, *on_unit_color
= NULL
, *id
;
1485 underline
= u
+ 1 < units
+ c
&&
1486 !streq(unit_type_suffix(u
->path
), unit_type_suffix((u
+ 1)->path
));
1489 on_underline
= ansi_underline();
1491 if (IN_SET(u
->state
,
1493 UNIT_FILE_MASKED_RUNTIME
,
1496 on_unit_color
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
1497 else if (IN_SET(u
->state
,
1500 on_unit_color
= underline
? ansi_highlight_green_underline() : ansi_highlight_green();
1502 on_unit_color
= on_underline
;
1504 id
= basename(u
->path
);
1506 r
= table_add_many(table
,
1508 TABLE_SET_COLOR
, strempty(on_underline
),
1509 TABLE_STRING
, unit_file_state_to_string(u
->state
),
1510 TABLE_SET_COLOR
, strempty(on_unit_color
));
1512 return table_log_add_error(r
);
1514 if (show_preset_for_state(u
->state
)) {
1515 const char *unit_preset_str
, *on_preset_color
;
1517 r
= unit_file_query_preset(arg_scope
, arg_root
, id
, &presets
);
1519 unit_preset_str
= "n/a";
1520 on_preset_color
= underline
? on_underline
: ansi_normal();
1521 } else if (r
== 0) {
1522 unit_preset_str
= "disabled";
1523 on_preset_color
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
1525 unit_preset_str
= "enabled";
1526 on_preset_color
= underline
? ansi_highlight_green_underline() : ansi_highlight_green();
1529 r
= table_add_many(table
,
1530 TABLE_STRING
, unit_preset_str
,
1531 TABLE_SET_COLOR
, strempty(on_preset_color
));
1533 r
= table_add_many(table
, TABLE_EMPTY
);
1536 return table_log_add_error(r
);
1539 r
= output_table(table
);
1544 printf("\n%u unit files listed.\n", c
);
1549 static int list_unit_files(int argc
, char *argv
[], void *userdata
) {
1550 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1551 _cleanup_free_ UnitFileList
*units
= NULL
;
1558 bool fallback
= false;
1560 if (install_client_side()) {
1566 h
= hashmap_new(&string_hash_ops
);
1570 r
= unit_file_get_list(arg_scope
, arg_root
, h
, arg_states
, strv_skip(argv
, 1));
1572 unit_file_list_free(h
);
1573 return log_error_errno(r
, "Failed to get unit file list: %m");
1576 n_units
= hashmap_size(h
);
1578 units
= new(UnitFileList
, n_units
?: 1); /* avoid malloc(0) */
1580 unit_file_list_free(h
);
1584 HASHMAP_FOREACH(u
, h
, i
) {
1585 if (!output_show_unit_file(u
, NULL
, NULL
))
1592 assert(c
<= n_units
);
1597 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
1598 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1601 r
= acquire_bus(BUS_MANAGER
, &bus
);
1605 r
= sd_bus_message_new_method_call(
1608 "org.freedesktop.systemd1",
1609 "/org/freedesktop/systemd1",
1610 "org.freedesktop.systemd1.Manager",
1611 "ListUnitFilesByPatterns");
1613 return bus_log_create_error(r
);
1615 r
= sd_bus_message_append_strv(m
, arg_states
);
1617 return bus_log_create_error(r
);
1619 if (arg_with_dependencies
) {
1620 _cleanup_strv_free_
char **names_with_deps
= NULL
;
1622 r
= append_unit_dependencies(bus
, strv_skip(argv
, 1), &names_with_deps
);
1624 return log_error_errno(r
, "Failed to append unit dependencies: %m");
1626 r
= sd_bus_message_append_strv(m
, names_with_deps
);
1628 return bus_log_create_error(r
);
1630 r
= sd_bus_message_append_strv(m
, strv_skip(argv
, 1));
1632 return bus_log_create_error(r
);
1635 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1636 if (r
< 0 && sd_bus_error_has_name(&error
, SD_BUS_ERROR_UNKNOWN_METHOD
)) {
1637 /* Fallback to legacy ListUnitFiles method */
1639 log_debug_errno(r
, "Failed to list unit files: %s Falling back to ListUnitsFiles method.", bus_error_message(&error
, r
));
1640 m
= sd_bus_message_unref(m
);
1641 sd_bus_error_free(&error
);
1643 r
= sd_bus_message_new_method_call(
1646 "org.freedesktop.systemd1",
1647 "/org/freedesktop/systemd1",
1648 "org.freedesktop.systemd1.Manager",
1651 return bus_log_create_error(r
);
1653 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1656 return log_error_errno(r
, "Failed to list unit files: %s", bus_error_message(&error
, r
));
1658 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ss)");
1660 return bus_log_parse_error(r
);
1662 while ((r
= sd_bus_message_read(reply
, "(ss)", &path
, &state
)) > 0) {
1664 if (!GREEDY_REALLOC(units
, size
, c
+ 1))
1667 units
[c
] = (struct UnitFileList
) {
1669 unit_file_state_from_string(state
)
1672 if (output_show_unit_file(&units
[c
],
1673 fallback
? arg_states
: NULL
,
1674 fallback
? strv_skip(argv
, 1) : NULL
))
1679 return bus_log_parse_error(r
);
1681 r
= sd_bus_message_exit_container(reply
);
1683 return bus_log_parse_error(r
);
1686 (void) pager_open(arg_pager_flags
);
1688 typesafe_qsort(units
, c
, compare_unit_file_list
);
1689 r
= output_unit_file_list(units
, c
);
1693 if (install_client_side())
1694 for (unit
= units
; unit
< units
+ c
; unit
++)
1703 static int list_dependencies_print(const char *name
, int level
, unsigned branches
, bool last
) {
1704 _cleanup_free_
char *n
= NULL
;
1705 size_t max_len
= MAX(columns(),20u);
1711 for (i
= level
- 1; i
>= 0; i
--) {
1713 if (len
> max_len
- 3 && !arg_full
) {
1714 printf("%s...\n",max_len
% 2 ? "" : " ");
1717 printf("%s", special_glyph(branches
& (1 << i
) ? SPECIAL_GLYPH_TREE_VERTICAL
: SPECIAL_GLYPH_TREE_SPACE
));
1721 if (len
> max_len
- 3 && !arg_full
) {
1722 printf("%s...\n",max_len
% 2 ? "" : " ");
1726 printf("%s", special_glyph(last
? SPECIAL_GLYPH_TREE_RIGHT
: SPECIAL_GLYPH_TREE_BRANCH
));
1730 printf("%s\n", name
);
1734 n
= ellipsize(name
, max_len
-len
, 100);
1742 static int list_dependencies_compare(char * const *a
, char * const *b
) {
1743 if (unit_name_to_type(*a
) == UNIT_TARGET
&& unit_name_to_type(*b
) != UNIT_TARGET
)
1745 if (unit_name_to_type(*a
) != UNIT_TARGET
&& unit_name_to_type(*b
) == UNIT_TARGET
)
1748 return strcasecmp(*a
, *b
);
1751 static int list_dependencies_one(
1756 unsigned branches
) {
1758 _cleanup_strv_free_
char **deps
= NULL
;
1766 r
= strv_extend(units
, name
);
1770 r
= list_dependencies_get_dependencies(bus
, name
, &deps
);
1774 typesafe_qsort(deps
, strv_length(deps
), list_dependencies_compare
);
1776 STRV_FOREACH(c
, deps
) {
1777 if (strv_contains(*units
, *c
)) {
1780 r
= list_dependencies_print("...", level
+ 1, (branches
<< 1) | (c
[1] == NULL
? 0 : 1), 1);
1790 UnitActiveState active_state
= _UNIT_ACTIVE_STATE_INVALID
;
1793 (void) get_state_one_unit(bus
, *c
, &active_state
);
1795 switch (active_state
) {
1797 case UNIT_RELOADING
:
1798 case UNIT_ACTIVATING
:
1799 on
= ansi_highlight_green();
1803 case UNIT_DEACTIVATING
:
1808 on
= ansi_highlight_red();
1812 printf("%s%s%s ", on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), ansi_normal());
1815 r
= list_dependencies_print(*c
, level
, branches
, c
[1] == NULL
);
1819 if (arg_all
|| unit_name_to_type(*c
) == UNIT_TARGET
) {
1820 r
= list_dependencies_one(bus
, *c
, level
+ 1, units
, (branches
<< 1) | (c
[1] == NULL
? 0 : 1));
1827 strv_remove(*units
, name
);
1832 static int list_dependencies(int argc
, char *argv
[], void *userdata
) {
1833 _cleanup_strv_free_
char **units
= NULL
, **done
= NULL
;
1834 char **u
, **patterns
;
1838 r
= acquire_bus(BUS_MANAGER
, &bus
);
1842 patterns
= strv_skip(argv
, 1);
1843 if (strv_isempty(patterns
)) {
1844 units
= strv_new(SPECIAL_DEFAULT_TARGET
);
1848 r
= expand_names(bus
, patterns
, NULL
, &units
, NULL
);
1850 return log_error_errno(r
, "Failed to expand names: %m");
1853 (void) pager_open(arg_pager_flags
);
1855 STRV_FOREACH(u
, units
) {
1860 r
= list_dependencies_one(bus
, *u
, 0, &done
, 0);
1868 struct machine_info
{
1872 char *control_group
;
1873 uint32_t n_failed_units
;
1878 static const struct bus_properties_map machine_info_property_map
[] = {
1879 { "SystemState", "s", NULL
, offsetof(struct machine_info
, state
) },
1880 { "NJobs", "u", NULL
, offsetof(struct machine_info
, n_jobs
) },
1881 { "NFailedUnits", "u", NULL
, offsetof(struct machine_info
, n_failed_units
) },
1882 { "ControlGroup", "s", NULL
, offsetof(struct machine_info
, control_group
) },
1883 { "UserspaceTimestamp", "t", NULL
, offsetof(struct machine_info
, timestamp
) },
1887 static void machine_info_clear(struct machine_info
*info
) {
1892 free(info
->control_group
);
1896 static void free_machines_list(struct machine_info
*machine_infos
, int n
) {
1902 for (i
= 0; i
< n
; i
++)
1903 machine_info_clear(&machine_infos
[i
]);
1905 free(machine_infos
);
1908 static int compare_machine_info(const struct machine_info
*a
, const struct machine_info
*b
) {
1911 r
= CMP(b
->is_host
, a
->is_host
);
1915 return strcasecmp(a
->name
, b
->name
);
1918 static int get_machine_properties(sd_bus
*bus
, struct machine_info
*mi
) {
1919 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*container
= NULL
;
1925 r
= sd_bus_open_system_machine(&container
, mi
->name
);
1932 r
= bus_map_all_properties(
1934 "org.freedesktop.systemd1",
1935 "/org/freedesktop/systemd1",
1936 machine_info_property_map
,
1947 static bool output_show_machine(const char *name
, char **patterns
) {
1948 return strv_fnmatch_or_empty(patterns
, name
, FNM_NOESCAPE
);
1951 static int get_machine_list(
1953 struct machine_info
**_machine_infos
,
1956 struct machine_info
*machine_infos
= NULL
;
1957 _cleanup_strv_free_
char **m
= NULL
;
1958 _cleanup_free_
char *hn
= NULL
;
1963 hn
= gethostname_malloc();
1967 if (output_show_machine(hn
, patterns
)) {
1968 if (!GREEDY_REALLOC0(machine_infos
, sz
, c
+1))
1971 machine_infos
[c
].is_host
= true;
1972 machine_infos
[c
].name
= TAKE_PTR(hn
);
1974 (void) get_machine_properties(bus
, &machine_infos
[c
]);
1978 r
= sd_get_machine_names(&m
);
1980 return log_error_errno(r
, "Failed to get machine list: %m");
1982 STRV_FOREACH(i
, m
) {
1983 _cleanup_free_
char *class = NULL
;
1985 if (!output_show_machine(*i
, patterns
))
1988 sd_machine_get_class(*i
, &class);
1989 if (!streq_ptr(class, "container"))
1992 if (!GREEDY_REALLOC0(machine_infos
, sz
, c
+1)) {
1993 free_machines_list(machine_infos
, c
);
1997 machine_infos
[c
].is_host
= false;
1998 machine_infos
[c
].name
= strdup(*i
);
1999 if (!machine_infos
[c
].name
) {
2000 free_machines_list(machine_infos
, c
);
2004 (void) get_machine_properties(NULL
, &machine_infos
[c
]);
2008 *_machine_infos
= machine_infos
;
2012 static int output_machines_list(struct machine_info
*machine_infos
, unsigned n
) {
2013 _cleanup_(table_unrefp
) Table
*table
= NULL
;
2014 struct machine_info
*m
;
2015 bool state_missing
= false;
2018 assert(machine_infos
|| n
== 0);
2020 table
= table_new("", "name", "state", "failed", "jobs");
2024 table_set_header(table
, !arg_no_legend
);
2026 /* Hide the 'glyph' column when --plain is requested */
2027 r
= table_hide_column_from_display(table
, 0);
2029 return log_error_errno(r
, "Failed to hide column: %m");
2032 table_set_width(table
, 0);
2034 for (m
= machine_infos
; m
< machine_infos
+ n
; m
++) {
2035 _cleanup_free_
char *mname
= NULL
;
2036 const char *on_state
= "", *on_failed
= "";
2037 bool circle
= false;
2039 if (streq_ptr(m
->state
, "degraded")) {
2040 on_state
= ansi_highlight_red();
2042 } else if (!streq_ptr(m
->state
, "running")) {
2043 on_state
= ansi_highlight_yellow();
2047 if (m
->n_failed_units
> 0)
2048 on_failed
= ansi_highlight_red();
2053 state_missing
= true;
2056 mname
= strjoin(strna(m
->name
), " (host)");
2058 r
= table_add_many(table
,
2059 TABLE_STRING
, circle
? special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
) : " ",
2060 TABLE_SET_COLOR
, on_state
,
2061 TABLE_STRING
, m
->is_host
? mname
: strna(m
->name
),
2062 TABLE_STRING
, strna(m
->state
),
2063 TABLE_SET_COLOR
, on_state
,
2064 TABLE_UINT32
, m
->n_failed_units
,
2065 TABLE_SET_COLOR
, on_failed
,
2066 TABLE_UINT32
, m
->n_jobs
);
2068 return table_log_add_error(r
);
2071 r
= output_table(table
);
2075 if (!arg_no_legend
) {
2077 if (state_missing
&& geteuid() != 0)
2078 printf("Notice: some information only available to privileged users was not shown.\n");
2079 printf("%u machines listed.\n", n
);
2085 static int list_machines(int argc
, char *argv
[], void *userdata
) {
2086 struct machine_info
*machine_infos
= NULL
;
2090 r
= acquire_bus(BUS_MANAGER
, &bus
);
2094 r
= get_machine_list(bus
, &machine_infos
, strv_skip(argv
, 1));
2098 (void) pager_open(arg_pager_flags
);
2100 typesafe_qsort(machine_infos
, r
, compare_machine_info
);
2101 rc
= output_machines_list(machine_infos
, r
);
2102 free_machines_list(machine_infos
, r
);
2107 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
2110 if (streq(key
, "systemd.unit")) {
2111 if (proc_cmdline_value_missing(key
, value
))
2113 if (!unit_name_is_valid(value
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
2114 return log_warning("Unit name specified on %s= is not valid, ignoring: %s", key
, value
);
2116 return free_and_strdup_warn(ret
, key
);
2118 } else if (!value
) {
2119 if (runlevel_to_target(key
))
2120 return free_and_strdup_warn(ret
, key
);
2126 static void emit_cmdline_warning(void) {
2127 if (arg_quiet
|| arg_root
)
2128 /* don't bother checking the commandline if we're operating on a container */
2131 _cleanup_free_
char *override
= NULL
;
2134 r
= proc_cmdline_parse(parse_proc_cmdline_item
, &override
, 0);
2136 log_debug_errno(r
, "Failed to parse kernel command line, ignoring: %m");
2138 log_notice("Note: found \"%s\" on the kernel commandline, which overrides the default unit.",
2142 static int determine_default(char **ret_name
) {
2145 if (install_client_side()) {
2146 r
= unit_file_get_default(arg_scope
, arg_root
, ret_name
);
2148 return log_error_errno(r
, "Failed to get default target: %m");
2153 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2154 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2157 r
= acquire_bus(BUS_MANAGER
, &bus
);
2161 r
= sd_bus_call_method(
2163 "org.freedesktop.systemd1",
2164 "/org/freedesktop/systemd1",
2165 "org.freedesktop.systemd1.Manager",
2171 return log_error_errno(r
, "Failed to get default target: %s", bus_error_message(&error
, r
));
2173 r
= sd_bus_message_read(reply
, "s", &name
);
2175 return bus_log_parse_error(r
);
2177 return free_and_strdup_warn(ret_name
, name
);
2181 static int get_default(int argc
, char *argv
[], void *userdata
) {
2182 _cleanup_free_
char *name
= NULL
;
2185 r
= determine_default(&name
);
2189 printf("%s\n", name
);
2191 emit_cmdline_warning();
2196 static int set_default(int argc
, char *argv
[], void *userdata
) {
2197 _cleanup_free_
char *unit
= NULL
;
2198 UnitFileChange
*changes
= NULL
;
2199 size_t n_changes
= 0;
2205 r
= unit_name_mangle_with_suffix(argv
[1], "set-default",
2206 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
2209 return log_error_errno(r
, "Failed to mangle unit name: %m");
2211 if (install_client_side()) {
2212 r
= unit_file_set_default(arg_scope
, UNIT_FILE_FORCE
, arg_root
, unit
, &changes
, &n_changes
);
2213 unit_file_dump_changes(r
, "set default", changes
, n_changes
, arg_quiet
);
2218 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2219 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2222 polkit_agent_open_maybe();
2224 r
= acquire_bus(BUS_MANAGER
, &bus
);
2228 r
= sd_bus_call_method(
2230 "org.freedesktop.systemd1",
2231 "/org/freedesktop/systemd1",
2232 "org.freedesktop.systemd1.Manager",
2238 return log_error_errno(r
, "Failed to set default target: %s", bus_error_message(&error
, r
));
2240 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
2244 /* Try to reload if enabled */
2246 r
= daemon_reload(argc
, argv
, userdata
);
2251 emit_cmdline_warning();
2254 _cleanup_free_
char *final
= NULL
;
2256 r
= determine_default(&final
);
2260 if (!streq(final
, unit
))
2261 log_notice("Note: \"%s\" is the default unit (possibly a runtime override).", final
);
2265 unit_file_changes_free(changes
, n_changes
);
2270 static int output_waiting_jobs(sd_bus
*bus
, Table
*table
, uint32_t id
, const char *method
, const char *prefix
) {
2271 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2272 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2273 const char *name
, *type
;
2279 r
= sd_bus_call_method(
2281 "org.freedesktop.systemd1",
2282 "/org/freedesktop/systemd1",
2283 "org.freedesktop.systemd1.Manager",
2289 return log_debug_errno(r
, "Failed to get waiting jobs for job %" PRIu32
, id
);
2291 r
= sd_bus_message_enter_container(reply
, 'a', "(usssoo)");
2293 return bus_log_parse_error(r
);
2295 while ((r
= sd_bus_message_read(reply
, "(usssoo)", &other_id
, &name
, &type
, NULL
, NULL
, NULL
)) > 0) {
2296 _cleanup_free_
char *row
= NULL
;
2299 if (asprintf(&row
, "%s %u (%s/%s)", prefix
, other_id
, name
, type
) < 0)
2302 rc
= table_add_many(table
,
2303 TABLE_STRING
, special_glyph(SPECIAL_GLYPH_TREE_RIGHT
),
2308 return table_log_add_error(r
);
2312 return bus_log_parse_error(r
);
2314 r
= sd_bus_message_exit_container(reply
);
2316 return bus_log_parse_error(r
);
2323 const char *name
, *type
, *state
;
2326 static int output_jobs_list(sd_bus
*bus
, const struct job_info
* jobs
, unsigned n
, bool skipped
) {
2327 _cleanup_(table_unrefp
) Table
*table
= NULL
;
2328 const struct job_info
*j
;
2329 const char *on
, *off
;
2332 assert(n
== 0 || jobs
);
2335 if (!arg_no_legend
) {
2336 on
= ansi_highlight_green();
2337 off
= ansi_normal();
2339 printf("%sNo jobs %s.%s\n", on
, skipped
? "listed" : "running", off
);
2344 (void) pager_open(arg_pager_flags
);
2346 table
= table_new("job", "unit", "type", "state");
2350 table_set_header(table
, !arg_no_legend
);
2352 table_set_width(table
, 0);
2354 for (j
= jobs
; j
< jobs
+ n
; j
++) {
2355 if (streq(j
->state
, "running"))
2356 on
= ansi_highlight();
2361 r
= table_add_many(table
,
2363 TABLE_STRING
, j
->name
,
2364 TABLE_SET_COLOR
, on
,
2365 TABLE_STRING
, j
->type
,
2366 TABLE_STRING
, j
->state
,
2367 TABLE_SET_COLOR
, on
);
2369 return table_log_add_error(r
);
2372 output_waiting_jobs(bus
, table
, j
->id
, "GetJobAfter", "\twaiting for job");
2373 if (arg_jobs_before
)
2374 output_waiting_jobs(bus
, table
, j
->id
, "GetJobBefore", "\tblocking job");
2377 r
= table_print(table
, NULL
);
2379 return log_error_errno(r
, "Failed to print the table: %m");
2381 if (!arg_no_legend
) {
2382 on
= ansi_highlight();
2383 off
= ansi_normal();
2385 printf("\n%s%u jobs listed%s.\n", on
, n
, off
);
2391 static bool output_show_job(struct job_info
*job
, char **patterns
) {
2392 return strv_fnmatch_or_empty(patterns
, job
->name
, FNM_NOESCAPE
);
2395 static int list_jobs(int argc
, char *argv
[], void *userdata
) {
2396 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2397 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2398 _cleanup_free_
struct job_info
*jobs
= NULL
;
2399 const char *name
, *type
, *state
;
2400 bool skipped
= false;
2407 r
= acquire_bus(BUS_MANAGER
, &bus
);
2411 r
= sd_bus_call_method(
2413 "org.freedesktop.systemd1",
2414 "/org/freedesktop/systemd1",
2415 "org.freedesktop.systemd1.Manager",
2421 return log_error_errno(r
, "Failed to list jobs: %s", bus_error_message(&error
, r
));
2423 r
= sd_bus_message_enter_container(reply
, 'a', "(usssoo)");
2425 return bus_log_parse_error(r
);
2427 while ((r
= sd_bus_message_read(reply
, "(usssoo)", &id
, &name
, &type
, &state
, NULL
, NULL
)) > 0) {
2428 struct job_info job
= { id
, name
, type
, state
};
2430 if (!output_show_job(&job
, strv_skip(argv
, 1))) {
2435 if (!GREEDY_REALLOC(jobs
, size
, c
+ 1))
2441 return bus_log_parse_error(r
);
2443 r
= sd_bus_message_exit_container(reply
);
2445 return bus_log_parse_error(r
);
2447 (void) pager_open(arg_pager_flags
);
2449 return output_jobs_list(bus
, jobs
, c
, skipped
);
2452 static int cancel_job(int argc
, char *argv
[], void *userdata
) {
2458 return trivial_method(argc
, argv
, userdata
);
2460 r
= acquire_bus(BUS_MANAGER
, &bus
);
2464 polkit_agent_open_maybe();
2466 STRV_FOREACH(name
, strv_skip(argv
, 1)) {
2467 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2471 q
= safe_atou32(*name
, &id
);
2473 return log_error_errno(q
, "Failed to parse job id \"%s\": %m", *name
);
2475 q
= sd_bus_call_method(
2477 "org.freedesktop.systemd1",
2478 "/org/freedesktop/systemd1",
2479 "org.freedesktop.systemd1.Manager",
2485 log_error_errno(q
, "Failed to cancel job %"PRIu32
": %s", id
, bus_error_message(&error
, q
));
2494 static int need_daemon_reload(sd_bus
*bus
, const char *unit
) {
2495 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2499 /* We ignore all errors here, since this is used to show a
2502 /* We don't use unit_dbus_path_from_name() directly since we
2503 * don't want to load the unit if it isn't loaded. */
2505 r
= sd_bus_call_method(
2507 "org.freedesktop.systemd1",
2508 "/org/freedesktop/systemd1",
2509 "org.freedesktop.systemd1.Manager",
2517 r
= sd_bus_message_read(reply
, "o", &path
);
2521 r
= sd_bus_get_property_trivial(
2523 "org.freedesktop.systemd1",
2525 "org.freedesktop.systemd1.Unit",
2535 static void warn_unit_file_changed(const char *name
) {
2538 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.",
2539 ansi_highlight_red(),
2542 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user");
2545 static int unit_file_find_path(LookupPaths
*lp
, const char *unit_name
, char **ret_unit_path
) {
2551 STRV_FOREACH(p
, lp
->search_path
) {
2552 _cleanup_free_
char *path
= NULL
, *lpath
= NULL
;
2555 path
= path_join(*p
, unit_name
);
2559 r
= chase_symlinks(path
, arg_root
, 0, &lpath
, NULL
);
2565 return log_error_errno(r
, "Failed to access path \"%s\": %m", path
);
2568 *ret_unit_path
= TAKE_PTR(lpath
);
2574 *ret_unit_path
= NULL
;
2579 static int unit_find_template_path(
2580 const char *unit_name
,
2582 char **ret_fragment_path
,
2583 char **ret_template
) {
2585 _cleanup_free_
char *t
= NULL
, *f
= NULL
;
2588 /* Returns 1 if a fragment was found, 0 if not found, negative on error. */
2590 r
= unit_file_find_path(lp
, unit_name
, &f
);
2594 if (ret_fragment_path
)
2595 *ret_fragment_path
= TAKE_PTR(f
);
2597 *ret_template
= NULL
;
2598 return r
; /* found a real unit */
2601 r
= unit_name_template(unit_name
, &t
);
2603 if (ret_fragment_path
)
2604 *ret_fragment_path
= NULL
;
2606 *ret_template
= NULL
;
2608 return 0; /* not a template, does not exist */
2611 return log_error_errno(r
, "Failed to determine template name: %m");
2613 r
= unit_file_find_path(lp
, t
, ret_fragment_path
);
2618 *ret_template
= r
> 0 ? TAKE_PTR(t
) : NULL
;
2623 static int unit_find_paths(
2625 const char *unit_name
,
2627 bool force_client_side
,
2628 char **ret_fragment_path
,
2629 char ***ret_dropin_paths
) {
2631 _cleanup_strv_free_
char **dropins
= NULL
;
2632 _cleanup_free_
char *path
= NULL
;
2636 * Finds where the unit is defined on disk. Returns 0 if the unit is not found. Returns 1 if it is
2638 * - the path to the unit in *ret_frament_path, if it exists on disk,
2639 * - and a strv of existing drop-ins in *ret_dropin_paths, if the arg is not NULL and any dropins
2642 * Returns -ERFKILL if the unit is masked, and -EKEYREJECTED if the unit file could not be loaded for
2643 * some reason (the latter only applies if we are going through the service manager).
2647 assert(ret_fragment_path
);
2650 /* Go via the bus to acquire the path, unless we are explicitly told not to, or when the unit name is a template */
2651 if (!force_client_side
&&
2652 !install_client_side() &&
2653 !unit_name_is_valid(unit_name
, UNIT_NAME_TEMPLATE
)) {
2654 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2655 _cleanup_free_
char *load_state
= NULL
, *dbus_path
= NULL
;
2657 dbus_path
= unit_dbus_path_from_name(unit_name
);
2661 r
= sd_bus_get_property_string(
2663 "org.freedesktop.systemd1",
2665 "org.freedesktop.systemd1.Unit",
2670 return log_error_errno(r
, "Failed to get LoadState: %s", bus_error_message(&error
, r
));
2672 if (streq(load_state
, "masked"))
2674 if (streq(load_state
, "not-found")) {
2678 if (!STR_IN_SET(load_state
, "loaded", "bad-setting"))
2679 return -EKEYREJECTED
;
2681 r
= sd_bus_get_property_string(
2683 "org.freedesktop.systemd1",
2685 "org.freedesktop.systemd1.Unit",
2690 return log_error_errno(r
, "Failed to get FragmentPath: %s", bus_error_message(&error
, r
));
2692 if (ret_dropin_paths
) {
2693 r
= sd_bus_get_property_strv(
2695 "org.freedesktop.systemd1",
2697 "org.freedesktop.systemd1.Unit",
2702 return log_error_errno(r
, "Failed to get DropInPaths: %s", bus_error_message(&error
, r
));
2706 _cleanup_set_free_free_ Set
*names
= NULL
;
2708 if (!cached_name_map
) {
2709 r
= unit_file_build_name_map(lp
, NULL
, &cached_id_map
, &cached_name_map
, NULL
);
2714 r
= unit_file_find_fragment(cached_id_map
, cached_name_map
, unit_name
, &_path
, &names
);
2719 path
= strdup(_path
);
2724 if (ret_dropin_paths
) {
2725 r
= unit_file_find_dropin_paths(arg_root
, lp
->search_path
, NULL
,
2733 if (isempty(path
)) {
2734 *ret_fragment_path
= NULL
;
2737 *ret_fragment_path
= TAKE_PTR(path
);
2741 if (ret_dropin_paths
) {
2742 if (!strv_isempty(dropins
)) {
2743 *ret_dropin_paths
= TAKE_PTR(dropins
);
2746 *ret_dropin_paths
= NULL
;
2750 if (r
== 0 && !arg_force
)
2751 log_error("No files found for %s.", unit_name
);
2756 static int get_state_one_unit(sd_bus
*bus
, const char *name
, UnitActiveState
*active_state
) {
2757 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2758 _cleanup_free_
char *buf
= NULL
, *dbus_path
= NULL
;
2759 UnitActiveState state
;
2763 assert(active_state
);
2765 dbus_path
= unit_dbus_path_from_name(name
);
2769 r
= sd_bus_get_property_string(
2771 "org.freedesktop.systemd1",
2773 "org.freedesktop.systemd1.Unit",
2778 return log_error_errno(r
, "Failed to retrieve unit state: %s", bus_error_message(&error
, r
));
2780 state
= unit_active_state_from_string(buf
);
2782 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid unit state '%s' for: %s", buf
, name
);
2784 *active_state
= state
;
2788 static int unit_is_masked(sd_bus
*bus
, LookupPaths
*lp
, const char *name
) {
2789 _cleanup_free_
char *load_state
= NULL
;
2792 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
2793 _cleanup_free_
char *path
= NULL
;
2795 /* A template cannot be loaded, but it can be still masked, so
2796 * we need to use a different method. */
2798 r
= unit_file_find_path(lp
, name
, &path
);
2803 return null_or_empty_path(path
);
2806 r
= unit_load_state(bus
, name
, &load_state
);
2810 return streq(load_state
, "masked");
2813 static int check_triggering_units(sd_bus
*bus
, const char *name
) {
2814 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2815 _cleanup_free_
char *n
= NULL
, *dbus_path
= NULL
, *load_state
= NULL
;
2816 _cleanup_strv_free_
char **triggered_by
= NULL
;
2817 bool print_warning_label
= true;
2818 UnitActiveState active_state
;
2822 r
= unit_name_mangle(name
, 0, &n
);
2824 return log_error_errno(r
, "Failed to mangle unit name: %m");
2826 r
= unit_load_state(bus
, name
, &load_state
);
2830 if (streq(load_state
, "masked"))
2833 dbus_path
= unit_dbus_path_from_name(n
);
2837 r
= sd_bus_get_property_strv(
2839 "org.freedesktop.systemd1",
2841 "org.freedesktop.systemd1.Unit",
2846 return log_error_errno(r
, "Failed to get triggered by array of %s: %s", n
, bus_error_message(&error
, r
));
2848 STRV_FOREACH(i
, triggered_by
) {
2849 r
= get_state_one_unit(bus
, *i
, &active_state
);
2853 if (!IN_SET(active_state
, UNIT_ACTIVE
, UNIT_RELOADING
))
2856 if (print_warning_label
) {
2857 log_warning("Warning: Stopping %s, but it can still be activated by:", n
);
2858 print_warning_label
= false;
2861 log_warning(" %s", *i
);
2867 static const struct {
2868 const char *verb
; /* systemctl verb */
2869 const char *method
; /* Name of the specific D-Bus method */
2870 const char *job_type
; /* Job type when passing to the generic EnqueueUnitJob() method */
2871 } unit_actions
[] = {
2872 { "start", "StartUnit", "start" },
2873 { "stop", "StopUnit", "stop" },
2874 { "condstop", "StopUnit", "stop" }, /* legacy alias */
2875 { "reload", "ReloadUnit", "reload" },
2876 { "restart", "RestartUnit", "restart" },
2877 { "try-restart", "TryRestartUnit", "try-restart" },
2878 { "condrestart", "TryRestartUnit", "try-restart" }, /* legacy alias */
2879 { "reload-or-restart", "ReloadOrRestartUnit", "reload-or-restart" },
2880 { "try-reload-or-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" },
2881 { "reload-or-try-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2882 { "condreload", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2883 { "force-reload", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2886 static const char *verb_to_method(const char *verb
) {
2889 for (i
= 0; i
< ELEMENTSOF(unit_actions
); i
++)
2890 if (streq_ptr(unit_actions
[i
].verb
, verb
))
2891 return unit_actions
[i
].method
;
2896 static const char *verb_to_job_type(const char *verb
) {
2899 for (i
= 0; i
< ELEMENTSOF(unit_actions
); i
++)
2900 if (streq_ptr(unit_actions
[i
].verb
, verb
))
2901 return unit_actions
[i
].job_type
;
2906 static int start_unit_one(
2908 const char *method
, /* When using classic per-job bus methods */
2909 const char *job_type
, /* When using new-style EnqueueUnitJob() */
2912 sd_bus_error
*error
,
2914 BusWaitForUnits
*wu
) {
2916 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2926 log_debug("%s dbus call org.freedesktop.systemd1.Manager %s(%s, %s)",
2927 arg_dry_run
? "Would execute" : "Executing",
2928 method
, name
, mode
);
2933 if (arg_show_transaction
) {
2934 _cleanup_(sd_bus_error_free
) sd_bus_error enqueue_error
= SD_BUS_ERROR_NULL
;
2936 /* Use the new, fancy EnqueueUnitJob() API if the user wants us to print the transaction */
2937 r
= sd_bus_call_method(
2939 "org.freedesktop.systemd1",
2940 "/org/freedesktop/systemd1",
2941 "org.freedesktop.systemd1.Manager",
2946 name
, job_type
, mode
);
2948 if (!sd_bus_error_has_name(&enqueue_error
, SD_BUS_ERROR_UNKNOWN_METHOD
)) {
2949 (void) sd_bus_error_move(error
, &enqueue_error
);
2953 /* Hmm, the API is not yet available. Let's use the classic API instead (see below). */
2954 log_notice("--show-transaction not supported by this service manager, proceeding without.");
2959 r
= sd_bus_message_read(reply
, "uosos", &id
, &path
, &u
, NULL
, &jt
);
2961 return bus_log_parse_error(r
);
2963 log_info("Enqueued anchor job %" PRIu32
" %s/%s.", id
, u
, jt
);
2965 r
= sd_bus_message_enter_container(reply
, 'a', "(uosos)");
2967 return bus_log_parse_error(r
);
2969 r
= sd_bus_message_read(reply
, "(uosos)", &id
, NULL
, &u
, NULL
, &jt
);
2971 return bus_log_parse_error(r
);
2975 log_info("Enqueued auxiliary job %" PRIu32
" %s/%s.", id
, u
, jt
);
2978 r
= sd_bus_message_exit_container(reply
);
2980 return bus_log_parse_error(r
);
2987 r
= sd_bus_call_method(
2989 "org.freedesktop.systemd1",
2990 "/org/freedesktop/systemd1",
2991 "org.freedesktop.systemd1.Manager",
2999 r
= sd_bus_message_read(reply
, "o", &path
);
3001 return bus_log_parse_error(r
);
3004 if (need_daemon_reload(bus
, name
) > 0)
3005 warn_unit_file_changed(name
);
3008 log_debug("Adding %s to the set", path
);
3009 r
= bus_wait_for_jobs_add(w
, path
);
3011 return log_error_errno(r
, "Failed to watch job for %s: %m", name
);
3015 r
= bus_wait_for_units_add_unit(wu
, name
, BUS_WAIT_FOR_INACTIVE
|BUS_WAIT_NO_JOB
, NULL
, NULL
);
3017 return log_error_errno(r
, "Failed to watch unit %s: %m", name
);
3023 /* There's always a fallback possible for legacy actions. */
3024 if (arg_action
!= ACTION_SYSTEMCTL
)
3027 log_error_errno(r
, "Failed to %s %s: %s", job_type
, name
, bus_error_message(error
, r
));
3029 if (!sd_bus_error_has_name(error
, BUS_ERROR_NO_SUCH_UNIT
) &&
3030 !sd_bus_error_has_name(error
, BUS_ERROR_UNIT_MASKED
) &&
3031 !sd_bus_error_has_name(error
, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE
))
3032 log_error("See %s logs and 'systemctl%s status%s %s' for details.",
3033 arg_scope
== UNIT_FILE_SYSTEM
? "system" : "user",
3034 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user",
3035 name
[0] == '-' ? " --" : "",
3041 static const struct {
3045 } action_table
[_ACTION_MAX
] = {
3046 [ACTION_HALT
] = { SPECIAL_HALT_TARGET
, "halt", "replace-irreversibly" },
3047 [ACTION_POWEROFF
] = { SPECIAL_POWEROFF_TARGET
, "poweroff", "replace-irreversibly" },
3048 [ACTION_REBOOT
] = { SPECIAL_REBOOT_TARGET
, "reboot", "replace-irreversibly" },
3049 [ACTION_KEXEC
] = { SPECIAL_KEXEC_TARGET
, "kexec", "replace-irreversibly" },
3050 [ACTION_RUNLEVEL2
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
3051 [ACTION_RUNLEVEL3
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
3052 [ACTION_RUNLEVEL4
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
3053 [ACTION_RUNLEVEL5
] = { SPECIAL_GRAPHICAL_TARGET
, NULL
, "isolate" },
3054 [ACTION_RESCUE
] = { SPECIAL_RESCUE_TARGET
, "rescue", "isolate" },
3055 [ACTION_EMERGENCY
] = { SPECIAL_EMERGENCY_TARGET
, "emergency", "isolate" },
3056 [ACTION_DEFAULT
] = { SPECIAL_DEFAULT_TARGET
, "default", "isolate" },
3057 [ACTION_EXIT
] = { SPECIAL_EXIT_TARGET
, "exit", "replace-irreversibly" },
3058 [ACTION_SUSPEND
] = { SPECIAL_SUSPEND_TARGET
, "suspend", "replace-irreversibly" },
3059 [ACTION_HIBERNATE
] = { SPECIAL_HIBERNATE_TARGET
, "hibernate", "replace-irreversibly" },
3060 [ACTION_HYBRID_SLEEP
] = { SPECIAL_HYBRID_SLEEP_TARGET
, "hybrid-sleep", "replace-irreversibly" },
3061 [ACTION_SUSPEND_THEN_HIBERNATE
] = { SPECIAL_SUSPEND_THEN_HIBERNATE_TARGET
, "suspend-then-hibernate", "replace-irreversibly" },
3064 static enum action
verb_to_action(const char *verb
) {
3067 for (i
= 0; i
< _ACTION_MAX
; i
++)
3068 if (streq_ptr(action_table
[i
].verb
, verb
))
3071 return _ACTION_INVALID
;
3074 static const char** make_extra_args(const char *extra_args
[static 4]) {
3079 if (arg_scope
!= UNIT_FILE_SYSTEM
)
3080 extra_args
[n
++] = "--user";
3082 if (arg_transport
== BUS_TRANSPORT_REMOTE
) {
3083 extra_args
[n
++] = "-H";
3084 extra_args
[n
++] = arg_host
;
3085 } else if (arg_transport
== BUS_TRANSPORT_MACHINE
) {
3086 extra_args
[n
++] = "-M";
3087 extra_args
[n
++] = arg_host
;
3089 assert(arg_transport
== BUS_TRANSPORT_LOCAL
);
3091 extra_args
[n
] = NULL
;
3095 static int start_unit(int argc
, char *argv
[], void *userdata
) {
3096 _cleanup_(bus_wait_for_units_freep
) BusWaitForUnits
*wu
= NULL
;
3097 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
3098 const char *method
, *job_type
, *mode
, *one_name
, *suffix
= NULL
;
3099 _cleanup_free_
char **stopped_units
= NULL
; /* Do not use _cleanup_strv_free_ */
3100 _cleanup_strv_free_
char **names
= NULL
;
3101 int r
, ret
= EXIT_SUCCESS
;
3105 if (arg_wait
&& !STR_IN_SET(argv
[0], "start", "restart"))
3106 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3107 "--wait may only be used with the 'start' or 'restart' commands.");
3109 /* we cannot do sender tracking on the private bus, so we need the full
3110 * one for RefUnit to implement --wait */
3111 r
= acquire_bus(arg_wait
? BUS_FULL
: BUS_MANAGER
, &bus
);
3115 ask_password_agent_open_maybe();
3116 polkit_agent_open_maybe();
3118 if (arg_action
== ACTION_SYSTEMCTL
) {
3121 action
= verb_to_action(argv
[0]);
3123 if (action
!= _ACTION_INVALID
) {
3124 /* A command in style "systemctl reboot", "systemctl poweroff", … */
3125 method
= "StartUnit";
3127 mode
= action_table
[action
].mode
;
3128 one_name
= action_table
[action
].target
;
3130 if (streq(argv
[0], "isolate")) {
3131 /* A "systemctl isolate <unit1> <unit2> …" command */
3132 method
= "StartUnit";
3137 /* A command in style of "systemctl start <unit1> <unit2> …", "sysemctl stop <unit1> <unit2> …" and so on */
3138 method
= verb_to_method(argv
[0]);
3139 job_type
= verb_to_job_type(argv
[0]);
3140 mode
= arg_job_mode
;
3145 /* A SysV legacy command such as "halt", "reboot", "poweroff", … */
3146 assert(arg_action
>= 0 && arg_action
< _ACTION_MAX
);
3147 assert(action_table
[arg_action
].target
);
3148 assert(action_table
[arg_action
].mode
);
3150 method
= "StartUnit";
3152 mode
= action_table
[arg_action
].mode
;
3153 one_name
= action_table
[arg_action
].target
;
3157 names
= strv_new(one_name
);
3163 r
= expand_names(bus
, strv_skip(argv
, 1), suffix
, &names
, &expanded
);
3165 return log_error_errno(r
, "Failed to expand names: %m");
3167 if (!arg_all
&& expanded
&& streq(job_type
, "start") && !arg_quiet
) {
3168 log_warning("Warning: %ssystemctl start called with a glob pattern.%s",
3169 ansi_highlight_red(),
3171 log_notice("Hint: unit globs expand to loaded units, so start will usually have no effect.\n"
3172 " Passing --all will also load units which are pulled in by other units.\n"
3173 " See systemctl(1) for more details.");
3177 if (!arg_no_block
) {
3178 r
= bus_wait_for_jobs_new(bus
, &w
);
3180 return log_error_errno(r
, "Could not watch jobs: %m");
3184 r
= sd_bus_call_method_async(
3187 "org.freedesktop.systemd1",
3188 "/org/freedesktop/systemd1",
3189 "org.freedesktop.systemd1.Manager",
3194 return log_error_errno(r
, "Failed to enable subscription: %m");
3196 r
= bus_wait_for_units_new(bus
, &wu
);
3198 return log_error_errno(r
, "Failed to allocate unit watch context: %m");
3201 STRV_FOREACH(name
, names
) {
3202 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3204 r
= start_unit_one(bus
, method
, job_type
, *name
, mode
, &error
, w
, wu
);
3205 if (ret
== EXIT_SUCCESS
&& r
< 0)
3206 ret
= translate_bus_error_to_exit_status(r
, &error
);
3208 if (r
>= 0 && streq(method
, "StopUnit")) {
3209 r
= strv_push(&stopped_units
, *name
);
3215 if (!arg_no_block
) {
3216 const char* extra_args
[4];
3218 r
= bus_wait_for_jobs(w
, arg_quiet
, make_extra_args(extra_args
));
3222 /* When stopping units, warn if they can still be triggered by
3223 * another active unit (socket, path, timer) */
3225 STRV_FOREACH(name
, stopped_units
)
3226 (void) check_triggering_units(bus
, *name
);
3230 r
= bus_wait_for_units_run(wu
);
3232 return log_error_errno(r
, "Failed to wait for units: %m");
3233 if (r
== BUS_WAIT_FAILURE
&& ret
== EXIT_SUCCESS
)
3241 static int logind_set_wall_message(void) {
3242 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3244 _cleanup_free_
char *m
= NULL
;
3247 r
= acquire_bus(BUS_FULL
, &bus
);
3251 m
= strv_join(arg_wall
, " ");
3255 log_debug("%s wall message \"%s\".", arg_dry_run
? "Would set" : "Setting", m
);
3259 r
= sd_bus_call_method(
3261 "org.freedesktop.login1",
3262 "/org/freedesktop/login1",
3263 "org.freedesktop.login1.Manager",
3272 return log_warning_errno(r
, "Failed to set wall message, ignoring: %s", bus_error_message(&error
, r
));
3277 /* Ask systemd-logind, which might grant access to unprivileged users through polkit */
3278 static int logind_reboot(enum action a
) {
3280 static const struct {
3282 const char *description
;
3283 } actions
[_ACTION_MAX
] = {
3284 [ACTION_POWEROFF
] = { "PowerOff", "power off system" },
3285 [ACTION_REBOOT
] = { "Reboot", "reboot system" },
3286 [ACTION_HALT
] = { "Halt", "halt system" },
3287 [ACTION_SUSPEND
] = { "Suspend", "suspend system" },
3288 [ACTION_HIBERNATE
] = { "Hibernate", "hibernate system" },
3289 [ACTION_HYBRID_SLEEP
] = { "HybridSleep", "put system into hybrid sleep" },
3290 [ACTION_SUSPEND_THEN_HIBERNATE
] = { "SuspendThenHibernate", "suspend system, hibernate later" },
3293 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3297 if (a
< 0 || a
>= _ACTION_MAX
|| !actions
[a
].method
)
3300 r
= acquire_bus(BUS_FULL
, &bus
);
3304 polkit_agent_open_maybe();
3305 (void) logind_set_wall_message();
3307 log_debug("%s org.freedesktop.login1.Manager %s dbus call.", arg_dry_run
? "Would execute" : "Executing", actions
[a
].method
);
3312 r
= sd_bus_call_method(
3314 "org.freedesktop.login1",
3315 "/org/freedesktop/login1",
3316 "org.freedesktop.login1.Manager",
3320 "b", arg_ask_password
);
3322 return log_error_errno(r
, "Failed to %s via logind: %s", actions
[a
].description
, bus_error_message(&error
, r
));
3330 static int logind_check_inhibitors(enum action a
) {
3332 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
3333 _cleanup_strv_free_
char **sessions
= NULL
;
3334 const char *what
, *who
, *why
, *mode
;
3341 if (arg_ignore_inhibitors
|| arg_force
> 0)
3353 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
3356 r
= acquire_bus(BUS_FULL
, &bus
);
3360 r
= sd_bus_call_method(
3362 "org.freedesktop.login1",
3363 "/org/freedesktop/login1",
3364 "org.freedesktop.login1.Manager",
3370 /* If logind is not around, then there are no inhibitors... */
3373 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssuu)");
3375 return bus_log_parse_error(r
);
3377 while ((r
= sd_bus_message_read(reply
, "(ssssuu)", &what
, &who
, &why
, &mode
, &uid
, &pid
)) > 0) {
3378 _cleanup_free_
char *comm
= NULL
, *user
= NULL
;
3379 _cleanup_strv_free_
char **sv
= NULL
;
3381 if (!streq(mode
, "block"))
3384 sv
= strv_split(what
, ":");
3388 if (!pid_is_valid((pid_t
) pid
))
3389 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Invalid PID "PID_FMT
".", (pid_t
) pid
);
3391 if (!strv_contains(sv
,
3396 ACTION_KEXEC
) ? "shutdown" : "sleep"))
3399 get_process_comm(pid
, &comm
);
3400 user
= uid_to_name(uid
);
3402 log_warning("Operation inhibited by \"%s\" (PID "PID_FMT
" \"%s\", user %s), reason is \"%s\".",
3403 who
, (pid_t
) pid
, strna(comm
), strna(user
), why
);
3408 return bus_log_parse_error(r
);
3410 r
= sd_bus_message_exit_container(reply
);
3412 return bus_log_parse_error(r
);
3414 /* Check for current sessions */
3415 sd_get_sessions(&sessions
);
3416 STRV_FOREACH(s
, sessions
) {
3417 _cleanup_free_
char *type
= NULL
, *tty
= NULL
, *seat
= NULL
, *user
= NULL
, *service
= NULL
, *class = NULL
;
3419 if (sd_session_get_uid(*s
, &uid
) < 0 || uid
== getuid())
3422 if (sd_session_get_class(*s
, &class) < 0 || !streq(class, "user"))
3425 if (sd_session_get_type(*s
, &type
) < 0 || !STR_IN_SET(type
, "x11", "wayland", "tty", "mir"))
3428 sd_session_get_tty(*s
, &tty
);
3429 sd_session_get_seat(*s
, &seat
);
3430 sd_session_get_service(*s
, &service
);
3431 user
= uid_to_name(uid
);
3433 log_warning("User %s is logged in on %s.", strna(user
), isempty(tty
) ? (isempty(seat
) ? strna(service
) : seat
) : tty
);
3440 log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'systemctl %s -i'.",
3441 action_table
[a
].verb
);
3449 static int prepare_firmware_setup(void) {
3451 if (!arg_firmware_setup
)
3455 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3459 r
= acquire_bus(BUS_FULL
, &bus
);
3463 r
= sd_bus_call_method(
3465 "org.freedesktop.login1",
3466 "/org/freedesktop/login1",
3467 "org.freedesktop.login1.Manager",
3468 "SetRebootToFirmwareSetup",
3473 return log_error_errno(r
, "Cannot indicate to EFI to boot into setup mode: %s", bus_error_message(&error
, r
));
3477 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3478 "Booting into firmware setup not supported.");
3482 static int prepare_boot_loader_menu(void) {
3484 if (arg_boot_loader_menu
== USEC_INFINITY
)
3488 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3492 r
= acquire_bus(BUS_FULL
, &bus
);
3496 r
= sd_bus_call_method(
3498 "org.freedesktop.login1",
3499 "/org/freedesktop/login1",
3500 "org.freedesktop.login1.Manager",
3501 "SetRebootToBootLoaderMenu",
3504 "t", arg_boot_loader_menu
);
3506 return log_error_errno(r
, "Cannot indicate to boot loader to enter boot loader entry menu: %s", bus_error_message(&error
, r
));
3510 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3511 "Booting into boot loader menu not supported.");
3515 static int prepare_boot_loader_entry(void) {
3517 if (!arg_boot_loader_entry
)
3521 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3525 r
= acquire_bus(BUS_FULL
, &bus
);
3529 r
= sd_bus_call_method(
3531 "org.freedesktop.login1",
3532 "/org/freedesktop/login1",
3533 "org.freedesktop.login1.Manager",
3534 "SetRebootToBootLoaderEntry",
3537 "s", arg_boot_loader_entry
);
3539 return log_error_errno(r
, "Cannot set boot into loader entry '%s': %s", arg_boot_loader_entry
, bus_error_message(&error
, r
));
3543 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3544 "Booting into boot loader entry not supported.");
3548 static int load_kexec_kernel(void) {
3549 _cleanup_(boot_config_free
) BootConfig config
= {};
3550 _cleanup_free_
char *kernel
= NULL
, *initrd
= NULL
, *options
= NULL
;
3555 if (kexec_loaded()) {
3556 log_debug("Kexec kernel already loaded.");
3560 if (access(KEXEC
, X_OK
) < 0)
3561 return log_error_errno(errno
, KEXEC
" is not available: %m");
3563 r
= boot_entries_load_config_auto(NULL
, NULL
, &config
);
3565 /* The call doesn't log about ENOKEY, let's do so here. */
3566 return log_error_errno(r
,
3567 "No kexec kernel loaded and autodetection failed.\n%s",
3569 ? "Cannot automatically load kernel: ESP partition mount point not found."
3570 : "Automatic loading works only on systems booted with EFI.");
3574 e
= boot_config_default_entry(&config
);
3576 return log_error_errno(SYNTHETIC_ERRNO(ENOENT
),
3577 "No boot loader entry suitable as default, refusing to guess.");
3579 log_debug("Found default boot loader entry in file \"%s\"", e
->path
);
3582 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3583 "Boot entry does not refer to Linux kernel, which is not supported currently.");
3584 if (strv_length(e
->initrd
) > 1)
3585 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3586 "Boot entry specifies multiple initrds, which is not supported currently.");
3588 kernel
= path_join(e
->root
, e
->kernel
);
3592 if (!strv_isempty(e
->initrd
)) {
3593 initrd
= path_join(e
->root
, e
->initrd
[0]);
3598 options
= strv_join(e
->options
, " ");
3602 log_full(arg_quiet
? LOG_DEBUG
: LOG_INFO
,
3603 "%s "KEXEC
" --load \"%s\" --append \"%s\"%s%s%s",
3604 arg_dry_run
? "Would run" : "Running",
3607 initrd
? " --initrd \"" : NULL
, strempty(initrd
), initrd
? "\"" : "");
3611 r
= safe_fork("(kexec)", FORK_WAIT
|FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
, &pid
);
3615 const char* const args
[] = {
3618 "--append", options
,
3619 initrd
? "--initrd" : NULL
, initrd
,
3624 execv(args
[0], (char * const *) args
);
3625 _exit(EXIT_FAILURE
);
3631 static int set_exit_code(uint8_t code
) {
3632 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3636 r
= acquire_bus(BUS_MANAGER
, &bus
);
3640 r
= sd_bus_call_method(
3642 "org.freedesktop.systemd1",
3643 "/org/freedesktop/systemd1",
3644 "org.freedesktop.systemd1.Manager",
3650 return log_error_errno(r
, "Failed to set exit code: %s", bus_error_message(&error
, r
));
3655 static int start_special(int argc
, char *argv
[], void *userdata
) {
3658 bool termination_action
; /* an action that terminates the manager,
3659 * can be performed also by signal. */
3663 a
= verb_to_action(argv
[0]);
3665 r
= logind_check_inhibitors(a
);
3669 if (arg_force
>= 2) {
3675 r
= prepare_firmware_setup();
3679 r
= prepare_boot_loader_menu();
3683 r
= prepare_boot_loader_entry();
3687 if (a
== ACTION_REBOOT
&& argc
> 1) {
3688 r
= update_reboot_parameter_and_warn(argv
[1], false);
3692 } else if (a
== ACTION_KEXEC
) {
3693 r
= load_kexec_kernel();
3694 if (r
< 0 && arg_force
>= 1)
3695 log_notice("Failed to load kexec kernel, continuing without.");
3699 } else if (a
== ACTION_EXIT
&& argc
> 1) {
3702 /* If the exit code is not given on the command line,
3703 * don't reset it to zero: just keep it as it might
3704 * have been set previously. */
3706 r
= safe_atou8(argv
[1], &code
);
3708 return log_error_errno(r
, "Invalid exit code.");
3710 r
= set_exit_code(code
);
3715 termination_action
= IN_SET(a
,
3719 if (termination_action
&& arg_force
>= 2)
3722 if (arg_force
>= 1 &&
3723 (termination_action
|| IN_SET(a
, ACTION_KEXEC
, ACTION_EXIT
)))
3724 r
= trivial_method(argc
, argv
, userdata
);
3726 /* First try logind, to allow authentication with polkit */
3733 ACTION_HYBRID_SLEEP
,
3734 ACTION_SUSPEND_THEN_HIBERNATE
)) {
3736 r
= logind_reboot(a
);
3739 if (IN_SET(r
, -EOPNOTSUPP
, -EINPROGRESS
))
3740 /* requested operation is not supported or already in progress */
3743 /* On all other errors, try low-level operation. In order to minimize the difference between
3744 * operation with and without logind, we explicitly enable non-blocking mode for this, as
3745 * logind's shutdown operations are always non-blocking. */
3747 arg_no_block
= true;
3749 } else if (IN_SET(a
, ACTION_EXIT
, ACTION_KEXEC
))
3750 /* Since exit/kexec are so close in behaviour to power-off/reboot, let's also make them
3751 * asynchronous, in order to not confuse the user needlessly with unexpected behaviour. */
3752 arg_no_block
= true;
3754 r
= start_unit(argc
, argv
, userdata
);
3757 if (termination_action
&& arg_force
< 2 &&
3758 IN_SET(r
, -ENOENT
, -ETIMEDOUT
))
3759 log_notice("It is possible to perform action directly, see discussion of --force --force in man:systemctl(1).");
3764 static int start_system_special(int argc
, char *argv
[], void *userdata
) {
3765 /* Like start_special above, but raises an error when running in user mode */
3767 if (arg_scope
!= UNIT_FILE_SYSTEM
)
3768 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3769 "Bad action for %s mode.",
3770 arg_scope
== UNIT_FILE_GLOBAL
? "--global" : "--user");
3772 return start_special(argc
, argv
, userdata
);
3775 static int check_unit_generic(int code
, const UnitActiveState good_states
[], int nb_states
, char **args
) {
3776 _cleanup_strv_free_
char **names
= NULL
;
3777 UnitActiveState active_state
;
3783 r
= acquire_bus(BUS_MANAGER
, &bus
);
3787 r
= expand_names(bus
, args
, NULL
, &names
, NULL
);
3789 return log_error_errno(r
, "Failed to expand names: %m");
3791 STRV_FOREACH(name
, names
) {
3792 r
= get_state_one_unit(bus
, *name
, &active_state
);
3797 puts(unit_active_state_to_string(active_state
));
3799 for (i
= 0; i
< nb_states
; ++i
)
3800 if (good_states
[i
] == active_state
)
3804 /* use the given return code for the case that we won't find
3805 * any unit which matches the list */
3806 return found
? 0 : code
;
3809 static int check_unit_active(int argc
, char *argv
[], void *userdata
) {
3810 static const UnitActiveState states
[] = {
3815 /* According to LSB: 3, "program is not running" */
3816 return check_unit_generic(EXIT_PROGRAM_NOT_RUNNING
, states
, ELEMENTSOF(states
), strv_skip(argv
, 1));
3819 static int check_unit_failed(int argc
, char *argv
[], void *userdata
) {
3820 static const UnitActiveState states
[] = {
3824 return check_unit_generic(EXIT_PROGRAM_DEAD_AND_PID_EXISTS
, states
, ELEMENTSOF(states
), strv_skip(argv
, 1));
3827 static int kill_unit(int argc
, char *argv
[], void *userdata
) {
3828 _cleanup_strv_free_
char **names
= NULL
;
3829 char *kill_who
= NULL
, **name
;
3833 r
= acquire_bus(BUS_MANAGER
, &bus
);
3837 polkit_agent_open_maybe();
3840 arg_kill_who
= "all";
3842 /* --fail was specified */
3843 if (streq(arg_job_mode
, "fail"))
3844 kill_who
= strjoina(arg_kill_who
, "-fail");
3846 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
3848 return log_error_errno(r
, "Failed to expand names: %m");
3850 STRV_FOREACH(name
, names
) {
3851 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3853 q
= sd_bus_call_method(
3855 "org.freedesktop.systemd1",
3856 "/org/freedesktop/systemd1",
3857 "org.freedesktop.systemd1.Manager",
3861 "ssi", *name
, kill_who
? kill_who
: arg_kill_who
, arg_signal
);
3863 log_error_errno(q
, "Failed to kill unit %s: %s", *name
, bus_error_message(&error
, q
));
3872 static int clean_or_freeze_unit(int argc
, char *argv
[], void *userdata
) {
3873 _cleanup_(bus_wait_for_units_freep
) BusWaitForUnits
*w
= NULL
;
3874 _cleanup_strv_free_
char **names
= NULL
;
3875 int r
, ret
= EXIT_SUCCESS
;
3880 r
= acquire_bus(BUS_FULL
, &bus
);
3884 polkit_agent_open_maybe();
3886 if (!arg_clean_what
) {
3887 arg_clean_what
= strv_new("cache", "runtime");
3888 if (!arg_clean_what
)
3892 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
3894 return log_error_errno(r
, "Failed to expand names: %m");
3896 if (!arg_no_block
) {
3897 r
= bus_wait_for_units_new(bus
, &w
);
3899 return log_error_errno(r
, "Failed to allocate unit waiter: %m");
3902 if (streq(argv
[0], "clean"))
3903 method
= "CleanUnit";
3904 else if (streq(argv
[0], "freeze"))
3905 method
= "FreezeUnit";
3906 else if (streq(argv
[0], "thaw"))
3907 method
= "ThawUnit";
3909 STRV_FOREACH(name
, names
) {
3910 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3911 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
3914 /* If we shall wait for the cleaning to complete, let's add a ref on the unit first */
3915 r
= sd_bus_call_method(
3917 "org.freedesktop.systemd1",
3918 "/org/freedesktop/systemd1",
3919 "org.freedesktop.systemd1.Manager",
3925 log_error_errno(r
, "Failed to add reference to unit %s: %s", *name
, bus_error_message(&error
, r
));
3926 if (ret
== EXIT_SUCCESS
)
3932 r
= sd_bus_message_new_method_call(
3935 "org.freedesktop.systemd1",
3936 "/org/freedesktop/systemd1",
3937 "org.freedesktop.systemd1.Manager",
3940 return bus_log_create_error(r
);
3942 r
= sd_bus_message_append(m
, "s", *name
);
3944 return bus_log_create_error(r
);
3946 if (streq(method
, "CleanUnit")) {
3947 r
= sd_bus_message_append_strv(m
, arg_clean_what
);
3949 return bus_log_create_error(r
);
3952 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
3954 log_error_errno(r
, "Failed to %s unit %s: %s", argv
[0], *name
, bus_error_message(&error
, r
));
3955 if (ret
== EXIT_SUCCESS
) {
3962 r
= bus_wait_for_units_add_unit(w
, *name
, BUS_WAIT_REFFED
|BUS_WAIT_FOR_MAINTENANCE_END
, NULL
, NULL
);
3964 return log_error_errno(r
, "Failed to watch unit %s: %m", *name
);
3968 r
= bus_wait_for_units_run(w
);
3970 return log_error_errno(r
, "Failed to wait for units: %m");
3971 if (r
== BUS_WAIT_FAILURE
)
3977 typedef struct ExecStatusInfo
{
3985 usec_t start_timestamp
;
3986 usec_t exit_timestamp
;
3991 ExecCommandFlags flags
;
3993 LIST_FIELDS(struct ExecStatusInfo
, exec
);
3996 static void exec_status_info_free(ExecStatusInfo
*i
) {
4005 static int exec_status_info_deserialize(sd_bus_message
*m
, ExecStatusInfo
*i
, bool is_ex_prop
) {
4006 _cleanup_strv_free_
char **ex_opts
= NULL
;
4007 uint64_t start_timestamp
, exit_timestamp
, start_timestamp_monotonic
, exit_timestamp_monotonic
;
4010 int32_t code
, status
;
4016 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_STRUCT
, is_ex_prop
? "sasasttttuii" : "sasbttttuii");
4018 return bus_log_parse_error(r
);
4022 r
= sd_bus_message_read(m
, "s", &path
);
4024 return bus_log_parse_error(r
);
4026 i
->path
= strdup(path
);
4030 r
= sd_bus_message_read_strv(m
, &i
->argv
);
4032 return bus_log_parse_error(r
);
4034 r
= is_ex_prop
? sd_bus_message_read_strv(m
, &ex_opts
) : sd_bus_message_read(m
, "b", &ignore
);
4036 return bus_log_parse_error(r
);
4038 r
= sd_bus_message_read(m
,
4040 &start_timestamp
, &start_timestamp_monotonic
,
4041 &exit_timestamp
, &exit_timestamp_monotonic
,
4045 return bus_log_parse_error(r
);
4048 r
= exec_command_flags_from_strv(ex_opts
, &i
->flags
);
4050 return log_error_errno(r
, "Failed to convert strv to ExecCommandFlags: %m");
4052 i
->ignore
= FLAGS_SET(i
->flags
, EXEC_COMMAND_IGNORE_FAILURE
);
4056 i
->start_timestamp
= (usec_t
) start_timestamp
;
4057 i
->exit_timestamp
= (usec_t
) exit_timestamp
;
4058 i
->pid
= (pid_t
) pid
;
4062 r
= sd_bus_message_exit_container(m
);
4064 return bus_log_parse_error(r
);
4069 typedef struct UnitCondition
{
4076 LIST_FIELDS(struct UnitCondition
, conditions
);
4079 static void unit_condition_free(UnitCondition
*c
) {
4088 DEFINE_TRIVIAL_CLEANUP_FUNC(UnitCondition
*, unit_condition_free
);
4090 typedef struct UnitStatusInfo
{
4092 const char *load_state
;
4093 const char *active_state
;
4094 const char *freezer_state
;
4095 const char *sub_state
;
4096 const char *unit_file_state
;
4097 const char *unit_file_preset
;
4099 const char *description
;
4100 const char *following
;
4102 char **documentation
;
4104 const char *fragment_path
;
4105 const char *source_path
;
4106 const char *control_group
;
4108 char **dropin_paths
;
4110 char **triggered_by
;
4113 const char *load_error
;
4116 usec_t inactive_exit_timestamp
;
4117 usec_t inactive_exit_timestamp_monotonic
;
4118 usec_t active_enter_timestamp
;
4119 usec_t active_exit_timestamp
;
4120 usec_t inactive_enter_timestamp
;
4122 bool need_daemon_reload
;
4128 const char *status_text
;
4129 const char *pid_file
;
4133 usec_t start_timestamp
;
4134 usec_t exit_timestamp
;
4136 int exit_code
, exit_status
;
4138 const char *log_namespace
;
4140 usec_t condition_timestamp
;
4141 bool condition_result
;
4142 LIST_HEAD(UnitCondition
, conditions
);
4144 usec_t assert_timestamp
;
4146 bool failed_assert_trigger
;
4147 bool failed_assert_negate
;
4148 const char *failed_assert
;
4149 const char *failed_assert_parameter
;
4150 usec_t next_elapse_real
;
4151 usec_t next_elapse_monotonic
;
4154 unsigned n_accepted
;
4155 unsigned n_connections
;
4159 /* Pairs of type, path */
4163 const char *sysfs_path
;
4165 /* Mount, Automount */
4172 uint64_t memory_current
;
4173 uint64_t memory_min
;
4174 uint64_t memory_low
;
4175 uint64_t memory_high
;
4176 uint64_t memory_max
;
4177 uint64_t memory_swap_max
;
4178 uint64_t memory_limit
;
4179 uint64_t cpu_usage_nsec
;
4180 uint64_t tasks_current
;
4182 uint64_t ip_ingress_bytes
;
4183 uint64_t ip_egress_bytes
;
4184 uint64_t io_read_bytes
;
4185 uint64_t io_write_bytes
;
4187 uint64_t default_memory_min
;
4188 uint64_t default_memory_low
;
4190 LIST_HEAD(ExecStatusInfo
, exec
);
4193 static void unit_status_info_free(UnitStatusInfo
*info
) {
4197 strv_free(info
->documentation
);
4198 strv_free(info
->dropin_paths
);
4199 strv_free(info
->triggered_by
);
4200 strv_free(info
->triggers
);
4201 strv_free(info
->listen
);
4203 while ((c
= info
->conditions
)) {
4204 LIST_REMOVE(conditions
, info
->conditions
, c
);
4205 unit_condition_free(c
);
4208 while ((p
= info
->exec
)) {
4209 LIST_REMOVE(exec
, info
->exec
, p
);
4210 exec_status_info_free(p
);
4214 static void format_active_state(const char *active_state
, const char **active_on
, const char **active_off
) {
4215 if (streq_ptr(active_state
, "failed")) {
4216 *active_on
= ansi_highlight_red();
4217 *active_off
= ansi_normal();
4218 } else if (STRPTR_IN_SET(active_state
, "active", "reloading")) {
4219 *active_on
= ansi_highlight_green();
4220 *active_off
= ansi_normal();
4222 *active_on
= *active_off
= "";
4225 static void print_status_info(
4230 char since1
[FORMAT_TIMESTAMP_RELATIVE_MAX
], since2
[FORMAT_TIMESTAMP_MAX
];
4231 const char *s1
, *s2
, *active_on
, *active_off
, *on
, *off
, *ss
, *fs
;
4232 _cleanup_free_
char *formatted_path
= NULL
;
4241 /* This shows pretty information about a unit. See
4242 * print_property() for a low-level property printer */
4244 format_active_state(i
->active_state
, &active_on
, &active_off
);
4246 printf("%s%s%s %s", active_on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), active_off
, strna(i
->id
));
4248 if (i
->description
&& !streq_ptr(i
->id
, i
->description
))
4249 printf(" - %s", i
->description
);
4254 printf(" Follow: unit currently follows state of %s\n", i
->following
);
4256 if (STRPTR_IN_SET(i
->load_state
, "error", "not-found", "bad-setting")) {
4257 on
= ansi_highlight_red();
4258 off
= ansi_normal();
4262 path
= i
->source_path
?: i
->fragment_path
;
4263 if (path
&& terminal_urlify_path(path
, NULL
, &formatted_path
) >= 0)
4264 path
= formatted_path
;
4266 if (!isempty(i
->load_error
))
4267 printf(" Loaded: %s%s%s (Reason: %s)\n",
4268 on
, strna(i
->load_state
), off
, i
->load_error
);
4269 else if (path
&& !isempty(i
->unit_file_state
)) {
4270 bool show_preset
= !isempty(i
->unit_file_preset
) &&
4271 show_preset_for_state(unit_file_state_from_string(i
->unit_file_state
));
4273 printf(" Loaded: %s%s%s (%s; %s%s%s)\n",
4274 on
, strna(i
->load_state
), off
,
4277 show_preset
? "; vendor preset: " : "",
4278 show_preset
? i
->unit_file_preset
: "");
4281 printf(" Loaded: %s%s%s (%s)\n",
4282 on
, strna(i
->load_state
), off
, path
);
4284 printf(" Loaded: %s%s%s\n",
4285 on
, strna(i
->load_state
), off
);
4288 printf(" Transient: yes\n");
4290 if (!strv_isempty(i
->dropin_paths
)) {
4291 _cleanup_free_
char *dir
= NULL
;
4295 STRV_FOREACH(dropin
, i
->dropin_paths
) {
4296 _cleanup_free_
char *dropin_formatted
= NULL
;
4305 dir
= dirname_malloc(*dropin
);
4313 special_glyph(SPECIAL_GLYPH_TREE_RIGHT
));
4316 last
= ! (*(dropin
+ 1) && startswith(*(dropin
+ 1), dir
));
4318 if (terminal_urlify_path(*dropin
, basename(*dropin
), &dropin_formatted
) >= 0)
4319 df
= dropin_formatted
;
4323 printf("%s%s", df
, last
? "\n" : ", ");
4327 ss
= streq_ptr(i
->active_state
, i
->sub_state
) ? NULL
: i
->sub_state
;
4329 printf(" Active: %s%s (%s)%s",
4330 active_on
, strna(i
->active_state
), ss
, active_off
);
4332 printf(" Active: %s%s%s",
4333 active_on
, strna(i
->active_state
), active_off
);
4335 fs
= !isempty(i
->freezer_state
) && !streq(i
->freezer_state
, "running") ? i
->freezer_state
: NULL
;
4337 printf(" %s(%s)%s", ansi_highlight_yellow(), fs
, active_off
);
4339 if (!isempty(i
->result
) && !streq(i
->result
, "success"))
4340 printf(" (Result: %s)", i
->result
);
4342 timestamp
= STRPTR_IN_SET(i
->active_state
, "active", "reloading") ? i
->active_enter_timestamp
:
4343 STRPTR_IN_SET(i
->active_state
, "inactive", "failed") ? i
->inactive_enter_timestamp
:
4344 STRPTR_IN_SET(i
->active_state
, "activating") ? i
->inactive_exit_timestamp
:
4345 i
->active_exit_timestamp
;
4347 s1
= format_timestamp_relative(since1
, sizeof(since1
), timestamp
);
4348 s2
= format_timestamp(since2
, sizeof(since2
), timestamp
);
4351 printf(" since %s; %s\n", s2
, s1
);
4353 printf(" since %s\n", s2
);
4357 STRV_FOREACH(t
, i
->triggered_by
) {
4358 UnitActiveState state
= _UNIT_ACTIVE_STATE_INVALID
;
4360 (void) get_state_one_unit(bus
, *t
, &state
);
4361 format_active_state(unit_active_state_to_string(state
), &on
, &off
);
4363 printf("%s %s%s%s %s\n",
4364 t
== i
->triggered_by
? "TriggeredBy:" : " ",
4365 on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
,
4369 if (endswith(i
->id
, ".timer")) {
4370 char tstamp1
[FORMAT_TIMESTAMP_RELATIVE_MAX
],
4371 tstamp2
[FORMAT_TIMESTAMP_MAX
];
4372 const char *next_rel_time
, *next_time
;
4373 dual_timestamp nw
, next
= {i
->next_elapse_real
,
4374 i
->next_elapse_monotonic
};
4377 printf(" Trigger: ");
4379 dual_timestamp_get(&nw
);
4380 next_elapse
= calc_next_elapse(&nw
, &next
);
4381 next_rel_time
= format_timestamp_relative(tstamp1
, sizeof tstamp1
, next_elapse
);
4382 next_time
= format_timestamp(tstamp2
, sizeof tstamp2
, next_elapse
);
4384 if (next_time
&& next_rel_time
)
4385 printf("%s; %s\n", next_time
, next_rel_time
);
4390 STRV_FOREACH(t
, i
->triggers
) {
4391 UnitActiveState state
= _UNIT_ACTIVE_STATE_INVALID
;
4393 (void) get_state_one_unit(bus
, *t
, &state
);
4394 format_active_state(unit_active_state_to_string(state
), &on
, &off
);
4396 printf("%s %s%s%s %s\n",
4397 t
== i
->triggers
? " Triggers:" : " ",
4398 on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
,
4402 if (!i
->condition_result
&& i
->condition_timestamp
> 0) {
4406 s1
= format_timestamp_relative(since1
, sizeof(since1
), i
->condition_timestamp
);
4407 s2
= format_timestamp(since2
, sizeof(since2
), i
->condition_timestamp
);
4409 printf(" Condition: start %scondition failed%s at %s%s%s\n",
4410 ansi_highlight_yellow(), ansi_normal(),
4411 s2
, s1
? "; " : "", strempty(s1
));
4413 LIST_FOREACH(conditions
, c
, i
->conditions
)
4414 if (c
->tristate
< 0)
4417 LIST_FOREACH(conditions
, c
, i
->conditions
)
4418 if (c
->tristate
< 0)
4419 printf(" %s %s=%s%s%s was not met\n",
4420 --n
? special_glyph(SPECIAL_GLYPH_TREE_BRANCH
) : special_glyph(SPECIAL_GLYPH_TREE_RIGHT
),
4422 c
->trigger
? "|" : "",
4423 c
->negate
? "!" : "",
4427 if (!i
->assert_result
&& i
->assert_timestamp
> 0) {
4428 s1
= format_timestamp_relative(since1
, sizeof(since1
), i
->assert_timestamp
);
4429 s2
= format_timestamp(since2
, sizeof(since2
), i
->assert_timestamp
);
4431 printf(" Assert: start %sassertion failed%s at %s%s%s\n",
4432 ansi_highlight_red(), ansi_normal(),
4433 s2
, s1
? "; " : "", strempty(s1
));
4434 if (i
->failed_assert_trigger
)
4435 printf(" none of the trigger assertions were met\n");
4436 else if (i
->failed_assert
)
4437 printf(" %s=%s%s was not met\n",
4439 i
->failed_assert_negate
? "!" : "",
4440 i
->failed_assert_parameter
);
4444 printf(" Device: %s\n", i
->sysfs_path
);
4446 printf(" Where: %s\n", i
->where
);
4448 printf(" What: %s\n", i
->what
);
4450 STRV_FOREACH(t
, i
->documentation
) {
4451 _cleanup_free_
char *formatted
= NULL
;
4454 if (terminal_urlify(*t
, NULL
, &formatted
) >= 0)
4459 printf(" %*s %s\n", 9, t
== i
->documentation
? "Docs:" : "", q
);
4462 STRV_FOREACH_PAIR(t
, t2
, i
->listen
)
4463 printf(" %*s %s (%s)\n", 9, t
== i
->listen
? "Listen:" : "", *t2
, *t
);
4466 printf(" Accepted: %u; Connected: %u;", i
->n_accepted
, i
->n_connections
);
4468 printf(" Refused: %u", i
->n_refused
);
4472 LIST_FOREACH(exec
, p
, i
->exec
) {
4473 _cleanup_free_
char *argv
= NULL
;
4476 /* Only show exited processes here */
4480 /* Don't print ExecXYZEx= properties here since it will appear as a
4481 * duplicate of the non-Ex= variant. */
4482 if (endswith(p
->name
, "Ex"))
4485 argv
= strv_join(p
->argv
, " ");
4486 printf(" Process: "PID_FMT
" %s=%s ", p
->pid
, p
->name
, strna(argv
));
4488 good
= is_clean_exit(p
->code
, p
->status
, EXIT_CLEAN_DAEMON
, NULL
);
4490 on
= ansi_highlight_red();
4491 off
= ansi_normal();
4495 printf("%s(code=%s, ", on
, sigchld_code_to_string(p
->code
));
4497 if (p
->code
== CLD_EXITED
) {
4500 printf("status=%i", p
->status
);
4502 c
= exit_status_to_string(p
->status
, EXIT_STATUS_LIBC
| EXIT_STATUS_SYSTEMD
);
4507 printf("signal=%s", signal_to_string(p
->status
));
4509 printf(")%s\n", off
);
4511 if (i
->main_pid
== p
->pid
&&
4512 i
->start_timestamp
== p
->start_timestamp
&&
4513 i
->exit_timestamp
== p
->start_timestamp
)
4514 /* Let's not show this twice */
4517 if (p
->pid
== i
->control_pid
)
4521 if (i
->main_pid
> 0 || i
->control_pid
> 0) {
4522 if (i
->main_pid
> 0) {
4523 printf(" Main PID: "PID_FMT
, i
->main_pid
);
4527 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
4528 _cleanup_free_
char *comm
= NULL
;
4530 (void) get_process_comm(i
->main_pid
, &comm
);
4532 printf(" (%s)", comm
);
4535 } else if (i
->exit_code
> 0) {
4536 printf(" (code=%s, ", sigchld_code_to_string(i
->exit_code
));
4538 if (i
->exit_code
== CLD_EXITED
) {
4541 printf("status=%i", i
->exit_status
);
4543 c
= exit_status_to_string(i
->exit_status
,
4544 EXIT_STATUS_LIBC
| EXIT_STATUS_SYSTEMD
);
4549 printf("signal=%s", signal_to_string(i
->exit_status
));
4554 if (i
->control_pid
> 0) {
4555 _cleanup_free_
char *c
= NULL
;
4557 if (i
->main_pid
> 0)
4558 fputs("; Control PID: ", stdout
);
4560 fputs("Cntrl PID: ", stdout
); /* if first in column, abbreviated so it fits alignment */
4562 printf(PID_FMT
, i
->control_pid
);
4564 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
4565 (void) get_process_comm(i
->control_pid
, &c
);
4575 printf(" Status: \"%s\"\n", i
->status_text
);
4576 if (i
->status_errno
> 0)
4577 printf(" Error: %i (%s)\n", i
->status_errno
, strerror_safe(i
->status_errno
));
4579 if (i
->ip_ingress_bytes
!= (uint64_t) -1 && i
->ip_egress_bytes
!= (uint64_t) -1) {
4580 char buf_in
[FORMAT_BYTES_MAX
], buf_out
[FORMAT_BYTES_MAX
];
4582 printf(" IP: %s in, %s out\n",
4583 format_bytes(buf_in
, sizeof(buf_in
), i
->ip_ingress_bytes
),
4584 format_bytes(buf_out
, sizeof(buf_out
), i
->ip_egress_bytes
));
4587 if (i
->io_read_bytes
!= UINT64_MAX
&& i
->io_write_bytes
!= UINT64_MAX
) {
4588 char buf_in
[FORMAT_BYTES_MAX
], buf_out
[FORMAT_BYTES_MAX
];
4590 printf(" IO: %s read, %s written\n",
4591 format_bytes(buf_in
, sizeof(buf_in
), i
->io_read_bytes
),
4592 format_bytes(buf_out
, sizeof(buf_out
), i
->io_write_bytes
));
4595 if (i
->tasks_current
!= (uint64_t) -1) {
4596 printf(" Tasks: %" PRIu64
, i
->tasks_current
);
4598 if (i
->tasks_max
!= (uint64_t) -1)
4599 printf(" (limit: %" PRIu64
")\n", i
->tasks_max
);
4604 if (i
->memory_current
!= (uint64_t) -1) {
4605 char buf
[FORMAT_BYTES_MAX
];
4607 printf(" Memory: %s", format_bytes(buf
, sizeof(buf
), i
->memory_current
));
4609 if (i
->memory_min
> 0 || i
->memory_low
> 0 ||
4610 i
->memory_high
!= CGROUP_LIMIT_MAX
|| i
->memory_max
!= CGROUP_LIMIT_MAX
||
4611 i
->memory_swap_max
!= CGROUP_LIMIT_MAX
||
4612 i
->memory_limit
!= CGROUP_LIMIT_MAX
) {
4613 const char *prefix
= "";
4616 if (i
->memory_min
> 0) {
4617 printf("%smin: %s", prefix
, format_bytes_cgroup_protection(buf
, sizeof(buf
), i
->memory_min
));
4620 if (i
->memory_low
> 0) {
4621 printf("%slow: %s", prefix
, format_bytes_cgroup_protection(buf
, sizeof(buf
), i
->memory_low
));
4624 if (i
->memory_high
!= CGROUP_LIMIT_MAX
) {
4625 printf("%shigh: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_high
));
4628 if (i
->memory_max
!= CGROUP_LIMIT_MAX
) {
4629 printf("%smax: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_max
));
4632 if (i
->memory_swap_max
!= CGROUP_LIMIT_MAX
) {
4633 printf("%sswap max: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_swap_max
));
4636 if (i
->memory_limit
!= CGROUP_LIMIT_MAX
) {
4637 printf("%slimit: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_limit
));
4645 if (i
->cpu_usage_nsec
!= (uint64_t) -1) {
4646 char buf
[FORMAT_TIMESPAN_MAX
];
4647 printf(" CPU: %s\n", format_timespan(buf
, sizeof(buf
), i
->cpu_usage_nsec
/ NSEC_PER_USEC
, USEC_PER_MSEC
));
4650 if (i
->control_group
) {
4651 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
4652 static const char prefix
[] = " ";
4655 printf(" CGroup: %s\n", i
->control_group
);
4658 if (c
> sizeof(prefix
) - 1)
4659 c
-= sizeof(prefix
) - 1;
4663 r
= unit_show_processes(bus
, i
->id
, i
->control_group
, prefix
, c
, get_output_flags(), &error
);
4668 /* Fallback for older systemd versions where the GetUnitProcesses() call is not yet available */
4670 if (i
->main_pid
> 0)
4671 extra
[k
++] = i
->main_pid
;
4673 if (i
->control_pid
> 0)
4674 extra
[k
++] = i
->control_pid
;
4676 show_cgroup_and_extra(SYSTEMD_CGROUP_CONTROLLER
, i
->control_group
, prefix
, c
, extra
, k
, get_output_flags());
4678 log_warning_errno(r
, "Failed to dump process list for '%s', ignoring: %s",
4679 i
->id
, bus_error_message(&error
, r
));
4682 if (i
->id
&& arg_transport
== BUS_TRANSPORT_LOCAL
)
4683 show_journal_by_unit(
4689 i
->inactive_exit_timestamp_monotonic
,
4692 get_output_flags() | OUTPUT_BEGIN_NEWLINE
,
4693 SD_JOURNAL_LOCAL_ONLY
,
4694 arg_scope
== UNIT_FILE_SYSTEM
,
4697 if (i
->need_daemon_reload
)
4698 warn_unit_file_changed(i
->id
);
4701 static void show_unit_help(UnitStatusInfo
*i
) {
4706 if (!i
->documentation
) {
4707 log_info("Documentation for %s not known.", i
->id
);
4711 STRV_FOREACH(p
, i
->documentation
)
4712 if (startswith(*p
, "man:"))
4713 show_man_page(*p
+ 4, false);
4715 log_info("Can't show: %s", *p
);
4718 static int map_main_pid(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4719 UnitStatusInfo
*i
= userdata
;
4723 r
= sd_bus_message_read(m
, "u", &u
);
4727 i
->main_pid
= (pid_t
) u
;
4733 static int map_load_error(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4734 const char *message
, **p
= userdata
;
4737 r
= sd_bus_message_read(m
, "(ss)", NULL
, &message
);
4741 if (!isempty(message
))
4747 static int map_listen(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4748 const char *type
, *path
;
4749 char ***p
= userdata
;
4752 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
4756 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0) {
4758 r
= strv_extend(p
, type
);
4762 r
= strv_extend(p
, path
);
4769 r
= sd_bus_message_exit_container(m
);
4776 static int map_conditions(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4777 UnitStatusInfo
*i
= userdata
;
4778 const char *cond
, *param
;
4779 int trigger
, negate
;
4783 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sbbsi)");
4787 while ((r
= sd_bus_message_read(m
, "(sbbsi)", &cond
, &trigger
, &negate
, ¶m
, &state
)) > 0) {
4788 _cleanup_(unit_condition_freep
) UnitCondition
*c
= NULL
;
4790 c
= new(UnitCondition
, 1);
4794 *c
= (UnitCondition
) {
4795 .name
= strdup(cond
),
4796 .param
= strdup(param
),
4802 if (!c
->name
|| !c
->param
)
4805 LIST_PREPEND(conditions
, i
->conditions
, TAKE_PTR(c
));
4810 r
= sd_bus_message_exit_container(m
);
4817 static int map_asserts(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4818 UnitStatusInfo
*i
= userdata
;
4819 const char *cond
, *param
;
4820 int trigger
, negate
;
4824 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sbbsi)");
4828 while ((r
= sd_bus_message_read(m
, "(sbbsi)", &cond
, &trigger
, &negate
, ¶m
, &state
)) > 0) {
4829 if (state
< 0 && (!trigger
|| !i
->failed_assert
)) {
4830 i
->failed_assert
= cond
;
4831 i
->failed_assert_trigger
= trigger
;
4832 i
->failed_assert_negate
= negate
;
4833 i
->failed_assert_parameter
= param
;
4839 r
= sd_bus_message_exit_container(m
);
4846 static int map_exec(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4847 _cleanup_free_ ExecStatusInfo
*info
= NULL
;
4848 ExecStatusInfo
*last
;
4849 UnitStatusInfo
*i
= userdata
;
4850 bool is_ex_prop
= endswith(member
, "Ex");
4853 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, is_ex_prop
? "(sasasttttuii)" : "(sasbttttuii)");
4857 info
= new0(ExecStatusInfo
, 1);
4861 LIST_FIND_TAIL(exec
, i
->exec
, last
);
4863 while ((r
= exec_status_info_deserialize(m
, info
, is_ex_prop
)) > 0) {
4865 info
->name
= strdup(member
);
4869 LIST_INSERT_AFTER(exec
, i
->exec
, last
, info
);
4872 info
= new0(ExecStatusInfo
, 1);
4879 r
= sd_bus_message_exit_container(m
);
4886 static int print_property(const char *name
, const char *expected_value
, sd_bus_message
*m
, bool value
, bool all
) {
4888 const char *contents
;
4894 /* This is a low-level property printer, see
4895 * print_status_info() for the nicer output */
4897 r
= sd_bus_message_peek_type(m
, &bus_type
, &contents
);
4903 case SD_BUS_TYPE_INT32
:
4904 if (endswith(name
, "ActionExitStatus")) {
4907 r
= sd_bus_message_read_basic(m
, bus_type
, &i
);
4911 if (i
>= 0 && i
<= 255)
4912 bus_print_property_valuef(name
, expected_value
, value
, "%"PRIi32
, i
);
4914 bus_print_property_value(name
, expected_value
, value
, "[not set]");
4917 } else if (streq(name
, "NUMAPolicy")) {
4920 r
= sd_bus_message_read_basic(m
, bus_type
, &i
);
4924 bus_print_property_valuef(name
, expected_value
, value
, "%s", strna(mpol_to_string(i
)));
4930 case SD_BUS_TYPE_STRUCT
:
4932 if (contents
[0] == SD_BUS_TYPE_UINT32
&& streq(name
, "Job")) {
4935 r
= sd_bus_message_read(m
, "(uo)", &u
, NULL
);
4937 return bus_log_parse_error(r
);
4940 bus_print_property_valuef(name
, expected_value
, value
, "%"PRIu32
, u
);
4942 bus_print_property_value(name
, expected_value
, value
, "");
4946 } else if (contents
[0] == SD_BUS_TYPE_STRING
&& streq(name
, "Unit")) {
4949 r
= sd_bus_message_read(m
, "(so)", &s
, NULL
);
4951 return bus_log_parse_error(r
);
4953 if (all
|| !isempty(s
))
4954 bus_print_property_value(name
, expected_value
, value
, s
);
4958 } else if (contents
[0] == SD_BUS_TYPE_STRING
&& streq(name
, "LoadError")) {
4959 const char *a
= NULL
, *b
= NULL
;
4961 r
= sd_bus_message_read(m
, "(ss)", &a
, &b
);
4963 return bus_log_parse_error(r
);
4965 if (!isempty(a
) || !isempty(b
))
4966 bus_print_property_valuef(name
, expected_value
, value
, "%s \"%s\"", strempty(a
), strempty(b
));
4968 bus_print_property_value(name
, expected_value
, value
, "");
4972 } else if (STR_IN_SET(name
, "SystemCallFilter", "RestrictAddressFamilies")) {
4973 _cleanup_strv_free_
char **l
= NULL
;
4976 r
= sd_bus_message_enter_container(m
, 'r', "bas");
4978 return bus_log_parse_error(r
);
4980 r
= sd_bus_message_read(m
, "b", &whitelist
);
4982 return bus_log_parse_error(r
);
4984 r
= sd_bus_message_read_strv(m
, &l
);
4986 return bus_log_parse_error(r
);
4988 r
= sd_bus_message_exit_container(m
);
4990 return bus_log_parse_error(r
);
4992 if (all
|| whitelist
|| !strv_isempty(l
)) {
4997 fputs(name
, stdout
);
5004 STRV_FOREACH(i
, l
) {
5012 fputc('\n', stdout
);
5017 } else if (STR_IN_SET(name
, "SELinuxContext", "AppArmorProfile", "SmackProcessLabel")) {
5021 r
= sd_bus_message_read(m
, "(bs)", &ignore
, &s
);
5023 return bus_log_parse_error(r
);
5026 bus_print_property_valuef(name
, expected_value
, value
, "%s%s", ignore
? "-" : "", s
);
5028 bus_print_property_value(name
, expected_value
, value
, "");
5032 } else if (endswith(name
, "ExitStatus") && streq(contents
, "aiai")) {
5033 const int32_t *status
, *signal
;
5034 size_t n_status
, n_signal
, i
;
5036 r
= sd_bus_message_enter_container(m
, 'r', "aiai");
5038 return bus_log_parse_error(r
);
5040 r
= sd_bus_message_read_array(m
, 'i', (const void **) &status
, &n_status
);
5042 return bus_log_parse_error(r
);
5044 r
= sd_bus_message_read_array(m
, 'i', (const void **) &signal
, &n_signal
);
5046 return bus_log_parse_error(r
);
5048 r
= sd_bus_message_exit_container(m
);
5050 return bus_log_parse_error(r
);
5052 n_status
/= sizeof(int32_t);
5053 n_signal
/= sizeof(int32_t);
5055 if (all
|| n_status
> 0 || n_signal
> 0) {
5059 fputs(name
, stdout
);
5063 for (i
= 0; i
< n_status
; i
++) {
5069 printf("%"PRIi32
, status
[i
]);
5072 for (i
= 0; i
< n_signal
; i
++) {
5075 str
= signal_to_string((int) signal
[i
]);
5085 printf("%"PRIi32
, status
[i
]);
5088 fputc('\n', stdout
);
5095 case SD_BUS_TYPE_ARRAY
:
5097 if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "EnvironmentFiles")) {
5101 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sb)");
5103 return bus_log_parse_error(r
);
5105 while ((r
= sd_bus_message_read(m
, "(sb)", &path
, &ignore
)) > 0)
5106 bus_print_property_valuef(name
, expected_value
, value
, "%s (ignore_errors=%s)", path
, yes_no(ignore
));
5109 return bus_log_parse_error(r
);
5111 r
= sd_bus_message_exit_container(m
);
5113 return bus_log_parse_error(r
);
5117 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "Paths")) {
5118 const char *type
, *path
;
5120 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5122 return bus_log_parse_error(r
);
5124 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0)
5125 bus_print_property_valuef(name
, expected_value
, value
, "%s (%s)", path
, type
);
5127 return bus_log_parse_error(r
);
5129 r
= sd_bus_message_exit_container(m
);
5131 return bus_log_parse_error(r
);
5135 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "Listen")) {
5136 const char *type
, *path
;
5138 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5140 return bus_log_parse_error(r
);
5142 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0)
5143 bus_print_property_valuef(name
, expected_value
, value
, "%s (%s)", path
, type
);
5145 return bus_log_parse_error(r
);
5147 r
= sd_bus_message_exit_container(m
);
5149 return bus_log_parse_error(r
);
5153 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "TimersMonotonic")) {
5155 uint64_t v
, next_elapse
;
5157 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(stt)");
5159 return bus_log_parse_error(r
);
5161 while ((r
= sd_bus_message_read(m
, "(stt)", &base
, &v
, &next_elapse
)) > 0) {
5162 char timespan1
[FORMAT_TIMESPAN_MAX
] = "n/a", timespan2
[FORMAT_TIMESPAN_MAX
] = "n/a";
5164 (void) format_timespan(timespan1
, sizeof timespan1
, v
, 0);
5165 (void) format_timespan(timespan2
, sizeof timespan2
, next_elapse
, 0);
5167 bus_print_property_valuef(name
, expected_value
, value
,
5168 "{ %s=%s ; next_elapse=%s }", base
, timespan1
, timespan2
);
5171 return bus_log_parse_error(r
);
5173 r
= sd_bus_message_exit_container(m
);
5175 return bus_log_parse_error(r
);
5179 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "TimersCalendar")) {
5180 const char *base
, *spec
;
5181 uint64_t next_elapse
;
5183 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sst)");
5185 return bus_log_parse_error(r
);
5187 while ((r
= sd_bus_message_read(m
, "(sst)", &base
, &spec
, &next_elapse
)) > 0) {
5188 char timestamp
[FORMAT_TIMESTAMP_MAX
] = "n/a";
5190 (void) format_timestamp(timestamp
, sizeof(timestamp
), next_elapse
);
5191 bus_print_property_valuef(name
, expected_value
, value
,
5192 "{ %s=%s ; next_elapse=%s }", base
, spec
, timestamp
);
5195 return bus_log_parse_error(r
);
5197 r
= sd_bus_message_exit_container(m
);
5199 return bus_log_parse_error(r
);
5203 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& startswith(name
, "Exec")) {
5204 ExecStatusInfo info
= {};
5205 bool is_ex_prop
= endswith(name
, "Ex");
5207 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, is_ex_prop
? "(sasasttttuii)" : "(sasbttttuii)");
5209 return bus_log_parse_error(r
);
5211 while ((r
= exec_status_info_deserialize(m
, &info
, is_ex_prop
)) > 0) {
5212 char timestamp1
[FORMAT_TIMESTAMP_MAX
], timestamp2
[FORMAT_TIMESTAMP_MAX
];
5213 _cleanup_strv_free_
char **optv
= NULL
;
5214 _cleanup_free_
char *tt
, *o
= NULL
;
5216 tt
= strv_join(info
.argv
, " ");
5219 r
= exec_command_flags_to_strv(info
.flags
, &optv
);
5221 return log_error_errno(r
, "Failed to convert ExecCommandFlags to strv: %m");
5223 o
= strv_join(optv
, " ");
5225 bus_print_property_valuef(name
, expected_value
, value
,
5226 "{ path=%s ; argv[]=%s ; flags=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT
" ; code=%s ; status=%i%s%s }",
5230 strna(format_timestamp(timestamp1
, sizeof(timestamp1
), info
.start_timestamp
)),
5231 strna(format_timestamp(timestamp2
, sizeof(timestamp2
), info
.exit_timestamp
)),
5233 sigchld_code_to_string(info
.code
),
5235 info
.code
== CLD_EXITED
? "" : "/",
5236 strempty(info
.code
== CLD_EXITED
? NULL
: signal_to_string(info
.status
)));
5238 bus_print_property_valuef(name
, expected_value
, value
,
5239 "{ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT
" ; code=%s ; status=%i%s%s }",
5242 yes_no(info
.ignore
),
5243 strna(format_timestamp(timestamp1
, sizeof(timestamp1
), info
.start_timestamp
)),
5244 strna(format_timestamp(timestamp2
, sizeof(timestamp2
), info
.exit_timestamp
)),
5246 sigchld_code_to_string(info
.code
),
5248 info
.code
== CLD_EXITED
? "" : "/",
5249 strempty(info
.code
== CLD_EXITED
? NULL
: signal_to_string(info
.status
)));
5252 strv_free(info
.argv
);
5256 r
= sd_bus_message_exit_container(m
);
5258 return bus_log_parse_error(r
);
5262 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "DeviceAllow")) {
5263 const char *path
, *rwm
;
5265 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5267 return bus_log_parse_error(r
);
5269 while ((r
= sd_bus_message_read(m
, "(ss)", &path
, &rwm
)) > 0)
5270 bus_print_property_valuef(name
, expected_value
, value
, "%s %s", strna(path
), strna(rwm
));
5272 return bus_log_parse_error(r
);
5274 r
= sd_bus_message_exit_container(m
);
5276 return bus_log_parse_error(r
);
5280 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5281 STR_IN_SET(name
, "IODeviceWeight", "BlockIODeviceWeight")) {
5285 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5287 return bus_log_parse_error(r
);
5289 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &weight
)) > 0)
5290 bus_print_property_valuef(name
, expected_value
, value
, "%s %"PRIu64
, strna(path
), weight
);
5292 return bus_log_parse_error(r
);
5294 r
= sd_bus_message_exit_container(m
);
5296 return bus_log_parse_error(r
);
5300 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5301 (cgroup_io_limit_type_from_string(name
) >= 0 ||
5302 STR_IN_SET(name
, "BlockIOReadBandwidth", "BlockIOWriteBandwidth"))) {
5306 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5308 return bus_log_parse_error(r
);
5310 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &bandwidth
)) > 0)
5311 bus_print_property_valuef(name
, expected_value
, value
, "%s %"PRIu64
, strna(path
), bandwidth
);
5313 return bus_log_parse_error(r
);
5315 r
= sd_bus_message_exit_container(m
);
5317 return bus_log_parse_error(r
);
5321 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5322 streq(name
, "IODeviceLatencyTargetUSec")) {
5323 char ts
[FORMAT_TIMESPAN_MAX
];
5327 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5329 return bus_log_parse_error(r
);
5331 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &target
)) > 0)
5332 bus_print_property_valuef(name
, expected_value
, value
, "%s %s", strna(path
),
5333 format_timespan(ts
, sizeof(ts
), target
, 1));
5335 return bus_log_parse_error(r
);
5337 r
= sd_bus_message_exit_container(m
);
5339 return bus_log_parse_error(r
);
5343 } else if (contents
[0] == SD_BUS_TYPE_BYTE
&& streq(name
, "StandardInputData")) {
5344 _cleanup_free_
char *h
= NULL
;
5349 r
= sd_bus_message_read_array(m
, 'y', &p
, &sz
);
5351 return bus_log_parse_error(r
);
5353 n
= base64mem(p
, sz
, &h
);
5357 bus_print_property_value(name
, expected_value
, value
, h
);
5361 } else if (STR_IN_SET(name
, "IPAddressAllow", "IPAddressDeny")) {
5362 _cleanup_free_
char *addresses
= NULL
;
5364 r
= sd_bus_message_enter_container(m
, 'a', "(iayu)");
5366 return bus_log_parse_error(r
);
5369 _cleanup_free_
char *str
= NULL
;
5375 r
= sd_bus_message_enter_container(m
, 'r', "iayu");
5377 return bus_log_parse_error(r
);
5381 r
= sd_bus_message_read(m
, "i", &family
);
5383 return bus_log_parse_error(r
);
5385 r
= sd_bus_message_read_array(m
, 'y', &ap
, &an
);
5387 return bus_log_parse_error(r
);
5389 r
= sd_bus_message_read(m
, "u", &prefixlen
);
5391 return bus_log_parse_error(r
);
5393 r
= sd_bus_message_exit_container(m
);
5395 return bus_log_parse_error(r
);
5397 if (!IN_SET(family
, AF_INET
, AF_INET6
))
5400 if (an
!= FAMILY_ADDRESS_SIZE(family
))
5403 if (prefixlen
> FAMILY_ADDRESS_SIZE(family
) * 8)
5406 if (in_addr_prefix_to_string(family
, (union in_addr_union
*) ap
, prefixlen
, &str
) < 0)
5409 if (!strextend_with_separator(&addresses
, " ", str
, NULL
))
5413 r
= sd_bus_message_exit_container(m
);
5415 return bus_log_parse_error(r
);
5417 if (all
|| !isempty(addresses
))
5418 bus_print_property_value(name
, expected_value
, value
, strempty(addresses
));
5422 } else if (STR_IN_SET(name
, "BindPaths", "BindReadOnlyPaths")) {
5423 _cleanup_free_
char *paths
= NULL
;
5424 const char *source
, *dest
;
5428 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ssbt)");
5430 return bus_log_parse_error(r
);
5432 while ((r
= sd_bus_message_read(m
, "(ssbt)", &source
, &dest
, &ignore_enoent
, &rbind
)) > 0) {
5433 _cleanup_free_
char *str
= NULL
;
5435 if (isempty(source
))
5438 if (asprintf(&str
, "%s%s%s%s%s",
5439 ignore_enoent
? "-" : "",
5441 isempty(dest
) ? "" : ":",
5443 rbind
== MS_REC
? ":rbind" : "") < 0)
5446 if (!strextend_with_separator(&paths
, " ", str
, NULL
))
5450 return bus_log_parse_error(r
);
5452 r
= sd_bus_message_exit_container(m
);
5454 return bus_log_parse_error(r
);
5456 if (all
|| !isempty(paths
))
5457 bus_print_property_value(name
, expected_value
, value
, strempty(paths
));
5461 } else if (streq(name
, "TemporaryFileSystem")) {
5462 _cleanup_free_
char *paths
= NULL
;
5463 const char *target
, *option
;
5465 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5467 return bus_log_parse_error(r
);
5469 while ((r
= sd_bus_message_read(m
, "(ss)", &target
, &option
)) > 0) {
5470 _cleanup_free_
char *str
= NULL
;
5472 if (isempty(target
))
5475 if (asprintf(&str
, "%s%s%s", target
, isempty(option
) ? "" : ":", strempty(option
)) < 0)
5478 if (!strextend_with_separator(&paths
, " ", str
, NULL
))
5482 return bus_log_parse_error(r
);
5484 r
= sd_bus_message_exit_container(m
);
5486 return bus_log_parse_error(r
);
5488 if (all
|| !isempty(paths
))
5489 bus_print_property_value(name
, expected_value
, value
, strempty(paths
));
5493 } else if (streq(name
, "LogExtraFields")) {
5494 _cleanup_free_
char *fields
= NULL
;
5498 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "ay");
5500 return bus_log_parse_error(r
);
5502 while ((r
= sd_bus_message_read_array(m
, 'y', &p
, &sz
)) > 0) {
5503 _cleanup_free_
char *str
= NULL
;
5506 if (memchr(p
, 0, sz
))
5509 eq
= memchr(p
, '=', sz
);
5513 if (!journal_field_valid(p
, eq
- (const char*) p
, false))
5516 str
= malloc(sz
+ 1);
5523 if (!utf8_is_valid(str
))
5526 if (!strextend_with_separator(&fields
, " ", str
, NULL
))
5530 return bus_log_parse_error(r
);
5532 r
= sd_bus_message_exit_container(m
);
5534 return bus_log_parse_error(r
);
5536 if (all
|| !isempty(fields
))
5537 bus_print_property_value(name
, expected_value
, value
, strempty(fields
));
5540 } else if (contents
[0] == SD_BUS_TYPE_BYTE
&& STR_IN_SET(name
, "CPUAffinity", "NUMAMask", "AllowedCPUs", "AllowedMemoryNodes", "EffectiveCPUs", "EffectiveMemoryNodes")) {
5541 _cleanup_free_
char *affinity
= NULL
;
5542 _cleanup_(cpu_set_reset
) CPUSet set
= {};
5546 r
= sd_bus_message_read_array(m
, 'y', &a
, &n
);
5548 return bus_log_parse_error(r
);
5550 r
= cpu_set_from_dbus(a
, n
, &set
);
5552 return log_error_errno(r
, "Failed to deserialize %s: %m", name
);
5554 affinity
= cpu_set_to_range_string(&set
);
5558 bus_print_property_value(name
, expected_value
, value
, affinity
);
5569 typedef enum SystemctlShowMode
{
5570 SYSTEMCTL_SHOW_PROPERTIES
,
5571 SYSTEMCTL_SHOW_STATUS
,
5572 SYSTEMCTL_SHOW_HELP
,
5573 _SYSTEMCTL_SHOW_MODE_MAX
,
5574 _SYSTEMCTL_SHOW_MODE_INVALID
= -1,
5575 } SystemctlShowMode
;
5577 static const char* const systemctl_show_mode_table
[_SYSTEMCTL_SHOW_MODE_MAX
] = {
5578 [SYSTEMCTL_SHOW_PROPERTIES
] = "show",
5579 [SYSTEMCTL_SHOW_STATUS
] = "status",
5580 [SYSTEMCTL_SHOW_HELP
] = "help",
5583 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(systemctl_show_mode
, SystemctlShowMode
);
5585 static int show_one(
5589 SystemctlShowMode show_mode
,
5593 static const struct bus_properties_map property_map
[] = {
5594 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
5595 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
) },
5596 { "FreezerState", "s", NULL
, offsetof(UnitStatusInfo
, freezer_state
) },
5597 { "Documentation", "as", NULL
, offsetof(UnitStatusInfo
, documentation
) },
5600 { "Id", "s", NULL
, offsetof(UnitStatusInfo
, id
) },
5601 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
5602 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
) },
5603 { "FreezerState", "s", NULL
, offsetof(UnitStatusInfo
, freezer_state
) },
5604 { "SubState", "s", NULL
, offsetof(UnitStatusInfo
, sub_state
) },
5605 { "UnitFileState", "s", NULL
, offsetof(UnitStatusInfo
, unit_file_state
) },
5606 { "UnitFilePreset", "s", NULL
, offsetof(UnitStatusInfo
, unit_file_preset
) },
5607 { "Description", "s", NULL
, offsetof(UnitStatusInfo
, description
) },
5608 { "Following", "s", NULL
, offsetof(UnitStatusInfo
, following
) },
5609 { "Documentation", "as", NULL
, offsetof(UnitStatusInfo
, documentation
) },
5610 { "FragmentPath", "s", NULL
, offsetof(UnitStatusInfo
, fragment_path
) },
5611 { "SourcePath", "s", NULL
, offsetof(UnitStatusInfo
, source_path
) },
5612 { "ControlGroup", "s", NULL
, offsetof(UnitStatusInfo
, control_group
) },
5613 { "DropInPaths", "as", NULL
, offsetof(UnitStatusInfo
, dropin_paths
) },
5614 { "LoadError", "(ss)", map_load_error
, offsetof(UnitStatusInfo
, load_error
) },
5615 { "Result", "s", NULL
, offsetof(UnitStatusInfo
, result
) },
5616 { "TriggeredBy", "as", NULL
, offsetof(UnitStatusInfo
, triggered_by
) },
5617 { "Triggers", "as", NULL
, offsetof(UnitStatusInfo
, triggers
) },
5618 { "InactiveExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, inactive_exit_timestamp
) },
5619 { "InactiveExitTimestampMonotonic", "t", NULL
, offsetof(UnitStatusInfo
, inactive_exit_timestamp_monotonic
) },
5620 { "ActiveEnterTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, active_enter_timestamp
) },
5621 { "ActiveExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, active_exit_timestamp
) },
5622 { "InactiveEnterTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, inactive_enter_timestamp
) },
5623 { "NeedDaemonReload", "b", NULL
, offsetof(UnitStatusInfo
, need_daemon_reload
) },
5624 { "Transient", "b", NULL
, offsetof(UnitStatusInfo
, transient
) },
5625 { "ExecMainPID", "u", NULL
, offsetof(UnitStatusInfo
, main_pid
) },
5626 { "MainPID", "u", map_main_pid
, 0 },
5627 { "ControlPID", "u", NULL
, offsetof(UnitStatusInfo
, control_pid
) },
5628 { "StatusText", "s", NULL
, offsetof(UnitStatusInfo
, status_text
) },
5629 { "PIDFile", "s", NULL
, offsetof(UnitStatusInfo
, pid_file
) },
5630 { "StatusErrno", "i", NULL
, offsetof(UnitStatusInfo
, status_errno
) },
5631 { "ExecMainStartTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, start_timestamp
) },
5632 { "ExecMainExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, exit_timestamp
) },
5633 { "ExecMainCode", "i", NULL
, offsetof(UnitStatusInfo
, exit_code
) },
5634 { "ExecMainStatus", "i", NULL
, offsetof(UnitStatusInfo
, exit_status
) },
5635 { "LogNamespace", "s", NULL
, offsetof(UnitStatusInfo
, log_namespace
) },
5636 { "ConditionTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, condition_timestamp
) },
5637 { "ConditionResult", "b", NULL
, offsetof(UnitStatusInfo
, condition_result
) },
5638 { "Conditions", "a(sbbsi)", map_conditions
, 0 },
5639 { "AssertTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, assert_timestamp
) },
5640 { "AssertResult", "b", NULL
, offsetof(UnitStatusInfo
, assert_result
) },
5641 { "Asserts", "a(sbbsi)", map_asserts
, 0 },
5642 { "NextElapseUSecRealtime", "t", NULL
, offsetof(UnitStatusInfo
, next_elapse_real
) },
5643 { "NextElapseUSecMonotonic", "t", NULL
, offsetof(UnitStatusInfo
, next_elapse_monotonic
) },
5644 { "NAccepted", "u", NULL
, offsetof(UnitStatusInfo
, n_accepted
) },
5645 { "NConnections", "u", NULL
, offsetof(UnitStatusInfo
, n_connections
) },
5646 { "NRefused", "u", NULL
, offsetof(UnitStatusInfo
, n_refused
) },
5647 { "Accept", "b", NULL
, offsetof(UnitStatusInfo
, accept
) },
5648 { "Listen", "a(ss)", map_listen
, offsetof(UnitStatusInfo
, listen
) },
5649 { "SysFSPath", "s", NULL
, offsetof(UnitStatusInfo
, sysfs_path
) },
5650 { "Where", "s", NULL
, offsetof(UnitStatusInfo
, where
) },
5651 { "What", "s", NULL
, offsetof(UnitStatusInfo
, what
) },
5652 { "MemoryCurrent", "t", NULL
, offsetof(UnitStatusInfo
, memory_current
) },
5653 { "DefaultMemoryMin", "t", NULL
, offsetof(UnitStatusInfo
, default_memory_min
) },
5654 { "DefaultMemoryLow", "t", NULL
, offsetof(UnitStatusInfo
, default_memory_low
) },
5655 { "MemoryMin", "t", NULL
, offsetof(UnitStatusInfo
, memory_min
) },
5656 { "MemoryLow", "t", NULL
, offsetof(UnitStatusInfo
, memory_low
) },
5657 { "MemoryHigh", "t", NULL
, offsetof(UnitStatusInfo
, memory_high
) },
5658 { "MemoryMax", "t", NULL
, offsetof(UnitStatusInfo
, memory_max
) },
5659 { "MemorySwapMax", "t", NULL
, offsetof(UnitStatusInfo
, memory_swap_max
) },
5660 { "MemoryLimit", "t", NULL
, offsetof(UnitStatusInfo
, memory_limit
) },
5661 { "CPUUsageNSec", "t", NULL
, offsetof(UnitStatusInfo
, cpu_usage_nsec
) },
5662 { "TasksCurrent", "t", NULL
, offsetof(UnitStatusInfo
, tasks_current
) },
5663 { "TasksMax", "t", NULL
, offsetof(UnitStatusInfo
, tasks_max
) },
5664 { "IPIngressBytes", "t", NULL
, offsetof(UnitStatusInfo
, ip_ingress_bytes
) },
5665 { "IPEgressBytes", "t", NULL
, offsetof(UnitStatusInfo
, ip_egress_bytes
) },
5666 { "IOReadBytes", "t", NULL
, offsetof(UnitStatusInfo
, io_read_bytes
) },
5667 { "IOWriteBytes", "t", NULL
, offsetof(UnitStatusInfo
, io_write_bytes
) },
5668 { "ExecCondition", "a(sasbttttuii)", map_exec
, 0 },
5669 { "ExecConditionEx", "a(sasasttttuii)", map_exec
, 0 },
5670 { "ExecStartPre", "a(sasbttttuii)", map_exec
, 0 },
5671 { "ExecStartPreEx", "a(sasasttttuii)", map_exec
, 0 },
5672 { "ExecStart", "a(sasbttttuii)", map_exec
, 0 },
5673 { "ExecStartEx", "a(sasasttttuii)", map_exec
, 0 },
5674 { "ExecStartPost", "a(sasbttttuii)", map_exec
, 0 },
5675 { "ExecStartPostEx", "a(sasasttttuii)", map_exec
, 0 },
5676 { "ExecReload", "a(sasbttttuii)", map_exec
, 0 },
5677 { "ExecReloadEx", "a(sasasttttuii)", map_exec
, 0 },
5678 { "ExecStopPre", "a(sasbttttuii)", map_exec
, 0 },
5679 { "ExecStop", "a(sasbttttuii)", map_exec
, 0 },
5680 { "ExecStopEx", "a(sasasttttuii)", map_exec
, 0 },
5681 { "ExecStopPost", "a(sasbttttuii)", map_exec
, 0 },
5682 { "ExecStopPostEx", "a(sasasttttuii)", map_exec
, 0 },
5686 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5687 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5688 _cleanup_set_free_ Set
*found_properties
= NULL
;
5689 _cleanup_(unit_status_info_free
) UnitStatusInfo info
= {
5690 .memory_current
= (uint64_t) -1,
5691 .memory_high
= CGROUP_LIMIT_MAX
,
5692 .memory_max
= CGROUP_LIMIT_MAX
,
5693 .memory_swap_max
= CGROUP_LIMIT_MAX
,
5694 .memory_limit
= (uint64_t) -1,
5695 .cpu_usage_nsec
= (uint64_t) -1,
5696 .tasks_current
= (uint64_t) -1,
5697 .tasks_max
= (uint64_t) -1,
5698 .ip_ingress_bytes
= (uint64_t) -1,
5699 .ip_egress_bytes
= (uint64_t) -1,
5700 .io_read_bytes
= UINT64_MAX
,
5701 .io_write_bytes
= UINT64_MAX
,
5709 log_debug("Showing one %s", path
);
5711 r
= bus_map_all_properties(
5713 "org.freedesktop.systemd1",
5715 show_mode
== SYSTEMCTL_SHOW_STATUS
? status_map
: property_map
,
5716 BUS_MAP_BOOLEAN_AS_BOOL
,
5721 return log_error_errno(r
, "Failed to get properties: %s", bus_error_message(&error
, r
));
5723 if (unit
&& streq_ptr(info
.load_state
, "not-found") && streq_ptr(info
.active_state
, "inactive")) {
5724 log_full(show_mode
== SYSTEMCTL_SHOW_STATUS
? LOG_ERR
: LOG_DEBUG
,
5725 "Unit %s could not be found.", unit
);
5727 if (show_mode
== SYSTEMCTL_SHOW_STATUS
)
5728 return EXIT_PROGRAM_OR_SERVICES_STATUS_UNKNOWN
;
5729 else if (show_mode
== SYSTEMCTL_SHOW_HELP
)
5738 if (show_mode
== SYSTEMCTL_SHOW_STATUS
) {
5739 print_status_info(bus
, &info
, ellipsized
);
5741 if (info
.active_state
&& !STR_IN_SET(info
.active_state
, "active", "reloading"))
5742 return EXIT_PROGRAM_NOT_RUNNING
;
5744 return EXIT_PROGRAM_RUNNING_OR_SERVICE_OK
;
5746 } else if (show_mode
== SYSTEMCTL_SHOW_HELP
) {
5747 show_unit_help(&info
);
5751 r
= sd_bus_message_rewind(reply
, true);
5753 return log_error_errno(r
, "Failed to rewind: %s", bus_error_message(&error
, r
));
5755 r
= bus_message_print_all_properties(reply
, print_property
, arg_properties
, arg_value
, arg_all
, &found_properties
);
5757 return bus_log_parse_error(r
);
5759 STRV_FOREACH(pp
, arg_properties
)
5760 if (!set_contains(found_properties
, *pp
))
5761 log_debug("Property %s does not exist.", *pp
);
5766 static int get_unit_dbus_path_by_pid(
5771 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5772 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5776 r
= sd_bus_call_method(
5778 "org.freedesktop.systemd1",
5779 "/org/freedesktop/systemd1",
5780 "org.freedesktop.systemd1.Manager",
5786 return log_error_errno(r
, "Failed to get unit for PID %"PRIu32
": %s", pid
, bus_error_message(&error
, r
));
5788 r
= sd_bus_message_read(reply
, "o", &u
);
5790 return bus_log_parse_error(r
);
5800 static int show_all(
5805 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5806 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
5811 r
= get_unit_list(bus
, NULL
, NULL
, &unit_infos
, 0, &reply
);
5815 (void) pager_open(arg_pager_flags
);
5819 typesafe_qsort(unit_infos
, c
, compare_unit_info
);
5821 for (u
= unit_infos
; u
< unit_infos
+ c
; u
++) {
5822 _cleanup_free_
char *p
= NULL
;
5824 p
= unit_dbus_path_from_name(u
->id
);
5828 r
= show_one(bus
, p
, u
->id
, SYSTEMCTL_SHOW_STATUS
, new_line
, ellipsized
);
5831 else if (r
> 0 && ret
== 0)
5838 static int show_system_status(sd_bus
*bus
) {
5839 char since1
[FORMAT_TIMESTAMP_RELATIVE_MAX
], since2
[FORMAT_TIMESTAMP_MAX
];
5840 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5841 _cleanup_(machine_info_clear
) struct machine_info mi
= {};
5842 _cleanup_free_
char *hn
= NULL
;
5843 const char *on
, *off
;
5846 hn
= gethostname_malloc();
5850 r
= bus_map_all_properties(
5852 "org.freedesktop.systemd1",
5853 "/org/freedesktop/systemd1",
5854 machine_info_property_map
,
5860 return log_error_errno(r
, "Failed to read server status: %s", bus_error_message(&error
, r
));
5862 if (streq_ptr(mi
.state
, "degraded")) {
5863 on
= ansi_highlight_red();
5864 off
= ansi_normal();
5865 } else if (streq_ptr(mi
.state
, "running")) {
5866 on
= ansi_highlight_green();
5867 off
= ansi_normal();
5869 on
= ansi_highlight_yellow();
5870 off
= ansi_normal();
5873 printf("%s%s%s %s\n", on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
, arg_host
? arg_host
: hn
);
5875 printf(" State: %s%s%s\n",
5876 on
, strna(mi
.state
), off
);
5878 printf(" Jobs: %" PRIu32
" queued\n", mi
.n_jobs
);
5879 printf(" Failed: %" PRIu32
" units\n", mi
.n_failed_units
);
5881 printf(" Since: %s; %s\n",
5882 format_timestamp(since2
, sizeof(since2
), mi
.timestamp
),
5883 format_timestamp_relative(since1
, sizeof(since1
), mi
.timestamp
));
5885 printf(" CGroup: %s\n", mi
.control_group
?: "/");
5886 if (IN_SET(arg_transport
,
5887 BUS_TRANSPORT_LOCAL
,
5888 BUS_TRANSPORT_MACHINE
)) {
5889 static const char prefix
[] = " ";
5893 if (c
> sizeof(prefix
) - 1)
5894 c
-= sizeof(prefix
) - 1;
5898 show_cgroup(SYSTEMD_CGROUP_CONTROLLER
, strempty(mi
.control_group
), prefix
, c
, get_output_flags());
5904 static int show(int argc
, char *argv
[], void *userdata
) {
5905 bool new_line
= false, ellipsized
= false;
5906 SystemctlShowMode show_mode
;
5912 show_mode
= systemctl_show_mode_from_string(argv
[0]);
5914 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
5915 "Invalid argument.");
5917 if (show_mode
== SYSTEMCTL_SHOW_HELP
&& argc
<= 1)
5918 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
5919 "'help' command expects one or more unit names.\n"
5920 "(Alternatively, help for systemctl itself may be shown with --help)");
5922 r
= acquire_bus(BUS_MANAGER
, &bus
);
5926 (void) pager_open(arg_pager_flags
);
5928 /* If no argument is specified inspect the manager itself */
5929 if (show_mode
== SYSTEMCTL_SHOW_PROPERTIES
&& argc
<= 1)
5930 return show_one(bus
, "/org/freedesktop/systemd1", NULL
, show_mode
, &new_line
, &ellipsized
);
5932 if (show_mode
== SYSTEMCTL_SHOW_STATUS
&& argc
<= 1) {
5934 show_system_status(bus
);
5938 ret
= show_all(bus
, &new_line
, &ellipsized
);
5940 _cleanup_free_
char **patterns
= NULL
;
5943 STRV_FOREACH(name
, strv_skip(argv
, 1)) {
5944 _cleanup_free_
char *path
= NULL
, *unit
= NULL
;
5947 if (safe_atou32(*name
, &id
) < 0) {
5948 if (strv_push(&patterns
, *name
) < 0)
5952 } else if (show_mode
== SYSTEMCTL_SHOW_PROPERTIES
) {
5953 /* Interpret as job id */
5954 if (asprintf(&path
, "/org/freedesktop/systemd1/job/%u", id
) < 0)
5958 /* Interpret as PID */
5959 r
= get_unit_dbus_path_by_pid(bus
, id
, &path
);
5965 r
= unit_name_from_dbus_path(path
, &unit
);
5970 r
= show_one(bus
, path
, unit
, show_mode
, &new_line
, &ellipsized
);
5973 else if (r
> 0 && ret
== 0)
5977 if (!strv_isempty(patterns
)) {
5978 _cleanup_strv_free_
char **names
= NULL
;
5980 r
= expand_names(bus
, patterns
, NULL
, &names
, NULL
);
5982 return log_error_errno(r
, "Failed to expand names: %m");
5984 r
= maybe_extend_with_unit_dependencies(bus
, &names
);
5988 STRV_FOREACH(name
, names
) {
5989 _cleanup_free_
char *path
;
5991 path
= unit_dbus_path_from_name(*name
);
5995 r
= show_one(bus
, path
, *name
, show_mode
, &new_line
, &ellipsized
);
5998 if (r
> 0 && ret
== 0)
6004 if (ellipsized
&& !arg_quiet
)
6005 printf("Hint: Some lines were ellipsized, use -l to show in full.\n");
6010 static int cat(int argc
, char *argv
[], void *userdata
) {
6011 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
6012 _cleanup_strv_free_
char **names
= NULL
;
6018 /* Include all units by default — i.e. continue as if the --all
6019 * option was used */
6020 if (strv_isempty(arg_states
))
6023 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
6024 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot remotely cat units.");
6026 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
6028 return log_error_errno(r
, "Failed to determine unit paths: %m");
6030 r
= acquire_bus(BUS_MANAGER
, &bus
);
6034 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
6036 return log_error_errno(r
, "Failed to expand names: %m");
6038 r
= maybe_extend_with_unit_dependencies(bus
, &names
);
6042 (void) pager_open(arg_pager_flags
);
6044 STRV_FOREACH(name
, names
) {
6045 _cleanup_free_
char *fragment_path
= NULL
;
6046 _cleanup_strv_free_
char **dropin_paths
= NULL
;
6048 r
= unit_find_paths(bus
, *name
, &lp
, false, &fragment_path
, &dropin_paths
);
6049 if (r
== -ERFKILL
) {
6050 printf("%s# Unit %s is masked%s.\n",
6051 ansi_highlight_magenta(),
6056 if (r
== -EKEYREJECTED
) {
6057 printf("%s# Unit %s could not be loaded.%s\n",
6058 ansi_highlight_magenta(),
6066 /* Skip units which have no on-disk counterpart, but
6067 * propagate the error to the user */
6077 if (need_daemon_reload(bus
, *name
) > 0) /* ignore errors (<0), this is informational output */
6079 "%s# Warning: %s changed on disk, the version systemd has loaded is outdated.\n"
6080 "%s# This output shows the current version of the unit's original fragment and drop-in files.\n"
6081 "%s# If fragments or drop-ins were added or removed, they are not properly reflected in this output.\n"
6082 "%s# Run 'systemctl%s daemon-reload' to reload units.%s\n",
6083 ansi_highlight_red(),
6085 ansi_highlight_red(),
6086 ansi_highlight_red(),
6087 ansi_highlight_red(),
6088 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user",
6091 r
= cat_files(fragment_path
, dropin_paths
, 0);
6099 static int set_property(int argc
, char *argv
[], void *userdata
) {
6100 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6101 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6102 _cleanup_free_
char *n
= NULL
;
6107 r
= acquire_bus(BUS_MANAGER
, &bus
);
6111 polkit_agent_open_maybe();
6113 r
= sd_bus_message_new_method_call(
6116 "org.freedesktop.systemd1",
6117 "/org/freedesktop/systemd1",
6118 "org.freedesktop.systemd1.Manager",
6119 "SetUnitProperties");
6121 return bus_log_create_error(r
);
6123 r
= unit_name_mangle(argv
[1], arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, &n
);
6125 return log_error_errno(r
, "Failed to mangle unit name: %m");
6127 t
= unit_name_to_type(n
);
6129 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid unit type: %s", n
);
6131 r
= sd_bus_message_append(m
, "sb", n
, arg_runtime
);
6133 return bus_log_create_error(r
);
6135 r
= sd_bus_message_open_container(m
, SD_BUS_TYPE_ARRAY
, "(sv)");
6137 return bus_log_create_error(r
);
6139 r
= bus_append_unit_property_assignment_many(m
, t
, strv_skip(argv
, 2));
6143 r
= sd_bus_message_close_container(m
);
6145 return bus_log_create_error(r
);
6147 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6149 return log_error_errno(r
, "Failed to set unit properties on %s: %s", n
, bus_error_message(&error
, r
));
6154 static int daemon_reload(int argc
, char *argv
[], void *userdata
) {
6155 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6156 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6161 r
= acquire_bus(BUS_MANAGER
, &bus
);
6165 polkit_agent_open_maybe();
6167 switch (arg_action
) {
6174 method
= "Reexecute";
6177 case ACTION_SYSTEMCTL
:
6178 method
= streq(argv
[0], "daemon-reexec") ? "Reexecute" :
6179 /* "daemon-reload" */ "Reload";
6183 assert_not_reached("Unexpected action");
6186 r
= sd_bus_message_new_method_call(
6189 "org.freedesktop.systemd1",
6190 "/org/freedesktop/systemd1",
6191 "org.freedesktop.systemd1.Manager",
6194 return bus_log_create_error(r
);
6196 /* Note we use an extra-long timeout here. This is because a reload or reexec means generators are rerun which
6197 * are timed out after DEFAULT_TIMEOUT_USEC. Let's use twice that time here, so that the generators can have
6198 * their timeout, and for everything else there's the same time budget in place. */
6200 r
= sd_bus_call(bus
, m
, DEFAULT_TIMEOUT_USEC
* 2, &error
, NULL
);
6202 /* On reexecution, we expect a disconnect, not a reply */
6203 if (IN_SET(r
, -ETIMEDOUT
, -ECONNRESET
) && streq(method
, "Reexecute"))
6206 if (r
< 0 && arg_action
== ACTION_SYSTEMCTL
)
6207 return log_error_errno(r
, "Failed to reload daemon: %s", bus_error_message(&error
, r
));
6209 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
6210 * old ways of doing things, hence don't log any error in that case here. */
6212 return r
< 0 ? r
: 0;
6215 static int trivial_method(int argc
, char *argv
[], void *userdata
) {
6216 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6224 r
= acquire_bus(BUS_MANAGER
, &bus
);
6228 polkit_agent_open_maybe();
6231 streq(argv
[0], "clear-jobs") ||
6232 streq(argv
[0], "cancel") ? "ClearJobs" :
6233 streq(argv
[0], "reset-failed") ? "ResetFailed" :
6234 streq(argv
[0], "halt") ? "Halt" :
6235 streq(argv
[0], "reboot") ? "Reboot" :
6236 streq(argv
[0], "kexec") ? "KExec" :
6237 streq(argv
[0], "exit") ? "Exit" :
6238 /* poweroff */ "PowerOff";
6240 r
= sd_bus_call_method(
6242 "org.freedesktop.systemd1",
6243 "/org/freedesktop/systemd1",
6244 "org.freedesktop.systemd1.Manager",
6249 if (r
< 0 && arg_action
== ACTION_SYSTEMCTL
)
6250 return log_error_errno(r
, "Failed to execute operation: %s", bus_error_message(&error
, r
));
6252 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
6253 * old ways of doing things, hence don't log any error in that case here. */
6255 return r
< 0 ? r
: 0;
6258 static int reset_failed(int argc
, char *argv
[], void *userdata
) {
6259 _cleanup_strv_free_
char **names
= NULL
;
6265 return trivial_method(argc
, argv
, userdata
);
6267 r
= acquire_bus(BUS_MANAGER
, &bus
);
6271 polkit_agent_open_maybe();
6273 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
6275 return log_error_errno(r
, "Failed to expand names: %m");
6277 STRV_FOREACH(name
, names
) {
6278 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6280 q
= sd_bus_call_method(
6282 "org.freedesktop.systemd1",
6283 "/org/freedesktop/systemd1",
6284 "org.freedesktop.systemd1.Manager",
6290 log_error_errno(q
, "Failed to reset failed state of unit %s: %s", *name
, bus_error_message(&error
, q
));
6299 static int print_variable(const char *s
) {
6301 _cleanup_free_
char *esc
= NULL
;
6303 sep
= strchr(s
, '=');
6305 return log_error_errno(SYNTHETIC_ERRNO(EUCLEAN
),
6306 "Invalid environment block");
6308 esc
= shell_maybe_quote(sep
+ 1, ESCAPE_POSIX
);
6312 printf("%.*s=%s\n", (int)(sep
-s
), s
, esc
);
6316 static int show_environment(int argc
, char *argv
[], void *userdata
) {
6317 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6318 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
6323 r
= acquire_bus(BUS_MANAGER
, &bus
);
6327 (void) pager_open(arg_pager_flags
);
6329 r
= sd_bus_get_property(
6331 "org.freedesktop.systemd1",
6332 "/org/freedesktop/systemd1",
6333 "org.freedesktop.systemd1.Manager",
6339 return log_error_errno(r
, "Failed to get environment: %s", bus_error_message(&error
, r
));
6341 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "s");
6343 return bus_log_parse_error(r
);
6345 while ((r
= sd_bus_message_read_basic(reply
, SD_BUS_TYPE_STRING
, &text
)) > 0) {
6346 r
= print_variable(text
);
6351 return bus_log_parse_error(r
);
6353 r
= sd_bus_message_exit_container(reply
);
6355 return bus_log_parse_error(r
);
6360 static int switch_root(int argc
, char *argv
[], void *userdata
) {
6361 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6362 _cleanup_free_
char *cmdline_init
= NULL
;
6363 const char *root
, *init
;
6367 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
6368 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot switch root remotely.");
6370 if (argc
< 2 || argc
> 3)
6371 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Wrong number of arguments.");
6378 r
= proc_cmdline_get_key("init", 0, &cmdline_init
);
6380 log_debug_errno(r
, "Failed to parse /proc/cmdline: %m");
6382 init
= cmdline_init
;
6385 init
= empty_to_null(init
);
6387 const char *root_systemd_path
= NULL
, *root_init_path
= NULL
;
6389 root_systemd_path
= prefix_roota(root
, "/" SYSTEMD_BINARY_PATH
);
6390 root_init_path
= prefix_roota(root
, init
);
6392 /* If the passed init is actually the same as the
6393 * systemd binary, then let's suppress it. */
6394 if (files_same(root_init_path
, root_systemd_path
, 0) > 0)
6398 /* Instruct PID1 to exclude us from its killing spree applied during the transition. Otherwise we
6399 * would exit with a failure status even though the switch to the new root has succeed. */
6401 assert(saved_argv
[0]);
6402 saved_argv
[0][0] = '@';
6404 r
= acquire_bus(BUS_MANAGER
, &bus
);
6408 /* If we are slow to exit after the root switch, the new systemd instance
6409 * will send us a signal to terminate. Just ignore it and exit normally.
6410 * This way the unit does not end up as failed.
6412 r
= ignore_signals(SIGTERM
, -1);
6414 log_warning_errno(r
, "Failed to change disposition of SIGTERM to ignore: %m");
6416 log_debug("Switching root - root: %s; init: %s", root
, strna(init
));
6418 r
= sd_bus_call_method(
6420 "org.freedesktop.systemd1",
6421 "/org/freedesktop/systemd1",
6422 "org.freedesktop.systemd1.Manager",
6428 (void) default_signals(SIGTERM
, -1);
6430 return log_error_errno(r
, "Failed to switch root: %s", bus_error_message(&error
, r
));
6436 static int log_level(int argc
, char *argv
[], void *userdata
) {
6438 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6441 r
= acquire_bus(BUS_MANAGER
, &bus
);
6446 _cleanup_free_
char *level
= NULL
;
6448 r
= sd_bus_get_property_string(
6450 "org.freedesktop.systemd1",
6451 "/org/freedesktop/systemd1",
6452 "org.freedesktop.systemd1.Manager",
6457 return log_error_errno(r
, "Failed to get log level: %s", bus_error_message(&error
, r
));
6464 r
= sd_bus_set_property(
6466 "org.freedesktop.systemd1",
6467 "/org/freedesktop/systemd1",
6468 "org.freedesktop.systemd1.Manager",
6474 return log_error_errno(r
, "Failed to set log level: %s", bus_error_message(&error
, r
));
6480 static int log_target(int argc
, char *argv
[], void *userdata
) {
6482 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6485 r
= acquire_bus(BUS_MANAGER
, &bus
);
6490 _cleanup_free_
char *target
= NULL
;
6492 r
= sd_bus_get_property_string(
6494 "org.freedesktop.systemd1",
6495 "/org/freedesktop/systemd1",
6496 "org.freedesktop.systemd1.Manager",
6501 return log_error_errno(r
, "Failed to get log target: %s", bus_error_message(&error
, r
));
6508 r
= sd_bus_set_property(
6510 "org.freedesktop.systemd1",
6511 "/org/freedesktop/systemd1",
6512 "org.freedesktop.systemd1.Manager",
6518 return log_error_errno(r
, "Failed to set log target: %s", bus_error_message(&error
, r
));
6524 static int service_watchdogs(int argc
, char *argv
[], void *userdata
) {
6526 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6531 r
= acquire_bus(BUS_MANAGER
, &bus
);
6536 /* get ServiceWatchdogs */
6537 r
= sd_bus_get_property_trivial(
6539 "org.freedesktop.systemd1",
6540 "/org/freedesktop/systemd1",
6541 "org.freedesktop.systemd1.Manager",
6547 return log_error_errno(r
, "Failed to get service-watchdog state: %s", bus_error_message(&error
, r
));
6549 printf("%s\n", yes_no(!!b
));
6552 /* set ServiceWatchdogs */
6555 b
= parse_boolean(argv
[1]);
6557 return log_error_errno(b
, "Failed to parse service-watchdogs argument: %m");
6559 r
= sd_bus_set_property(
6561 "org.freedesktop.systemd1",
6562 "/org/freedesktop/systemd1",
6563 "org.freedesktop.systemd1.Manager",
6569 return log_error_errno(r
, "Failed to set service-watchdog state: %s", bus_error_message(&error
, r
));
6575 static int set_environment(int argc
, char *argv
[], void *userdata
) {
6576 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6577 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6585 r
= acquire_bus(BUS_MANAGER
, &bus
);
6589 polkit_agent_open_maybe();
6591 method
= streq(argv
[0], "set-environment")
6593 : "UnsetEnvironment";
6595 r
= sd_bus_message_new_method_call(
6598 "org.freedesktop.systemd1",
6599 "/org/freedesktop/systemd1",
6600 "org.freedesktop.systemd1.Manager",
6603 return bus_log_create_error(r
);
6605 r
= sd_bus_message_append_strv(m
, strv_skip(argv
, 1));
6607 return bus_log_create_error(r
);
6609 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6611 return log_error_errno(r
, "Failed to set environment: %s", bus_error_message(&error
, r
));
6616 static int import_environment(int argc
, char *argv
[], void *userdata
) {
6617 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6618 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6622 r
= acquire_bus(BUS_MANAGER
, &bus
);
6626 polkit_agent_open_maybe();
6628 r
= sd_bus_message_new_method_call(
6631 "org.freedesktop.systemd1",
6632 "/org/freedesktop/systemd1",
6633 "org.freedesktop.systemd1.Manager",
6636 return bus_log_create_error(r
);
6639 r
= sd_bus_message_append_strv(m
, environ
);
6643 r
= sd_bus_message_open_container(m
, 'a', "s");
6645 return bus_log_create_error(r
);
6647 STRV_FOREACH(a
, strv_skip(argv
, 1)) {
6649 if (!env_name_is_valid(*a
))
6650 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Not a valid environment variable name: %s", *a
);
6652 STRV_FOREACH(b
, environ
) {
6655 eq
= startswith(*b
, *a
);
6656 if (eq
&& *eq
== '=') {
6658 r
= sd_bus_message_append(m
, "s", *b
);
6660 return bus_log_create_error(r
);
6667 r
= sd_bus_message_close_container(m
);
6670 return bus_log_create_error(r
);
6672 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6674 return log_error_errno(r
, "Failed to import environment: %s", bus_error_message(&error
, r
));
6679 static int enable_sysv_units(const char *verb
, char **args
) {
6682 #if HAVE_SYSV_COMPAT
6683 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
6686 /* Processes all SysV units, and reshuffles the array so that afterwards only the native units remain */
6688 if (arg_scope
!= UNIT_FILE_SYSTEM
)
6691 if (getenv_bool("SYSTEMCTL_SKIP_SYSV") > 0)
6694 if (!STR_IN_SET(verb
,
6700 r
= lookup_paths_init(&paths
, arg_scope
, LOOKUP_PATHS_EXCLUDE_GENERATED
, arg_root
);
6707 const char *argv
[] = {
6708 ROOTLIBEXECDIR
"/systemd-sysv-install",
6715 _cleanup_free_
char *p
= NULL
, *q
= NULL
, *l
= NULL
, *v
= NULL
;
6716 bool found_native
= false, found_sysv
;
6724 if (!endswith(name
, ".service"))
6727 if (path_is_absolute(name
))
6730 j
= unit_file_exists(arg_scope
, &paths
, name
);
6731 if (j
< 0 && !IN_SET(j
, -ELOOP
, -ERFKILL
, -EADDRNOTAVAIL
))
6732 return log_error_errno(j
, "Failed to look up unit file state: %m");
6733 found_native
= j
!= 0;
6735 /* If we have both a native unit and a SysV script, enable/disable them both (below); for is-enabled,
6736 * prefer the native unit */
6737 if (found_native
&& streq(verb
, "is-enabled"))
6740 p
= path_join(arg_root
, SYSTEM_SYSVINIT_PATH
, name
);
6744 p
[strlen(p
) - STRLEN(".service")] = 0;
6745 found_sysv
= access(p
, F_OK
) >= 0;
6751 log_info("Synchronizing state of %s with SysV service script with %s.", name
, argv
[0]);
6753 log_info("%s is not a native service, redirecting to systemd-sysv-install.", name
);
6756 if (!isempty(arg_root
)) {
6757 q
= strjoin("--root=", arg_root
);
6764 /* Let's copy the verb, since it's still pointing directly into the original argv[] array we
6765 * got passed, but safe_fork() is likely going to rewrite that for the new child */
6771 argv
[c
++] = basename(p
);
6774 l
= strv_join((char**)argv
, " ");
6779 log_info("Executing: %s", l
);
6781 j
= safe_fork("(sysv-install)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
, &pid
);
6786 execv(argv
[0], (char**) argv
);
6787 log_error_errno(errno
, "Failed to execute %s: %m", argv
[0]);
6788 _exit(EXIT_FAILURE
);
6791 j
= wait_for_terminate_and_check("sysv-install", pid
, WAIT_LOG_ABNORMAL
);
6794 if (streq(verb
, "is-enabled")) {
6795 if (j
== EXIT_SUCCESS
) {
6804 } else if (j
!= EXIT_SUCCESS
)
6805 return -EBADE
; /* We don't warn here, under the assumption the script already showed an explanation */
6810 /* Remove this entry, so that we don't try enabling it as native unit */
6813 assert(args
[f
] == name
);
6814 strv_remove(args
+ f
, name
);
6821 static int mangle_names(const char *operation
, char **original_names
, char ***mangled_names
) {
6822 char **i
, **l
, **name
;
6825 l
= i
= new(char*, strv_length(original_names
) + 1);
6829 STRV_FOREACH(name
, original_names
) {
6831 /* When enabling units qualified path names are OK,
6832 * too, hence allow them explicitly. */
6834 if (is_path(*name
)) {
6841 r
= unit_name_mangle_with_suffix(*name
, operation
,
6842 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
6847 return log_error_errno(r
, "Failed to mangle unit name: %m");
6860 static int normalize_filenames(char **names
) {
6864 STRV_FOREACH(u
, names
)
6865 if (!path_is_absolute(*u
)) {
6866 char* normalized_path
;
6868 if (!isempty(arg_root
))
6869 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6870 "Non-absolute paths are not allowed when --root is used: %s",
6873 if (!strchr(*u
,'/'))
6874 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6875 "Link argument does contain at least one directory separator: %s",
6878 r
= path_make_absolute_cwd(*u
, &normalized_path
);
6882 free_and_replace(*u
, normalized_path
);
6888 static int normalize_names(char **names
, bool warn_if_path
) {
6890 bool was_path
= false;
6892 STRV_FOREACH(u
, names
) {
6898 r
= free_and_strdup(u
, basename(*u
));
6900 return log_error_errno(r
, "Failed to normalize unit file path: %m");
6905 if (warn_if_path
&& was_path
)
6906 log_warning("Warning: Can't execute disable on the unit file path. Proceeding with the unit name.");
6911 static int unit_exists(LookupPaths
*lp
, const char *unit
) {
6912 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6913 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6914 _cleanup_free_
char *path
= NULL
;
6915 static const struct bus_properties_map property_map
[] = {
6916 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
6917 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
)},
6920 UnitStatusInfo info
= {};
6924 if (unit_name_is_valid(unit
, UNIT_NAME_TEMPLATE
))
6925 return unit_find_template_path(unit
, lp
, NULL
, NULL
);
6927 path
= unit_dbus_path_from_name(unit
);
6931 r
= acquire_bus(BUS_MANAGER
, &bus
);
6935 r
= bus_map_all_properties(bus
, "org.freedesktop.systemd1", path
, property_map
, 0, &error
, &m
, &info
);
6937 return log_error_errno(r
, "Failed to get properties: %s", bus_error_message(&error
, r
));
6939 return !streq_ptr(info
.load_state
, "not-found") || !streq_ptr(info
.active_state
, "inactive");
6942 static int enable_unit(int argc
, char *argv
[], void *userdata
) {
6943 _cleanup_strv_free_
char **names
= NULL
;
6944 const char *verb
= argv
[0];
6945 UnitFileChange
*changes
= NULL
;
6946 size_t n_changes
= 0;
6947 int carries_install_info
= -1;
6948 bool ignore_carries_install_info
= arg_quiet
;
6954 r
= mangle_names("to enable", strv_skip(argv
, 1), &names
);
6958 r
= enable_sysv_units(verb
, names
);
6962 /* If the operation was fully executed by the SysV compat, let's finish early */
6963 if (strv_isempty(names
)) {
6964 if (arg_no_reload
|| install_client_side())
6966 return daemon_reload(argc
, argv
, userdata
);
6969 if (streq(verb
, "disable")) {
6970 r
= normalize_names(names
, true);
6975 if (streq(verb
, "link")) {
6976 r
= normalize_filenames(names
);
6981 if (install_client_side()) {
6982 UnitFileFlags flags
;
6984 flags
= args_to_flags();
6985 if (streq(verb
, "enable")) {
6986 r
= unit_file_enable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6987 carries_install_info
= r
;
6988 } else if (streq(verb
, "disable"))
6989 r
= unit_file_disable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6990 else if (streq(verb
, "reenable")) {
6991 r
= unit_file_reenable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6992 carries_install_info
= r
;
6993 } else if (streq(verb
, "link"))
6994 r
= unit_file_link(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6995 else if (streq(verb
, "preset")) {
6996 r
= unit_file_preset(arg_scope
, flags
, arg_root
, names
, arg_preset_mode
, &changes
, &n_changes
);
6997 } else if (streq(verb
, "mask"))
6998 r
= unit_file_mask(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6999 else if (streq(verb
, "unmask"))
7000 r
= unit_file_unmask(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
7001 else if (streq(verb
, "revert"))
7002 r
= unit_file_revert(arg_scope
, arg_root
, names
, &changes
, &n_changes
);
7004 assert_not_reached("Unknown verb");
7006 unit_file_dump_changes(r
, verb
, changes
, n_changes
, arg_quiet
);
7011 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
, *m
= NULL
;
7012 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7013 bool expect_carries_install_info
= false;
7014 bool send_runtime
= true, send_force
= true, send_preset_mode
= false;
7018 if (STR_IN_SET(verb
, "mask", "unmask")) {
7020 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
7022 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
7026 STRV_FOREACH(name
, names
) {
7027 r
= unit_exists(&lp
, *name
);
7031 log_notice("Unit %s does not exist, proceeding anyway.", *name
);
7035 r
= acquire_bus(BUS_MANAGER
, &bus
);
7039 polkit_agent_open_maybe();
7041 if (streq(verb
, "enable")) {
7042 method
= "EnableUnitFiles";
7043 expect_carries_install_info
= true;
7044 } else if (streq(verb
, "disable")) {
7045 method
= "DisableUnitFiles";
7047 } else if (streq(verb
, "reenable")) {
7048 method
= "ReenableUnitFiles";
7049 expect_carries_install_info
= true;
7050 } else if (streq(verb
, "link"))
7051 method
= "LinkUnitFiles";
7052 else if (streq(verb
, "preset")) {
7054 if (arg_preset_mode
!= UNIT_FILE_PRESET_FULL
) {
7055 method
= "PresetUnitFilesWithMode";
7056 send_preset_mode
= true;
7058 method
= "PresetUnitFiles";
7060 expect_carries_install_info
= true;
7061 ignore_carries_install_info
= true;
7062 } else if (streq(verb
, "mask"))
7063 method
= "MaskUnitFiles";
7064 else if (streq(verb
, "unmask")) {
7065 method
= "UnmaskUnitFiles";
7067 } else if (streq(verb
, "revert")) {
7068 method
= "RevertUnitFiles";
7069 send_runtime
= send_force
= false;
7071 assert_not_reached("Unknown verb");
7073 r
= sd_bus_message_new_method_call(
7076 "org.freedesktop.systemd1",
7077 "/org/freedesktop/systemd1",
7078 "org.freedesktop.systemd1.Manager",
7081 return bus_log_create_error(r
);
7083 r
= sd_bus_message_append_strv(m
, names
);
7085 return bus_log_create_error(r
);
7087 if (send_preset_mode
) {
7088 r
= sd_bus_message_append(m
, "s", unit_file_preset_mode_to_string(arg_preset_mode
));
7090 return bus_log_create_error(r
);
7094 r
= sd_bus_message_append(m
, "b", arg_runtime
);
7096 return bus_log_create_error(r
);
7100 r
= sd_bus_message_append(m
, "b", arg_force
);
7102 return bus_log_create_error(r
);
7105 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
7107 return log_error_errno(r
, "Failed to %s unit: %s", verb
, bus_error_message(&error
, r
));
7109 if (expect_carries_install_info
) {
7110 r
= sd_bus_message_read(reply
, "b", &carries_install_info
);
7112 return bus_log_parse_error(r
);
7115 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
7119 /* Try to reload if enabled */
7121 r
= daemon_reload(argc
, argv
, userdata
);
7126 if (carries_install_info
== 0 && !ignore_carries_install_info
)
7127 log_notice("The unit files have no installation config (WantedBy=, RequiredBy=, Also=,\n"
7128 "Alias= settings in the [Install] section, and DefaultInstance= for template\n"
7129 "units). This means they are not meant to be enabled using systemctl.\n"
7130 " \n" /* trick: the space is needed so that the line does not get stripped from output */
7131 "Possible reasons for having this kind of units are:\n"
7132 "%1$s A unit may be statically enabled by being symlinked from another unit's\n"
7133 " .wants/ or .requires/ directory.\n"
7134 "%1$s A unit's purpose may be to act as a helper for some other unit which has\n"
7135 " a requirement dependency on it.\n"
7136 "%1$s A unit may be started when needed via activation (socket, path, timer,\n"
7137 " D-Bus, udev, scripted systemctl call, ...).\n"
7138 "%1$s In case of template units, the unit is meant to be enabled with some\n"
7139 " instance name specified.",
7140 special_glyph(SPECIAL_GLYPH_BULLET
));
7142 if (arg_now
&& STR_IN_SET(argv
[0], "enable", "disable", "mask")) {
7146 r
= acquire_bus(BUS_MANAGER
, &bus
);
7150 len
= strv_length(names
);
7152 char *new_args
[len
+ 2];
7154 new_args
[0] = (char*) (streq(argv
[0], "enable") ? "start" : "stop");
7155 for (i
= 0; i
< len
; i
++)
7156 new_args
[i
+ 1] = basename(names
[i
]);
7157 new_args
[i
+ 1] = NULL
;
7159 r
= start_unit(len
+ 1, new_args
, userdata
);
7164 unit_file_changes_free(changes
, n_changes
);
7169 static int add_dependency(int argc
, char *argv
[], void *userdata
) {
7170 _cleanup_strv_free_
char **names
= NULL
;
7171 _cleanup_free_
char *target
= NULL
;
7172 const char *verb
= argv
[0];
7173 UnitFileChange
*changes
= NULL
;
7174 size_t n_changes
= 0;
7181 r
= unit_name_mangle_with_suffix(argv
[1], "as target",
7182 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
7183 ".target", &target
);
7185 return log_error_errno(r
, "Failed to mangle unit name: %m");
7187 r
= mangle_names("as dependency", strv_skip(argv
, 2), &names
);
7191 if (streq(verb
, "add-wants"))
7193 else if (streq(verb
, "add-requires"))
7194 dep
= UNIT_REQUIRES
;
7196 assert_not_reached("Unknown verb");
7198 if (install_client_side()) {
7199 r
= unit_file_add_dependency(arg_scope
, args_to_flags(), arg_root
, names
, target
, dep
, &changes
, &n_changes
);
7200 unit_file_dump_changes(r
, "add dependency on", changes
, n_changes
, arg_quiet
);
7205 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
, *m
= NULL
;
7206 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7209 r
= acquire_bus(BUS_MANAGER
, &bus
);
7213 polkit_agent_open_maybe();
7215 r
= sd_bus_message_new_method_call(
7218 "org.freedesktop.systemd1",
7219 "/org/freedesktop/systemd1",
7220 "org.freedesktop.systemd1.Manager",
7221 "AddDependencyUnitFiles");
7223 return bus_log_create_error(r
);
7225 r
= sd_bus_message_append_strv(m
, names
);
7227 return bus_log_create_error(r
);
7229 r
= sd_bus_message_append(m
, "ssbb", target
, unit_dependency_to_string(dep
), arg_runtime
, arg_force
);
7231 return bus_log_create_error(r
);
7233 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
7235 return log_error_errno(r
, "Failed to add dependency: %s", bus_error_message(&error
, r
));
7237 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
7241 if (arg_no_reload
) {
7246 r
= daemon_reload(argc
, argv
, userdata
);
7250 unit_file_changes_free(changes
, n_changes
);
7255 static int preset_all(int argc
, char *argv
[], void *userdata
) {
7256 UnitFileChange
*changes
= NULL
;
7257 size_t n_changes
= 0;
7260 if (install_client_side()) {
7261 r
= unit_file_preset_all(arg_scope
, args_to_flags(), arg_root
, arg_preset_mode
, &changes
, &n_changes
);
7262 unit_file_dump_changes(r
, "preset", changes
, n_changes
, arg_quiet
);
7267 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7268 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7271 r
= acquire_bus(BUS_MANAGER
, &bus
);
7275 polkit_agent_open_maybe();
7277 r
= sd_bus_call_method(
7279 "org.freedesktop.systemd1",
7280 "/org/freedesktop/systemd1",
7281 "org.freedesktop.systemd1.Manager",
7282 "PresetAllUnitFiles",
7286 unit_file_preset_mode_to_string(arg_preset_mode
),
7290 return log_error_errno(r
, "Failed to preset all units: %s", bus_error_message(&error
, r
));
7292 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
7296 if (arg_no_reload
) {
7301 r
= daemon_reload(argc
, argv
, userdata
);
7305 unit_file_changes_free(changes
, n_changes
);
7310 static int show_installation_targets_client_side(const char *name
) {
7311 UnitFileChange
*changes
= NULL
;
7312 size_t n_changes
= 0, i
;
7313 UnitFileFlags flags
;
7317 p
= STRV_MAKE(name
);
7318 flags
= UNIT_FILE_DRY_RUN
|
7319 (arg_runtime
? UNIT_FILE_RUNTIME
: 0);
7321 r
= unit_file_disable(UNIT_FILE_SYSTEM
, flags
, NULL
, p
, &changes
, &n_changes
);
7323 return log_error_errno(r
, "Failed to get file links for %s: %m", name
);
7325 for (i
= 0; i
< n_changes
; i
++)
7326 if (changes
[i
].type
== UNIT_FILE_UNLINK
)
7327 printf(" %s\n", changes
[i
].path
);
7332 static int show_installation_targets(sd_bus
*bus
, const char *name
) {
7333 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7334 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7338 r
= sd_bus_call_method(
7340 "org.freedesktop.systemd1",
7341 "/org/freedesktop/systemd1",
7342 "org.freedesktop.systemd1.Manager",
7346 "sb", name
, arg_runtime
);
7348 return log_error_errno(r
, "Failed to get unit file links for %s: %s", name
, bus_error_message(&error
, r
));
7350 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "s");
7352 return bus_log_parse_error(r
);
7354 while ((r
= sd_bus_message_read(reply
, "s", &link
)) > 0)
7355 printf(" %s\n", link
);
7358 return bus_log_parse_error(r
);
7360 r
= sd_bus_message_exit_container(reply
);
7362 return bus_log_parse_error(r
);
7367 static int unit_is_enabled(int argc
, char *argv
[], void *userdata
) {
7368 _cleanup_strv_free_
char **names
= NULL
;
7373 r
= mangle_names("to check", strv_skip(argv
, 1), &names
);
7377 r
= enable_sysv_units(argv
[0], names
);
7383 if (install_client_side()) {
7384 STRV_FOREACH(name
, names
) {
7385 UnitFileState state
;
7387 r
= unit_file_get_state(arg_scope
, arg_root
, *name
, &state
);
7389 return log_error_errno(r
, "Failed to get unit file state for %s: %m", *name
);
7393 UNIT_FILE_ENABLED_RUNTIME
,
7397 UNIT_FILE_GENERATED
))
7401 puts(unit_file_state_to_string(state
));
7403 r
= show_installation_targets_client_side(*name
);
7412 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7415 r
= acquire_bus(BUS_MANAGER
, &bus
);
7419 STRV_FOREACH(name
, names
) {
7420 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7423 r
= sd_bus_call_method(
7425 "org.freedesktop.systemd1",
7426 "/org/freedesktop/systemd1",
7427 "org.freedesktop.systemd1.Manager",
7433 return log_error_errno(r
, "Failed to get unit file state for %s: %s", *name
, bus_error_message(&error
, r
));
7435 r
= sd_bus_message_read(reply
, "s", &s
);
7437 return bus_log_parse_error(r
);
7439 if (STR_IN_SET(s
, "enabled", "enabled-runtime", "static", "indirect", "generated"))
7445 r
= show_installation_targets(bus
, *name
);
7453 return enabled
? EXIT_SUCCESS
: EXIT_FAILURE
;
7456 static int match_startup_finished(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
7457 char **state
= userdata
;
7462 r
= sd_bus_get_property_string(
7463 sd_bus_message_get_bus(m
),
7464 "org.freedesktop.systemd1",
7465 "/org/freedesktop/systemd1",
7466 "org.freedesktop.systemd1.Manager",
7471 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m
)), r
);
7475 static int is_system_running(int argc
, char *argv
[], void *userdata
) {
7476 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7477 _cleanup_(sd_bus_slot_unrefp
) sd_bus_slot
*slot_startup_finished
= NULL
;
7478 _cleanup_(sd_event_unrefp
) sd_event
* event
= NULL
;
7479 _cleanup_free_
char *state
= NULL
;
7483 if (running_in_chroot() > 0 || (arg_transport
== BUS_TRANSPORT_LOCAL
&& !sd_booted())) {
7486 return EXIT_FAILURE
;
7489 r
= acquire_bus(BUS_MANAGER
, &bus
);
7494 r
= sd_event_default(&event
);
7496 r
= sd_bus_attach_event(bus
, event
, 0);
7498 r
= sd_bus_match_signal_async(
7500 &slot_startup_finished
,
7501 "org.freedesktop.systemd1",
7502 "/org/freedesktop/systemd1",
7503 "org.freedesktop.systemd1.Manager",
7505 match_startup_finished
, NULL
, &state
);
7507 log_warning_errno(r
, "Failed to request match for StartupFinished: %m");
7512 r
= sd_bus_get_property_string(
7514 "org.freedesktop.systemd1",
7515 "/org/freedesktop/systemd1",
7516 "org.freedesktop.systemd1.Manager",
7521 log_warning_errno(r
, "Failed to query system state: %s", bus_error_message(&error
, r
));
7525 return EXIT_FAILURE
;
7528 if (arg_wait
&& STR_IN_SET(state
, "initializing", "starting")) {
7529 r
= sd_event_loop(event
);
7531 log_warning_errno(r
, "Failed to get property from event loop: %m");
7534 return EXIT_FAILURE
;
7541 return streq(state
, "running") ? EXIT_SUCCESS
: EXIT_FAILURE
;
7544 static int create_edit_temp_file(const char *new_path
, const char *original_path
, char **ret_tmp_fn
) {
7545 _cleanup_free_
char *t
= NULL
;
7549 assert(original_path
);
7552 r
= tempfn_random(new_path
, NULL
, &t
);
7554 return log_error_errno(r
, "Failed to determine temporary filename for \"%s\": %m", new_path
);
7556 r
= mkdir_parents(new_path
, 0755);
7558 return log_error_errno(r
, "Failed to create directories for \"%s\": %m", new_path
);
7560 r
= copy_file(original_path
, t
, 0, 0644, 0, 0, COPY_REFLINK
);
7565 return log_error_errno(r
, "Failed to create temporary file \"%s\": %m", t
);
7568 return log_error_errno(r
, "Failed to create temporary file for \"%s\": %m", new_path
);
7570 *ret_tmp_fn
= TAKE_PTR(t
);
7575 static int get_file_to_edit(
7576 const LookupPaths
*paths
,
7580 _cleanup_free_
char *path
= NULL
, *run
= NULL
;
7585 path
= path_join(paths
->persistent_config
, name
);
7590 run
= path_join(paths
->runtime_config
, name
);
7596 if (access(path
, F_OK
) >= 0)
7597 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
7598 "Refusing to create \"%s\" because it would be overridden by \"%s\" anyway.",
7601 *ret_path
= TAKE_PTR(run
);
7603 *ret_path
= TAKE_PTR(path
);
7608 static int unit_file_create_new(
7609 const LookupPaths
*paths
,
7610 const char *unit_name
,
7612 char **ret_new_path
,
7613 char **ret_tmp_path
) {
7615 _cleanup_free_
char *new_path
= NULL
, *tmp_path
= NULL
;
7620 assert(ret_new_path
);
7621 assert(ret_tmp_path
);
7623 ending
= strjoina(unit_name
, suffix
);
7624 r
= get_file_to_edit(paths
, ending
, &new_path
);
7628 r
= create_edit_temp_file(new_path
, new_path
, &tmp_path
);
7632 *ret_new_path
= TAKE_PTR(new_path
);
7633 *ret_tmp_path
= TAKE_PTR(tmp_path
);
7638 static int unit_file_create_copy(
7639 const LookupPaths
*paths
,
7640 const char *unit_name
,
7641 const char *fragment_path
,
7642 char **ret_new_path
,
7643 char **ret_tmp_path
) {
7645 _cleanup_free_
char *new_path
= NULL
, *tmp_path
= NULL
;
7648 assert(fragment_path
);
7650 assert(ret_new_path
);
7651 assert(ret_tmp_path
);
7653 r
= get_file_to_edit(paths
, unit_name
, &new_path
);
7657 if (!path_equal(fragment_path
, new_path
) && access(new_path
, F_OK
) >= 0) {
7660 r
= ask_char(&response
, "yn", "\"%s\" already exists. Overwrite with \"%s\"? [(y)es, (n)o] ", new_path
, fragment_path
);
7663 if (response
!= 'y')
7664 return log_warning_errno(SYNTHETIC_ERRNO(EKEYREJECTED
), "%s skipped.", unit_name
);
7667 r
= create_edit_temp_file(new_path
, fragment_path
, &tmp_path
);
7671 *ret_new_path
= TAKE_PTR(new_path
);
7672 *ret_tmp_path
= TAKE_PTR(tmp_path
);
7677 static int run_editor(char **paths
) {
7682 r
= safe_fork("(editor)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
|FORK_WAIT
, NULL
);
7686 char **editor_args
= NULL
, **tmp_path
, **original_path
;
7687 size_t n_editor_args
= 0, i
= 1, argc
;
7688 const char **args
, *editor
, *p
;
7690 argc
= strv_length(paths
)/2 + 1;
7692 /* SYSTEMD_EDITOR takes precedence over EDITOR which takes precedence over VISUAL
7693 * If neither SYSTEMD_EDITOR nor EDITOR nor VISUAL are present,
7694 * we try to execute well known editors
7696 editor
= getenv("SYSTEMD_EDITOR");
7698 editor
= getenv("EDITOR");
7700 editor
= getenv("VISUAL");
7702 if (!isempty(editor
)) {
7703 editor_args
= strv_split(editor
, WHITESPACE
);
7706 _exit(EXIT_FAILURE
);
7708 n_editor_args
= strv_length(editor_args
);
7709 argc
+= n_editor_args
- 1;
7712 args
= newa(const char*, argc
+ 1);
7714 if (n_editor_args
> 0) {
7715 args
[0] = editor_args
[0];
7716 for (; i
< n_editor_args
; i
++)
7717 args
[i
] = editor_args
[i
];
7720 STRV_FOREACH_PAIR(original_path
, tmp_path
, paths
)
7721 args
[i
++] = *tmp_path
;
7724 if (n_editor_args
> 0)
7725 execvp(args
[0], (char* const*) args
);
7727 FOREACH_STRING(p
, "editor", "nano", "vim", "vi") {
7729 execvp(p
, (char* const*) args
);
7730 /* We do not fail if the editor doesn't exist
7731 * because we want to try each one of them before
7734 if (errno
!= ENOENT
) {
7735 log_error_errno(errno
, "Failed to execute %s: %m", editor
);
7736 _exit(EXIT_FAILURE
);
7740 log_error("Cannot edit unit(s), no editor available. Please set either $SYSTEMD_EDITOR, $EDITOR or $VISUAL.");
7741 _exit(EXIT_FAILURE
);
7747 static int find_paths_to_edit(sd_bus
*bus
, char **names
, char ***paths
) {
7748 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
7755 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
7759 STRV_FOREACH(name
, names
) {
7760 _cleanup_free_
char *path
= NULL
, *new_path
= NULL
, *tmp_path
= NULL
, *tmp_name
= NULL
;
7761 const char *unit_name
;
7763 r
= unit_find_paths(bus
, *name
, &lp
, false, &path
, NULL
);
7764 if (r
== -EKEYREJECTED
) {
7765 /* If loading of the unit failed server side complete, then the server won't tell us the unit
7766 * file path. In that case, find the file client side. */
7767 log_debug_errno(r
, "Unit '%s' was not loaded correctly, retrying client-side.", *name
);
7768 r
= unit_find_paths(bus
, *name
, &lp
, true, &path
, NULL
);
7771 return log_error_errno(r
, "Unit '%s' masked, cannot edit.", *name
);
7779 log_info("Run 'systemctl edit%s --force --full %s' to create a new unit.",
7780 arg_scope
== UNIT_FILE_GLOBAL
? " --global" :
7781 arg_scope
== UNIT_FILE_USER
? " --user" : "",
7786 /* Create a new unit from scratch */
7788 r
= unit_file_create_new(&lp
, unit_name
,
7789 arg_full
? NULL
: ".d/override.conf",
7790 &new_path
, &tmp_path
);
7794 unit_name
= basename(path
);
7795 /* We follow unit aliases, but we need to propagate the instance */
7796 if (unit_name_is_valid(*name
, UNIT_NAME_INSTANCE
) &&
7797 unit_name_is_valid(unit_name
, UNIT_NAME_TEMPLATE
)) {
7798 _cleanup_free_
char *instance
= NULL
;
7800 r
= unit_name_to_instance(*name
, &instance
);
7804 r
= unit_name_replace_instance(unit_name
, instance
, &tmp_name
);
7808 unit_name
= tmp_name
;
7812 r
= unit_file_create_copy(&lp
, unit_name
, path
, &new_path
, &tmp_path
);
7814 r
= unit_file_create_new(&lp
, unit_name
, ".d/override.conf", &new_path
, &tmp_path
);
7819 r
= strv_push_pair(paths
, new_path
, tmp_path
);
7823 new_path
= tmp_path
= NULL
;
7829 static int edit(int argc
, char *argv
[], void *userdata
) {
7830 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
7831 _cleanup_strv_free_
char **names
= NULL
;
7832 _cleanup_strv_free_
char **paths
= NULL
;
7833 char **original
, **tmp
;
7838 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit units if not on a tty.");
7840 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
7841 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit units remotely.");
7843 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
7845 return log_error_errno(r
, "Failed to determine unit paths: %m");
7847 r
= acquire_bus(BUS_MANAGER
, &bus
);
7851 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
7853 return log_error_errno(r
, "Failed to expand names: %m");
7855 STRV_FOREACH(tmp
, names
) {
7856 r
= unit_is_masked(bus
, &lp
, *tmp
);
7860 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit %s: unit is masked.", *tmp
);
7863 r
= find_paths_to_edit(bus
, names
, &paths
);
7867 if (strv_isempty(paths
))
7870 r
= run_editor(paths
);
7874 STRV_FOREACH_PAIR(original
, tmp
, paths
) {
7875 /* If the temporary file is empty we ignore it.
7876 * This allows the user to cancel the modification.
7878 if (null_or_empty_path(*tmp
)) {
7879 log_warning("Editing \"%s\" canceled: temporary file is empty.", *original
);
7883 r
= rename(*tmp
, *original
);
7885 r
= log_error_errno(errno
, "Failed to rename \"%s\" to \"%s\": %m", *tmp
, *original
);
7892 if (!arg_no_reload
&& !install_client_side())
7893 r
= daemon_reload(argc
, argv
, userdata
);
7896 STRV_FOREACH_PAIR(original
, tmp
, paths
) {
7897 (void) unlink(*tmp
);
7899 /* Removing empty dropin dirs */
7901 _cleanup_free_
char *dir
;
7903 dir
= dirname_malloc(*original
);
7907 /* no need to check if the dir is empty, rmdir
7908 * does nothing if it is not the case.
7917 static int systemctl_help(void) {
7918 _cleanup_free_
char *link
= NULL
;
7921 (void) pager_open(arg_pager_flags
);
7923 r
= terminal_urlify_man("systemctl", "1", &link
);
7927 printf("%1$s [OPTIONS...] COMMAND ...\n\n"
7928 "%5$sQuery or send control commands to the system manager.%6$s\n"
7929 "\n%3$sUnit Commands:%4$s\n"
7930 " list-units [PATTERN...] List units currently in memory\n"
7931 " list-sockets [PATTERN...] List socket units currently in memory,\n"
7932 " ordered by address\n"
7933 " list-timers [PATTERN...] List timer units currently in memory,\n"
7934 " ordered by next elapse\n"
7935 " start UNIT... Start (activate) one or more units\n"
7936 " stop UNIT... Stop (deactivate) one or more units\n"
7937 " reload UNIT... Reload one or more units\n"
7938 " restart UNIT... Start or restart one or more units\n"
7939 " try-restart UNIT... Restart one or more units if active\n"
7940 " reload-or-restart UNIT... Reload one or more units if possible,\n"
7941 " otherwise start or restart\n"
7942 " try-reload-or-restart UNIT... If active, reload one or more units,\n"
7943 " if supported, otherwise restart\n"
7944 " isolate UNIT Start one unit and stop all others\n"
7945 " kill UNIT... Send signal to processes of a unit\n"
7946 " clean UNIT... Clean runtime, cache, state, logs or\n"
7947 " configuration of unit\n"
7948 " freeze PATTERN... Freeze execution of unit processes\n"
7949 " thaw PATTERN... Resume execution of a frozen unit\n"
7950 " is-active PATTERN... Check whether units are active\n"
7951 " is-failed PATTERN... Check whether units are failed\n"
7952 " status [PATTERN...|PID...] Show runtime status of one or more units\n"
7953 " show [PATTERN...|JOB...] Show properties of one or more\n"
7954 " units/jobs or the manager\n"
7955 " cat PATTERN... Show files and drop-ins of specified units\n"
7956 " set-property UNIT PROPERTY=VALUE... Sets one or more properties of a unit\n"
7957 " help PATTERN...|PID... Show manual for one or more units\n"
7958 " reset-failed [PATTERN...] Reset failed state for all, one, or more\n"
7960 " list-dependencies [UNIT...] Recursively show units which are required\n"
7961 " or wanted by the units or by which those\n"
7962 " units are required or wanted"
7963 "\n%3$sUnit File Commands:%4$s\n"
7964 " list-unit-files [PATTERN...] List installed unit files\n"
7965 " enable [UNIT...|PATH...] Enable one or more unit files\n"
7966 " disable UNIT... Disable one or more unit files\n"
7967 " reenable UNIT... Reenable one or more unit files\n"
7968 " preset UNIT... Enable/disable one or more unit files\n"
7969 " based on preset configuration\n"
7970 " preset-all Enable/disable all unit files based on\n"
7971 " preset configuration\n"
7972 " is-enabled UNIT... Check whether unit files are enabled\n"
7973 " mask UNIT... Mask one or more units\n"
7974 " unmask UNIT... Unmask one or more units\n"
7975 " link PATH... Link one or more units files into\n"
7976 " the search path\n"
7977 " revert UNIT... Revert one or more unit files to vendor\n"
7979 " add-wants TARGET UNIT... Add 'Wants' dependency for the target\n"
7980 " on specified one or more units\n"
7981 " add-requires TARGET UNIT... Add 'Requires' dependency for the target\n"
7982 " on specified one or more units\n"
7983 " edit UNIT... Edit one or more unit files\n"
7984 " get-default Get the name of the default target\n"
7985 " set-default TARGET Set the default target\n"
7986 "\n%3$sMachine Commands:%4$s\n"
7987 " list-machines [PATTERN...] List local containers and host\n"
7988 "\n%3$sJob Commands:%4$s\n"
7989 " list-jobs [PATTERN...] List jobs\n"
7990 " cancel [JOB...] Cancel all, one, or more jobs\n"
7991 "\n%3$sEnvironment Commands:%4$s\n"
7992 " show-environment Dump environment\n"
7993 " set-environment VARIABLE=VALUE... Set one or more environment variables\n"
7994 " unset-environment VARIABLE... Unset one or more environment variables\n"
7995 " import-environment [VARIABLE...] Import all or some environment variables\n"
7996 "\n%3$sManager State Commands:%4$s\n"
7997 " daemon-reload Reload systemd manager configuration\n"
7998 " daemon-reexec Reexecute systemd manager\n"
7999 " log-level [LEVEL] Get/set logging threshold for manager\n"
8000 " log-target [TARGET] Get/set logging target for manager\n"
8001 " service-watchdogs [BOOL] Get/set service watchdog state\n"
8002 "\n%3$sSystem Commands:%4$s\n"
8003 " is-system-running Check whether system is fully running\n"
8004 " default Enter system default mode\n"
8005 " rescue Enter system rescue mode\n"
8006 " emergency Enter system emergency mode\n"
8007 " halt Shut down and halt the system\n"
8008 " poweroff Shut down and power-off the system\n"
8009 " reboot [ARG] Shut down and reboot the system\n"
8010 " kexec Shut down and reboot the system with kexec\n"
8011 " exit [EXIT_CODE] Request user instance or container exit\n"
8012 " switch-root ROOT [INIT] Change to a different root file system\n"
8013 " suspend Suspend the system\n"
8014 " hibernate Hibernate the system\n"
8015 " hybrid-sleep Hibernate and suspend the system\n"
8016 " suspend-then-hibernate Suspend the system, wake after a period of\n"
8017 " time, and hibernate"
8018 "\n%3$sOptions:%4$s\n"
8019 " -h --help Show this help\n"
8020 " --version Show package version\n"
8021 " --system Connect to system manager\n"
8022 " --user Connect to user service manager\n"
8023 " -H --host=[USER@]HOST Operate on remote host\n"
8024 " -M --machine=CONTAINER Operate on a local container\n"
8025 " -t --type=TYPE List units of a particular type\n"
8026 " --state=STATE List units with particular LOAD or SUB or ACTIVE state\n"
8027 " --failed Shorcut for --state=failed\n"
8028 " -p --property=NAME Show only properties by this name\n"
8029 " -P NAME Equivalent to --value --property=NAME\n"
8030 " -a --all Show all properties/all units currently in memory,\n"
8031 " including dead/empty ones. To list all units installed\n"
8032 " on the system, use 'list-unit-files' instead.\n"
8033 " -l --full Don't ellipsize unit names on output\n"
8034 " -r --recursive Show unit list of host and local containers\n"
8035 " --reverse Show reverse dependencies with 'list-dependencies'\n"
8036 " --with-dependencies Show unit dependencies with 'status', 'cat',\n"
8037 " 'list-units', and 'list-unit-files'.\n"
8038 " --job-mode=MODE Specify how to deal with already queued jobs, when\n"
8039 " queueing a new job\n"
8040 " -T --show-transaction When enqueuing a unit job, show full transaction\n"
8041 " --show-types When showing sockets, explicitly show their type\n"
8042 " --value When showing properties, only print the value\n"
8043 " -i --ignore-inhibitors When shutting down or sleeping, ignore inhibitors\n"
8044 " --kill-who=WHO Whom to send signal to\n"
8045 " -s --signal=SIGNAL Which signal to send\n"
8046 " --what=RESOURCES Which types of resources to remove\n"
8047 " --now Start or stop unit after enabling or disabling it\n"
8048 " --dry-run Only print what would be done\n"
8049 " Currently supported by verbs: halt, poweroff, reboot,\n"
8050 " kexec, suspend, hibernate, suspend-then-hibernate,\n"
8051 " hybrid-sleep, default, rescue, emergency, and exit.\n"
8052 " -q --quiet Suppress output\n"
8053 " --wait For (re)start, wait until service stopped again\n"
8054 " For is-system-running, wait until startup is completed\n"
8055 " --no-block Do not wait until operation finished\n"
8056 " --no-wall Don't send wall message before halt/power-off/reboot\n"
8057 " --no-reload Don't reload daemon after en-/dis-abling unit files\n"
8058 " --no-legend Do not print a legend (column headers and hints)\n"
8059 " --no-pager Do not pipe output into a pager\n"
8060 " --no-ask-password Do not ask for system passwords\n"
8061 " --global Enable/disable/mask unit files globally\n"
8062 " --runtime Enable/disable/mask unit files temporarily until next\n"
8064 " -f --force When enabling unit files, override existing symlinks\n"
8065 " When shutting down, execute action immediately\n"
8066 " --preset-mode= Apply only enable, only disable, or all presets\n"
8067 " --root=PATH Enable/disable/mask unit files in the specified root\n"
8069 " -n --lines=INTEGER Number of journal entries to show\n"
8070 " -o --output=STRING Change journal output mode (short, short-precise,\n"
8071 " short-iso, short-iso-precise, short-full,\n"
8072 " short-monotonic, short-unix,\n"
8073 " verbose, export, json, json-pretty, json-sse, cat)\n"
8074 " --firmware-setup Tell the firmware to show the setup menu on next boot\n"
8075 " --boot-loader-menu=TIME\n"
8076 " Boot into boot loader menu on next boot\n"
8077 " --boot-loader-entry=NAME\n"
8078 " Boot into a specific boot loader entry on next boot\n"
8079 " --plain Print unit dependencies as a list instead of a tree\n"
8080 "\nSee the %2$s for details.\n"
8081 , program_invocation_short_name
8083 , ansi_underline(), ansi_normal()
8084 , ansi_highlight(), ansi_normal()
8090 static int halt_help(void) {
8091 _cleanup_free_
char *link
= NULL
;
8094 r
= terminal_urlify_man("halt", "8", &link
);
8098 printf("%s [OPTIONS...]%s\n"
8099 "\n%s%s the system.%s\n"
8101 " --help Show this help\n"
8102 " --halt Halt the machine\n"
8103 " -p --poweroff Switch off the machine\n"
8104 " --reboot Reboot the machine\n"
8105 " -f --force Force immediate halt/power-off/reboot\n"
8106 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
8107 " -d --no-wtmp Don't write wtmp record\n"
8108 " --no-wall Don't send wall message before halt/power-off/reboot\n"
8109 "\nSee the %s for details.\n"
8110 , program_invocation_short_name
8111 , arg_action
== ACTION_REBOOT
? " [ARG]" : ""
8113 , arg_action
== ACTION_REBOOT
? "Reboot" :
8114 arg_action
== ACTION_POWEROFF
? "Power off" :
8123 static int shutdown_help(void) {
8124 _cleanup_free_
char *link
= NULL
;
8127 r
= terminal_urlify_man("shutdown", "8", &link
);
8131 printf("%s [OPTIONS...] [TIME] [WALL...]\n"
8132 "\n%sShut down the system.%s\n"
8134 " --help Show this help\n"
8135 " -H --halt Halt the machine\n"
8136 " -P --poweroff Power-off the machine\n"
8137 " -r --reboot Reboot the machine\n"
8138 " -h Equivalent to --poweroff, overridden by --halt\n"
8139 " -k Don't halt/power-off/reboot, just send warnings\n"
8140 " --no-wall Don't send wall message before halt/power-off/reboot\n"
8141 " -c Cancel a pending shutdown\n"
8142 "\nSee the %s for details.\n"
8143 , program_invocation_short_name
8144 , ansi_highlight(), ansi_normal()
8151 static int telinit_help(void) {
8152 _cleanup_free_
char *link
= NULL
;
8155 r
= terminal_urlify_man("telinit", "8", &link
);
8159 printf("%s [OPTIONS...] COMMAND\n\n"
8160 "%sSend control commands to the init daemon.%s\n"
8162 " 0 Power-off the machine\n"
8163 " 6 Reboot the machine\n"
8164 " 2, 3, 4, 5 Start runlevelX.target unit\n"
8165 " 1, s, S Enter rescue mode\n"
8166 " q, Q Reload init daemon configuration\n"
8167 " u, U Reexecute init daemon\n"
8169 " --help Show this help\n"
8170 " --no-wall Don't send wall message before halt/power-off/reboot\n"
8171 "\nSee the %s for details.\n"
8172 , program_invocation_short_name
8173 , ansi_highlight(), ansi_normal()
8180 static int runlevel_help(void) {
8181 _cleanup_free_
char *link
= NULL
;
8184 r
= terminal_urlify_man("runlevel", "8", &link
);
8188 printf("%s [OPTIONS...]\n"
8189 "\n%sPrints the previous and current runlevel of the init system.%s\n"
8191 " --help Show this help\n"
8192 "\nSee the %s for details.\n"
8193 , program_invocation_short_name
8194 , ansi_highlight(), ansi_normal()
8201 static void help_types(void) {
8203 puts("Available unit types:");
8205 DUMP_STRING_TABLE(unit_type
, UnitType
, _UNIT_TYPE_MAX
);
8208 static void help_states(void) {
8210 puts("Available unit load states:");
8211 DUMP_STRING_TABLE(unit_load_state
, UnitLoadState
, _UNIT_LOAD_STATE_MAX
);
8214 puts("\nAvailable unit active states:");
8215 DUMP_STRING_TABLE(unit_active_state
, UnitActiveState
, _UNIT_ACTIVE_STATE_MAX
);
8218 puts("\nAvailable unit file states:");
8219 DUMP_STRING_TABLE(unit_file_state
, UnitFileState
, _UNIT_FILE_STATE_MAX
);
8222 puts("\nAvailable automount unit substates:");
8223 DUMP_STRING_TABLE(automount_state
, AutomountState
, _AUTOMOUNT_STATE_MAX
);
8226 puts("\nAvailable device unit substates:");
8227 DUMP_STRING_TABLE(device_state
, DeviceState
, _DEVICE_STATE_MAX
);
8230 puts("\nAvailable mount unit substates:");
8231 DUMP_STRING_TABLE(mount_state
, MountState
, _MOUNT_STATE_MAX
);
8234 puts("\nAvailable path unit substates:");
8235 DUMP_STRING_TABLE(path_state
, PathState
, _PATH_STATE_MAX
);
8238 puts("\nAvailable scope unit substates:");
8239 DUMP_STRING_TABLE(scope_state
, ScopeState
, _SCOPE_STATE_MAX
);
8242 puts("\nAvailable service unit substates:");
8243 DUMP_STRING_TABLE(service_state
, ServiceState
, _SERVICE_STATE_MAX
);
8246 puts("\nAvailable slice unit substates:");
8247 DUMP_STRING_TABLE(slice_state
, SliceState
, _SLICE_STATE_MAX
);
8250 puts("\nAvailable socket unit substates:");
8251 DUMP_STRING_TABLE(socket_state
, SocketState
, _SOCKET_STATE_MAX
);
8254 puts("\nAvailable swap unit substates:");
8255 DUMP_STRING_TABLE(swap_state
, SwapState
, _SWAP_STATE_MAX
);
8258 puts("\nAvailable target unit substates:");
8259 DUMP_STRING_TABLE(target_state
, TargetState
, _TARGET_STATE_MAX
);
8262 puts("\nAvailable timer unit substates:");
8263 DUMP_STRING_TABLE(timer_state
, TimerState
, _TIMER_STATE_MAX
);
8266 static int help_boot_loader_entry(void) {
8267 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
8268 _cleanup_strv_free_
char **l
= NULL
;
8273 r
= acquire_bus(BUS_FULL
, &bus
);
8277 r
= sd_bus_get_property_strv(
8279 "org.freedesktop.login1",
8280 "/org/freedesktop/login1",
8281 "org.freedesktop.login1.Manager",
8282 "BootLoaderEntries",
8286 return log_error_errno(r
, "Failed to enumerate boot loader entries: %s", bus_error_message(&error
, r
));
8288 if (strv_isempty(l
))
8289 return log_error_errno(SYNTHETIC_ERRNO(ENODATA
), "No boot loader entries discovered.");
8297 static int systemctl_parse_argv(int argc
, char *argv
[]) {
8306 ARG_IGNORE_DEPENDENCIES
,
8319 ARG_NO_ASK_PASSWORD
,
8327 ARG_BOOT_LOADER_MENU
,
8328 ARG_BOOT_LOADER_ENTRY
,
8331 ARG_WITH_DEPENDENCIES
,
8336 static const struct option options
[] = {
8337 { "help", no_argument
, NULL
, 'h' },
8338 { "version", no_argument
, NULL
, ARG_VERSION
},
8339 { "type", required_argument
, NULL
, 't' },
8340 { "property", required_argument
, NULL
, 'p' },
8341 { "all", no_argument
, NULL
, 'a' },
8342 { "reverse", no_argument
, NULL
, ARG_REVERSE
},
8343 { "after", no_argument
, NULL
, ARG_AFTER
},
8344 { "before", no_argument
, NULL
, ARG_BEFORE
},
8345 { "show-types", no_argument
, NULL
, ARG_SHOW_TYPES
},
8346 { "failed", no_argument
, NULL
, ARG_FAILED
}, /* compatibility only */
8347 { "full", no_argument
, NULL
, 'l' },
8348 { "job-mode", required_argument
, NULL
, ARG_JOB_MODE
},
8349 { "fail", no_argument
, NULL
, ARG_FAIL
}, /* compatibility only */
8350 { "irreversible", no_argument
, NULL
, ARG_IRREVERSIBLE
}, /* compatibility only */
8351 { "ignore-dependencies", no_argument
, NULL
, ARG_IGNORE_DEPENDENCIES
}, /* compatibility only */
8352 { "ignore-inhibitors", no_argument
, NULL
, 'i' },
8353 { "value", no_argument
, NULL
, ARG_VALUE
},
8354 { "user", no_argument
, NULL
, ARG_USER
},
8355 { "system", no_argument
, NULL
, ARG_SYSTEM
},
8356 { "global", no_argument
, NULL
, ARG_GLOBAL
},
8357 { "wait", no_argument
, NULL
, ARG_WAIT
},
8358 { "no-block", no_argument
, NULL
, ARG_NO_BLOCK
},
8359 { "no-legend", no_argument
, NULL
, ARG_NO_LEGEND
},
8360 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
8361 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8362 { "dry-run", no_argument
, NULL
, ARG_DRY_RUN
},
8363 { "quiet", no_argument
, NULL
, 'q' },
8364 { "root", required_argument
, NULL
, ARG_ROOT
},
8365 { "force", no_argument
, NULL
, 'f' },
8366 { "no-reload", no_argument
, NULL
, ARG_NO_RELOAD
},
8367 { "kill-who", required_argument
, NULL
, ARG_KILL_WHO
},
8368 { "signal", required_argument
, NULL
, 's' },
8369 { "no-ask-password", no_argument
, NULL
, ARG_NO_ASK_PASSWORD
},
8370 { "host", required_argument
, NULL
, 'H' },
8371 { "machine", required_argument
, NULL
, 'M' },
8372 { "runtime", no_argument
, NULL
, ARG_RUNTIME
},
8373 { "lines", required_argument
, NULL
, 'n' },
8374 { "output", required_argument
, NULL
, 'o' },
8375 { "plain", no_argument
, NULL
, ARG_PLAIN
},
8376 { "state", required_argument
, NULL
, ARG_STATE
},
8377 { "recursive", no_argument
, NULL
, 'r' },
8378 { "with-dependencies", no_argument
, NULL
, ARG_WITH_DEPENDENCIES
},
8379 { "preset-mode", required_argument
, NULL
, ARG_PRESET_MODE
},
8380 { "firmware-setup", no_argument
, NULL
, ARG_FIRMWARE_SETUP
},
8381 { "boot-loader-menu", required_argument
, NULL
, ARG_BOOT_LOADER_MENU
},
8382 { "boot-loader-entry", required_argument
, NULL
, ARG_BOOT_LOADER_ENTRY
},
8383 { "now", no_argument
, NULL
, ARG_NOW
},
8384 { "message", required_argument
, NULL
, ARG_MESSAGE
},
8385 { "show-transaction", no_argument
, NULL
, 'T' },
8386 { "what", required_argument
, NULL
, ARG_WHAT
},
8395 /* we default to allowing interactive authorization only in systemctl (not in the legacy commands) */
8396 arg_ask_password
= true;
8398 while ((c
= getopt_long(argc
, argv
, "ht:p:P:alqfs:H:M:n:o:iTr.::", options
, NULL
)) >= 0)
8403 return systemctl_help();
8411 if (isempty(optarg
))
8412 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8413 "--type= requires arguments.");
8415 for (p
= optarg
;;) {
8416 _cleanup_free_
char *type
= NULL
;
8418 r
= extract_first_word(&p
, &type
, ",", 0);
8420 return log_error_errno(r
, "Failed to parse type: %s", optarg
);
8424 if (streq(type
, "help")) {
8429 if (unit_type_from_string(type
) >= 0) {
8430 if (strv_consume(&arg_types
, TAKE_PTR(type
)) < 0)
8435 /* It's much nicer to use --state= for
8436 * load states, but let's support this
8437 * in --types= too for compatibility
8438 * with old versions */
8439 if (unit_load_state_from_string(type
) >= 0) {
8440 if (strv_consume(&arg_states
, TAKE_PTR(type
)) < 0)
8445 log_error("Unknown unit type or load state '%s'.", type
);
8446 return log_info_errno(SYNTHETIC_ERRNO(EINVAL
),
8447 "Use -t help to see a list of allowed values.");
8458 /* Make sure that if the empty property list was specified, we won't show any
8460 if (isempty(optarg
) && !arg_properties
) {
8461 arg_properties
= new0(char*, 1);
8462 if (!arg_properties
)
8467 for (p
= optarg
;;) {
8468 _cleanup_free_
char *prop
= NULL
;
8470 r
= extract_first_word(&p
, &prop
, ",", 0);
8472 return log_error_errno(r
, "Failed to parse property: %s", optarg
);
8476 if (strv_consume(&arg_properties
, TAKE_PTR(prop
)) < 0)
8481 /* If the user asked for a particular property, show it, even if it is empty. */
8491 arg_dependency
= DEPENDENCY_REVERSE
;
8495 arg_dependency
= DEPENDENCY_AFTER
;
8496 arg_jobs_after
= true;
8500 arg_dependency
= DEPENDENCY_BEFORE
;
8501 arg_jobs_before
= true;
8504 case ARG_SHOW_TYPES
:
8505 arg_show_types
= true;
8513 arg_job_mode
= optarg
;
8517 arg_job_mode
= "fail";
8520 case ARG_IRREVERSIBLE
:
8521 arg_job_mode
= "replace-irreversibly";
8524 case ARG_IGNORE_DEPENDENCIES
:
8525 arg_job_mode
= "ignore-dependencies";
8529 arg_scope
= UNIT_FILE_USER
;
8533 arg_scope
= UNIT_FILE_SYSTEM
;
8537 arg_scope
= UNIT_FILE_GLOBAL
;
8545 arg_no_block
= true;
8549 arg_no_legend
= true;
8553 arg_pager_flags
|= PAGER_DISABLE
;
8561 r
= parse_path_argument_and_warn(optarg
, false, &arg_root
);
8571 if (strv_extend(&arg_states
, "failed") < 0)
8589 arg_no_reload
= true;
8593 arg_kill_who
= optarg
;
8597 if (streq(optarg
, "help")) {
8598 DUMP_STRING_TABLE(signal
, int, _NSIG
);
8602 arg_signal
= signal_from_string(optarg
);
8604 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8605 "Failed to parse signal string %s.",
8609 case ARG_NO_ASK_PASSWORD
:
8610 arg_ask_password
= false;
8614 arg_transport
= BUS_TRANSPORT_REMOTE
;
8619 arg_transport
= BUS_TRANSPORT_MACHINE
;
8628 if (safe_atou(optarg
, &arg_lines
) < 0)
8629 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8630 "Failed to parse lines '%s'",
8635 if (streq(optarg
, "help")) {
8636 DUMP_STRING_TABLE(output_mode
, OutputMode
, _OUTPUT_MODE_MAX
);
8640 arg_output
= output_mode_from_string(optarg
);
8642 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8643 "Unknown output '%s'.",
8646 if (OUTPUT_MODE_IS_JSON(arg_output
)) {
8647 arg_no_legend
= true;
8653 arg_ignore_inhibitors
= true;
8660 case ARG_FIRMWARE_SETUP
:
8661 arg_firmware_setup
= true;
8664 case ARG_BOOT_LOADER_MENU
:
8666 r
= parse_sec(optarg
, &arg_boot_loader_menu
);
8668 return log_error_errno(r
, "Failed to parse --boot-loader-menu= argument '%s': %m", optarg
);
8672 case ARG_BOOT_LOADER_ENTRY
:
8674 if (streq(optarg
, "help")) { /* Yes, this means, "help" is not a valid boot loader entry name we can deal with */
8675 r
= help_boot_loader_entry();
8682 arg_boot_loader_entry
= empty_to_null(optarg
);
8688 if (isempty(optarg
))
8689 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8690 "--state= requires arguments.");
8692 for (p
= optarg
;;) {
8693 _cleanup_free_
char *s
= NULL
;
8695 r
= extract_first_word(&p
, &s
, ",", 0);
8697 return log_error_errno(r
, "Failed to parse state: %s", optarg
);
8701 if (streq(s
, "help")) {
8706 if (strv_consume(&arg_states
, TAKE_PTR(s
)) < 0)
8714 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
8715 "--recursive requires root privileges.");
8717 arg_recursive
= true;
8720 case ARG_PRESET_MODE
:
8721 if (streq(optarg
, "help")) {
8722 DUMP_STRING_TABLE(unit_file_preset_mode
, UnitFilePresetMode
, _UNIT_FILE_PRESET_MAX
);
8726 arg_preset_mode
= unit_file_preset_mode_from_string(optarg
);
8727 if (arg_preset_mode
< 0)
8728 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8729 "Failed to parse preset mode: %s.", optarg
);
8738 if (strv_extend(&arg_wall
, optarg
) < 0)
8743 arg_show_transaction
= true;
8746 case ARG_WITH_DEPENDENCIES
:
8747 arg_with_dependencies
= true;
8753 if (isempty(optarg
))
8754 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "--what= requires arguments.");
8756 for (p
= optarg
;;) {
8757 _cleanup_free_
char *k
= NULL
;
8759 r
= extract_first_word(&p
, &k
, ",", 0);
8761 return log_error_errno(r
, "Failed to parse directory type: %s", optarg
);
8765 if (streq(k
, "help")) {
8774 r
= strv_consume(&arg_clean_what
, TAKE_PTR(k
));
8783 /* Output an error mimicking getopt, and print a hint afterwards */
8784 log_error("%s: invalid option -- '.'", program_invocation_name
);
8785 log_notice("Hint: to specify units starting with a dash, use \"--\":\n"
8786 " %s [OPTIONS...] COMMAND -- -.%s ...",
8787 program_invocation_name
, optarg
?: "mount");
8794 assert_not_reached("Unhandled option");
8797 if (arg_transport
!= BUS_TRANSPORT_LOCAL
&& arg_scope
!= UNIT_FILE_SYSTEM
)
8798 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8799 "Cannot access user instance remotely.");
8801 if (arg_wait
&& arg_no_block
)
8802 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8803 "--wait may not be combined with --no-block.");
8808 static int halt_parse_argv(int argc
, char *argv
[]) {
8816 static const struct option options
[] = {
8817 { "help", no_argument
, NULL
, ARG_HELP
},
8818 { "halt", no_argument
, NULL
, ARG_HALT
},
8819 { "poweroff", no_argument
, NULL
, 'p' },
8820 { "reboot", no_argument
, NULL
, ARG_REBOOT
},
8821 { "force", no_argument
, NULL
, 'f' },
8822 { "wtmp-only", no_argument
, NULL
, 'w' },
8823 { "no-wtmp", no_argument
, NULL
, 'd' },
8824 { "no-sync", no_argument
, NULL
, 'n' },
8825 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8834 if (utmp_get_runlevel(&runlevel
, NULL
) >= 0)
8835 if (IN_SET(runlevel
, '0', '6'))
8838 while ((c
= getopt_long(argc
, argv
, "pfwdnih", options
, NULL
)) >= 0)
8845 arg_action
= ACTION_HALT
;
8849 if (arg_action
!= ACTION_REBOOT
)
8850 arg_action
= ACTION_POWEROFF
;
8854 arg_action
= ACTION_REBOOT
;
8879 /* Compatibility nops */
8886 assert_not_reached("Unhandled option");
8889 if (arg_action
== ACTION_REBOOT
&& (argc
== optind
|| argc
== optind
+ 1)) {
8890 r
= update_reboot_parameter_and_warn(argc
== optind
+ 1 ? argv
[optind
] : NULL
, false);
8893 } else if (optind
< argc
)
8894 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8895 "Too many arguments.");
8900 static int shutdown_parse_argv(int argc
, char *argv
[]) {
8906 static const struct option options
[] = {
8907 { "help", no_argument
, NULL
, ARG_HELP
},
8908 { "halt", no_argument
, NULL
, 'H' },
8909 { "poweroff", no_argument
, NULL
, 'P' },
8910 { "reboot", no_argument
, NULL
, 'r' },
8911 { "kexec", no_argument
, NULL
, 'K' }, /* not documented extension */
8912 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8922 while ((c
= getopt_long(argc
, argv
, "HPrhkKat:fFc", options
, NULL
)) >= 0)
8926 return shutdown_help();
8929 arg_action
= ACTION_HALT
;
8933 arg_action
= ACTION_POWEROFF
;
8938 arg_action
= ACTION_KEXEC
;
8940 arg_action
= ACTION_REBOOT
;
8944 arg_action
= ACTION_KEXEC
;
8948 if (arg_action
!= ACTION_HALT
)
8949 arg_action
= ACTION_POWEROFF
;
8961 case 't': /* Note that we also ignore any passed argument to -t, not just the -t itself */
8964 /* Compatibility nops */
8968 arg_action
= ACTION_CANCEL_SHUTDOWN
;
8975 assert_not_reached("Unhandled option");
8978 if (argc
> optind
&& arg_action
!= ACTION_CANCEL_SHUTDOWN
) {
8979 r
= parse_shutdown_time_spec(argv
[optind
], &arg_when
);
8981 log_error("Failed to parse time specification: %s", argv
[optind
]);
8985 arg_when
= now(CLOCK_REALTIME
) + USEC_PER_MINUTE
;
8987 if (argc
> optind
&& arg_action
== ACTION_CANCEL_SHUTDOWN
)
8988 /* No time argument for shutdown cancel */
8989 wall
= argv
+ optind
;
8990 else if (argc
> optind
+ 1)
8991 /* We skip the time argument */
8992 wall
= argv
+ optind
+ 1;
8995 arg_wall
= strv_copy(wall
);
9005 static int telinit_parse_argv(int argc
, char *argv
[]) {
9011 static const struct option options
[] = {
9012 { "help", no_argument
, NULL
, ARG_HELP
},
9013 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
9017 static const struct {
9021 { '0', ACTION_POWEROFF
},
9022 { '6', ACTION_REBOOT
},
9023 { '1', ACTION_RESCUE
},
9024 { '2', ACTION_RUNLEVEL2
},
9025 { '3', ACTION_RUNLEVEL3
},
9026 { '4', ACTION_RUNLEVEL4
},
9027 { '5', ACTION_RUNLEVEL5
},
9028 { 's', ACTION_RESCUE
},
9029 { 'S', ACTION_RESCUE
},
9030 { 'q', ACTION_RELOAD
},
9031 { 'Q', ACTION_RELOAD
},
9032 { 'u', ACTION_REEXEC
},
9033 { 'U', ACTION_REEXEC
}
9042 while ((c
= getopt_long(argc
, argv
, "", options
, NULL
)) >= 0)
9046 return telinit_help();
9056 assert_not_reached("Unhandled option");
9060 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
9061 "%s: required argument missing.",
9062 program_invocation_short_name
);
9064 if (optind
+ 1 < argc
)
9065 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
9066 "Too many arguments.");
9068 if (strlen(argv
[optind
]) != 1)
9069 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
9070 "Expected single character argument.");
9072 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
9073 if (table
[i
].from
== argv
[optind
][0])
9076 if (i
>= ELEMENTSOF(table
))
9077 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
9078 "Unknown command '%s'.", argv
[optind
]);
9080 arg_action
= table
[i
].to
;
9087 static int runlevel_parse_argv(int argc
, char *argv
[]) {
9092 static const struct option options
[] = {
9093 { "help", no_argument
, NULL
, ARG_HELP
},
9102 while ((c
= getopt_long(argc
, argv
, "", options
, NULL
)) >= 0)
9106 return runlevel_help();
9112 assert_not_reached("Unhandled option");
9116 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
9117 "Too many arguments.");
9122 static int parse_argv(int argc
, char *argv
[]) {
9126 if (program_invocation_short_name
) {
9128 if (strstr(program_invocation_short_name
, "halt")) {
9129 arg_action
= ACTION_HALT
;
9130 return halt_parse_argv(argc
, argv
);
9132 } else if (strstr(program_invocation_short_name
, "poweroff")) {
9133 arg_action
= ACTION_POWEROFF
;
9134 return halt_parse_argv(argc
, argv
);
9136 } else if (strstr(program_invocation_short_name
, "reboot")) {
9138 arg_action
= ACTION_KEXEC
;
9140 arg_action
= ACTION_REBOOT
;
9141 return halt_parse_argv(argc
, argv
);
9143 } else if (strstr(program_invocation_short_name
, "shutdown")) {
9144 arg_action
= ACTION_POWEROFF
;
9145 return shutdown_parse_argv(argc
, argv
);
9147 } else if (strstr(program_invocation_short_name
, "init")) {
9149 /* Matches invocations as "init" as well as "telinit", which are synonymous when run as PID !=
9152 * On SysV "telinit" was the official command to communicate with PID 1, but "init" would
9153 * redirect itself to "telinit" if called with PID != 1. We follow the same logic here still,
9154 * though we add one level of indirection, as we implement "telinit" in "systemctl". Hence, for
9155 * us if you invoke "init" you get "systemd", but it will execve() "systemctl" immediately with
9156 * argv[] unmodified if PID is != 1. If you invoke "telinit" you directly get "systemctl". In
9157 * both cases we shall do the same thing, which is why we do strstr(p_i_s_n, "init") here, as a
9158 * quick way to match both.
9160 * Also see redirect_telinit() in src/core/main.c. */
9162 if (sd_booted() > 0) {
9163 arg_action
= _ACTION_INVALID
;
9164 return telinit_parse_argv(argc
, argv
);
9166 /* Hmm, so some other init system is running, we need to forward this request to
9167 * it. For now we simply guess that it is Upstart. */
9169 (void) rlimit_nofile_safe();
9170 execv(TELINIT
, argv
);
9172 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
9173 "Couldn't find an alternative telinit implementation to spawn.");
9176 } else if (strstr(program_invocation_short_name
, "runlevel")) {
9177 arg_action
= ACTION_RUNLEVEL
;
9178 return runlevel_parse_argv(argc
, argv
);
9182 arg_action
= ACTION_SYSTEMCTL
;
9183 return systemctl_parse_argv(argc
, argv
);
9186 #if HAVE_SYSV_COMPAT
9187 _pure_
static int action_to_runlevel(void) {
9188 static const char table
[_ACTION_MAX
] = {
9189 [ACTION_HALT
] = '0',
9190 [ACTION_POWEROFF
] = '0',
9191 [ACTION_REBOOT
] = '6',
9192 [ACTION_RUNLEVEL2
] = '2',
9193 [ACTION_RUNLEVEL3
] = '3',
9194 [ACTION_RUNLEVEL4
] = '4',
9195 [ACTION_RUNLEVEL5
] = '5',
9196 [ACTION_RESCUE
] = '1'
9199 assert(arg_action
>= 0 && arg_action
< _ACTION_MAX
);
9200 return table
[arg_action
];
9204 static int systemctl_main(int argc
, char *argv
[]) {
9205 static const Verb verbs
[] = {
9206 { "list-units", VERB_ANY
, VERB_ANY
, VERB_DEFAULT
|VERB_ONLINE_ONLY
, list_units
},
9207 { "list-unit-files", VERB_ANY
, VERB_ANY
, 0, list_unit_files
},
9208 { "list-sockets", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_sockets
},
9209 { "list-timers", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_timers
},
9210 { "list-jobs", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_jobs
},
9211 { "list-machines", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_machines
},
9212 { "clear-jobs", VERB_ANY
, 1, VERB_ONLINE_ONLY
, trivial_method
},
9213 { "cancel", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, cancel_job
},
9214 { "start", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9215 { "stop", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9216 { "condstop", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with ALTLinux */
9217 { "reload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9218 { "restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9219 { "try-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9220 { "reload-or-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9221 { "reload-or-try-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with old systemctl <= 228 */
9222 { "try-reload-or-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9223 { "force-reload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with SysV */
9224 { "condreload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with ALTLinux */
9225 { "condrestart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with RH */
9226 { "isolate", 2, 2, VERB_ONLINE_ONLY
, start_unit
},
9227 { "kill", 2, VERB_ANY
, VERB_ONLINE_ONLY
, kill_unit
},
9228 { "clean", 2, VERB_ANY
, VERB_ONLINE_ONLY
, clean_or_freeze_unit
},
9229 { "freeze", 2, VERB_ANY
, VERB_ONLINE_ONLY
, clean_or_freeze_unit
},
9230 { "thaw", 2, VERB_ANY
, VERB_ONLINE_ONLY
, clean_or_freeze_unit
},
9231 { "is-active", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_active
},
9232 { "check", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_active
}, /* deprecated alias of is-active */
9233 { "is-failed", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_failed
},
9234 { "show", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
9235 { "cat", 2, VERB_ANY
, VERB_ONLINE_ONLY
, cat
},
9236 { "status", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
9237 { "help", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
9238 { "daemon-reload", VERB_ANY
, 1, VERB_ONLINE_ONLY
, daemon_reload
},
9239 { "daemon-reexec", VERB_ANY
, 1, VERB_ONLINE_ONLY
, daemon_reload
},
9240 { "log-level", VERB_ANY
, 2, VERB_ONLINE_ONLY
, log_level
},
9241 { "log-target", VERB_ANY
, 2, VERB_ONLINE_ONLY
, log_target
},
9242 { "service-watchdogs", VERB_ANY
, 2, VERB_ONLINE_ONLY
, service_watchdogs
},
9243 { "show-environment", VERB_ANY
, 1, VERB_ONLINE_ONLY
, show_environment
},
9244 { "set-environment", 2, VERB_ANY
, VERB_ONLINE_ONLY
, set_environment
},
9245 { "unset-environment", 2, VERB_ANY
, VERB_ONLINE_ONLY
, set_environment
},
9246 { "import-environment", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, import_environment
},
9247 { "halt", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9248 { "poweroff", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9249 { "reboot", VERB_ANY
, 2, VERB_ONLINE_ONLY
, start_system_special
},
9250 { "kexec", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9251 { "suspend", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9252 { "hibernate", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9253 { "hybrid-sleep", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9254 { "suspend-then-hibernate",VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9255 { "default", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_special
},
9256 { "rescue", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9257 { "emergency", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9258 { "exit", VERB_ANY
, 2, VERB_ONLINE_ONLY
, start_special
},
9259 { "reset-failed", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, reset_failed
},
9260 { "enable", 2, VERB_ANY
, 0, enable_unit
},
9261 { "disable", 2, VERB_ANY
, 0, enable_unit
},
9262 { "is-enabled", 2, VERB_ANY
, 0, unit_is_enabled
},
9263 { "reenable", 2, VERB_ANY
, 0, enable_unit
},
9264 { "preset", 2, VERB_ANY
, 0, enable_unit
},
9265 { "preset-all", VERB_ANY
, 1, 0, preset_all
},
9266 { "mask", 2, VERB_ANY
, 0, enable_unit
},
9267 { "unmask", 2, VERB_ANY
, 0, enable_unit
},
9268 { "link", 2, VERB_ANY
, 0, enable_unit
},
9269 { "revert", 2, VERB_ANY
, 0, enable_unit
},
9270 { "switch-root", 2, VERB_ANY
, VERB_ONLINE_ONLY
, switch_root
},
9271 { "list-dependencies", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_dependencies
},
9272 { "set-default", 2, 2, 0, set_default
},
9273 { "get-default", VERB_ANY
, 1, 0, get_default
},
9274 { "set-property", 3, VERB_ANY
, VERB_ONLINE_ONLY
, set_property
},
9275 { "is-system-running", VERB_ANY
, 1, 0, is_system_running
},
9276 { "add-wants", 3, VERB_ANY
, 0, add_dependency
},
9277 { "add-requires", 3, VERB_ANY
, 0, add_dependency
},
9278 { "edit", 2, VERB_ANY
, VERB_ONLINE_ONLY
, edit
},
9282 const Verb
*verb
= verbs_find_verb(argv
[optind
], verbs
);
9283 if (verb
&& (verb
->flags
& VERB_ONLINE_ONLY
) && arg_root
)
9284 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
9285 "Verb '%s' cannot be used with --root=.",
9286 argv
[optind
] ?: verb
->verb
);
9288 return dispatch_verb(argc
, argv
, verbs
, NULL
);
9291 static int reload_with_fallback(void) {
9292 /* First, try systemd via D-Bus. */
9293 if (daemon_reload(0, NULL
, NULL
) >= 0)
9296 /* Nothing else worked, so let's try signals */
9297 assert(IN_SET(arg_action
, ACTION_RELOAD
, ACTION_REEXEC
));
9299 if (kill(1, arg_action
== ACTION_RELOAD
? SIGHUP
: SIGTERM
) < 0)
9300 return log_error_errno(errno
, "kill() failed: %m");
9305 static int start_with_fallback(void) {
9306 /* First, try systemd via D-Bus. */
9307 if (start_unit(0, NULL
, NULL
) == 0)
9310 #if HAVE_SYSV_COMPAT
9311 /* Nothing else worked, so let's try /dev/initctl */
9312 if (talk_initctl(action_to_runlevel()) > 0)
9316 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
9317 "Failed to talk to init daemon.");
9320 static int halt_now(enum action a
) {
9321 /* The kernel will automatically flush ATA disks and suchlike on reboot(), but the file systems need to be
9322 * synced explicitly in advance. */
9323 if (!arg_no_sync
&& !arg_dry_run
)
9326 /* Make sure C-A-D is handled by the kernel from this point on... */
9328 (void) reboot(RB_ENABLE_CAD
);
9334 log_info("Halting.");
9337 (void) reboot(RB_HALT_SYSTEM
);
9340 case ACTION_POWEROFF
:
9342 log_info("Powering off.");
9345 (void) reboot(RB_POWER_OFF
);
9350 return reboot_with_parameter(REBOOT_FALLBACK
|
9351 (arg_quiet
? 0 : REBOOT_LOG
) |
9352 (arg_dry_run
? REBOOT_DRY_RUN
: 0));
9355 assert_not_reached("Unknown action.");
9359 static int logind_schedule_shutdown(void) {
9362 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
9363 char date
[FORMAT_TIMESTAMP_MAX
];
9368 r
= acquire_bus(BUS_FULL
, &bus
);
9372 switch (arg_action
) {
9376 case ACTION_POWEROFF
:
9377 action
= "poweroff";
9392 action
= strjoina("dry-", action
);
9394 (void) logind_set_wall_message();
9396 r
= sd_bus_call_method(
9398 "org.freedesktop.login1",
9399 "/org/freedesktop/login1",
9400 "org.freedesktop.login1.Manager",
9408 return log_warning_errno(r
, "Failed to call ScheduleShutdown in logind, proceeding with immediate shutdown: %s", bus_error_message(&error
, r
));
9411 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.", format_timestamp(date
, sizeof(date
), arg_when
));
9414 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
9415 "Cannot schedule shutdown without logind support, proceeding with immediate shutdown.");
9419 static int halt_main(void) {
9422 r
= logind_check_inhibitors(arg_action
);
9426 /* Delayed shutdown requested, and was successful */
9427 if (arg_when
> 0 && logind_schedule_shutdown() == 0)
9429 /* no delay, or logind failed or is not at all available */
9431 if (geteuid() != 0) {
9432 if (arg_dry_run
|| arg_force
> 0) {
9433 (void) must_be_root();
9437 /* Try logind if we are a normal user and no special
9438 * mode applies. Maybe polkit allows us to shutdown
9440 if (IN_SET(arg_action
, ACTION_POWEROFF
, ACTION_REBOOT
, ACTION_HALT
)) {
9441 r
= logind_reboot(arg_action
);
9444 if (IN_SET(r
, -EOPNOTSUPP
, -EINPROGRESS
))
9445 /* requested operation is not
9446 * supported on the local system or
9447 * already in progress */
9449 /* on all other errors, try low-level operation */
9453 /* In order to minimize the difference between operation with and
9454 * without logind, we explicitly enable non-blocking mode for this,
9455 * as logind's shutdown operations are always non-blocking. */
9456 arg_no_block
= true;
9458 if (!arg_dry_run
&& !arg_force
)
9459 return start_with_fallback();
9461 assert(geteuid() == 0);
9464 if (sd_booted() > 0)
9465 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
9467 r
= utmp_put_shutdown();
9469 log_warning_errno(r
, "Failed to write utmp record: %m");
9476 r
= halt_now(arg_action
);
9477 return log_error_errno(r
, "Failed to reboot: %m");
9480 static int runlevel_main(void) {
9481 int r
, runlevel
, previous
;
9483 r
= utmp_get_runlevel(&runlevel
, &previous
);
9490 previous
<= 0 ? 'N' : previous
,
9491 runlevel
<= 0 ? 'N' : runlevel
);
9496 static int logind_cancel_shutdown(void) {
9498 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
9502 r
= acquire_bus(BUS_FULL
, &bus
);
9506 (void) logind_set_wall_message();
9508 r
= sd_bus_call_method(
9510 "org.freedesktop.login1",
9511 "/org/freedesktop/login1",
9512 "org.freedesktop.login1.Manager",
9513 "CancelScheduledShutdown",
9517 return log_warning_errno(r
, "Failed to talk to logind, shutdown hasn't been cancelled: %s", bus_error_message(&error
, r
));
9521 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
9522 "Not compiled with logind support, cannot cancel scheduled shutdowns.");
9526 static int run(int argc
, char *argv
[]) {
9529 setlocale(LC_ALL
, "");
9530 log_parse_environment();
9533 /* The journal merging logic potentially needs a lot of fds. */
9534 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE
);
9538 /* Explicitly not on_tty() to avoid setting cached value.
9539 * This becomes relevant for piping output which might be
9541 original_stdout_is_tty
= isatty(STDOUT_FILENO
);
9543 r
= parse_argv(argc
, argv
);
9547 if (arg_action
!= ACTION_SYSTEMCTL
&& running_in_chroot() > 0) {
9549 log_info("Running in chroot, ignoring request.");
9554 /* systemctl_main() will print an error message for the bus
9555 * connection, but only if it needs to */
9557 switch (arg_action
) {
9559 case ACTION_SYSTEMCTL
:
9560 r
= systemctl_main(argc
, argv
);
9563 /* Legacy command aliases set arg_action. They provide some fallbacks,
9564 * e.g. to tell sysvinit to reboot after you have installed systemd
9568 case ACTION_POWEROFF
:
9574 case ACTION_RUNLEVEL2
:
9575 case ACTION_RUNLEVEL3
:
9576 case ACTION_RUNLEVEL4
:
9577 case ACTION_RUNLEVEL5
:
9579 r
= start_with_fallback();
9584 r
= reload_with_fallback();
9587 case ACTION_CANCEL_SHUTDOWN
:
9588 r
= logind_cancel_shutdown();
9591 case ACTION_RUNLEVEL
:
9592 r
= runlevel_main();
9596 case ACTION_SUSPEND
:
9597 case ACTION_HIBERNATE
:
9598 case ACTION_HYBRID_SLEEP
:
9599 case ACTION_SUSPEND_THEN_HIBERNATE
:
9600 case ACTION_EMERGENCY
:
9601 case ACTION_DEFAULT
:
9602 /* systemctl verbs with no equivalent in the legacy commands.
9603 * These cannot appear in arg_action. Fall through. */
9605 case _ACTION_INVALID
:
9607 assert_not_reached("Unknown action");
9613 /* Note that we return r here, not 0, so that we can implement the LSB-like return codes */
9617 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);