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"
62 #include "parse-util.h"
63 #include "path-lookup.h"
64 #include "path-util.h"
65 #include "pretty-print.h"
66 #include "proc-cmdline.h"
67 #include "process-util.h"
68 #include "reboot-util.h"
69 #include "rlimit-util.h"
72 #include "signal-util.h"
73 #include "socket-util.h"
74 #include "sort-util.h"
75 #include "spawn-ask-password-agent.h"
76 #include "spawn-polkit-agent.h"
78 #include "stat-util.h"
79 #include "string-table.h"
81 #include "sysv-compat.h"
82 #include "terminal-util.h"
83 #include "tmpfile-util.h"
85 #include "unit-file.h"
86 #include "unit-name.h"
87 #include "user-util.h"
89 #include "utmp-wtmp.h"
93 static char **arg_types
= NULL
;
94 static char **arg_states
= NULL
;
95 static char **arg_properties
= NULL
;
96 static bool arg_all
= false;
97 static enum dependency
{
103 } arg_dependency
= DEPENDENCY_FORWARD
;
104 static const char *arg_job_mode
= "replace";
105 static UnitFileScope arg_scope
= UNIT_FILE_SYSTEM
;
106 static bool arg_wait
= false;
107 static bool arg_no_block
= false;
108 static bool arg_no_legend
= false;
109 static PagerFlags arg_pager_flags
= 0;
110 static bool arg_no_wtmp
= false;
111 static bool arg_no_sync
= false;
112 static bool arg_no_wall
= false;
113 static bool arg_no_reload
= false;
114 static bool arg_value
= false;
115 static bool arg_show_types
= false;
116 static bool arg_ignore_inhibitors
= false;
117 static bool arg_dry_run
= false;
118 static bool arg_quiet
= false;
119 static bool arg_full
= false;
120 static bool arg_recursive
= false;
121 static bool arg_with_dependencies
= false;
122 static bool arg_show_transaction
= false;
123 static int arg_force
= 0;
124 static bool arg_ask_password
= false;
125 static bool arg_runtime
= false;
126 static UnitFilePresetMode arg_preset_mode
= UNIT_FILE_PRESET_FULL
;
127 static char **arg_wall
= NULL
;
128 static const char *arg_kill_who
= NULL
;
129 static int arg_signal
= SIGTERM
;
130 static char *arg_root
= NULL
;
131 static usec_t arg_when
= 0;
142 ACTION_SUSPEND_THEN_HIBERNATE
,
153 ACTION_CANCEL_SHUTDOWN
,
156 } arg_action
= ACTION_SYSTEMCTL
;
157 static BusTransport arg_transport
= BUS_TRANSPORT_LOCAL
;
158 static const char *arg_host
= NULL
;
159 static unsigned arg_lines
= 10;
160 static OutputMode arg_output
= OUTPUT_SHORT
;
161 static bool arg_plain
= false;
162 static bool arg_firmware_setup
= false;
163 static usec_t arg_boot_loader_menu
= USEC_INFINITY
;
164 static const char *arg_boot_loader_entry
= NULL
;
165 static bool arg_now
= false;
166 static bool arg_jobs_before
= false;
167 static bool arg_jobs_after
= false;
168 static char **arg_clean_what
= NULL
;
170 /* This is a global cache that will be constructed on first use. */
171 static Hashmap
*cached_id_map
= NULL
;
172 static Hashmap
*cached_name_map
= NULL
;
174 STATIC_DESTRUCTOR_REGISTER(arg_wall
, strv_freep
);
175 STATIC_DESTRUCTOR_REGISTER(arg_root
, freep
);
176 STATIC_DESTRUCTOR_REGISTER(arg_types
, strv_freep
);
177 STATIC_DESTRUCTOR_REGISTER(arg_states
, strv_freep
);
178 STATIC_DESTRUCTOR_REGISTER(arg_properties
, strv_freep
);
179 STATIC_DESTRUCTOR_REGISTER(arg_clean_what
, strv_freep
);
180 STATIC_DESTRUCTOR_REGISTER(cached_id_map
, hashmap_freep
);
181 STATIC_DESTRUCTOR_REGISTER(cached_name_map
, hashmap_freep
);
183 static int daemon_reload(int argc
, char *argv
[], void* userdata
);
184 static int trivial_method(int argc
, char *argv
[], void *userdata
);
185 static int halt_now(enum action a
);
186 static int get_state_one_unit(sd_bus
*bus
, const char *name
, UnitActiveState
*active_state
);
188 static bool original_stdout_is_tty
;
190 typedef enum BusFocus
{
191 BUS_FULL
, /* The full bus indicated via --system or --user */
192 BUS_MANAGER
, /* The manager itself, possibly directly, possibly via the bus */
196 static sd_bus
*buses
[_BUS_FOCUS_MAX
] = {};
198 static UnitFileFlags
args_to_flags(void) {
199 return (arg_runtime
? UNIT_FILE_RUNTIME
: 0) |
200 (arg_force
? UNIT_FILE_FORCE
: 0);
203 static int acquire_bus(BusFocus focus
, sd_bus
**ret
) {
206 assert(focus
< _BUS_FOCUS_MAX
);
209 /* We only go directly to the manager, if we are using a local transport */
210 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
213 if (getenv_bool("SYSTEMCTL_FORCE_BUS") > 0)
219 user
= arg_scope
!= UNIT_FILE_SYSTEM
;
221 if (focus
== BUS_MANAGER
)
222 r
= bus_connect_transport_systemd(arg_transport
, arg_host
, user
, &buses
[focus
]);
224 r
= bus_connect_transport(arg_transport
, arg_host
, user
, &buses
[focus
]);
226 return log_error_errno(r
, "Failed to connect to bus: %m");
228 (void) sd_bus_set_allow_interactive_authorization(buses
[focus
], arg_ask_password
);
235 static void release_busses(void) {
238 for (w
= 0; w
< _BUS_FOCUS_MAX
; w
++)
239 buses
[w
] = sd_bus_flush_close_unref(buses
[w
]);
242 static void ask_password_agent_open_maybe(void) {
243 /* Open the password agent as a child process if necessary */
248 if (arg_scope
!= UNIT_FILE_SYSTEM
)
251 ask_password_agent_open_if_enabled(arg_transport
, arg_ask_password
);
254 static void polkit_agent_open_maybe(void) {
255 /* Open the polkit agent as a child process if necessary */
257 if (arg_scope
!= UNIT_FILE_SYSTEM
)
260 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
263 static OutputFlags
get_output_flags(void) {
265 arg_all
* OUTPUT_SHOW_ALL
|
266 (arg_full
|| !on_tty() || pager_have()) * OUTPUT_FULL_WIDTH
|
267 colors_enabled() * OUTPUT_COLOR
|
268 !arg_quiet
* OUTPUT_WARN_CUTOFF
;
271 static int translate_bus_error_to_exit_status(int r
, const sd_bus_error
*error
) {
274 if (!sd_bus_error_is_set(error
))
277 if (sd_bus_error_has_name(error
, SD_BUS_ERROR_ACCESS_DENIED
) ||
278 sd_bus_error_has_name(error
, BUS_ERROR_ONLY_BY_DEPENDENCY
) ||
279 sd_bus_error_has_name(error
, BUS_ERROR_NO_ISOLATION
) ||
280 sd_bus_error_has_name(error
, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE
))
281 return EXIT_NOPERMISSION
;
283 if (sd_bus_error_has_name(error
, BUS_ERROR_NO_SUCH_UNIT
))
284 return EXIT_NOTINSTALLED
;
286 if (sd_bus_error_has_name(error
, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE
) ||
287 sd_bus_error_has_name(error
, SD_BUS_ERROR_NOT_SUPPORTED
))
288 return EXIT_NOTIMPLEMENTED
;
290 if (sd_bus_error_has_name(error
, BUS_ERROR_LOAD_FAILED
))
291 return EXIT_NOTCONFIGURED
;
299 static bool install_client_side(void) {
300 /* Decides when to execute enable/disable/... operations
301 * client-side rather than server-side. */
303 if (running_in_chroot_or_offline())
306 if (sd_booted() <= 0)
309 if (!isempty(arg_root
))
312 if (arg_scope
== UNIT_FILE_GLOBAL
)
315 /* Unsupported environment variable, mostly for debugging purposes */
316 if (getenv_bool("SYSTEMCTL_INSTALL_CLIENT_SIDE") > 0)
322 static int compare_unit_info(const UnitInfo
*a
, const UnitInfo
*b
) {
326 /* First, order by machine */
327 if (!a
->machine
&& b
->machine
)
329 if (a
->machine
&& !b
->machine
)
331 if (a
->machine
&& b
->machine
) {
332 r
= strcasecmp(a
->machine
, b
->machine
);
337 /* Second, order by unit type */
338 d1
= strrchr(a
->id
, '.');
339 d2
= strrchr(b
->id
, '.');
341 r
= strcasecmp(d1
, d2
);
346 /* Third, order by name */
347 return strcasecmp(a
->id
, b
->id
);
350 static const char* unit_type_suffix(const char *name
) {
353 dot
= strrchr(name
, '.');
360 static bool output_show_unit(const UnitInfo
*u
, char **patterns
) {
363 if (!strv_fnmatch_or_empty(patterns
, u
->id
, FNM_NOESCAPE
))
366 if (arg_types
&& !strv_find(arg_types
, unit_type_suffix(u
->id
)))
372 /* Note that '--all' is not purely a state filter, but also a
373 * filter that hides units that "follow" other units (which is
374 * used for device units that appear under different names). */
375 if (!isempty(u
->following
))
378 if (!strv_isempty(arg_states
))
381 /* By default show all units except the ones in inactive
382 * state and with no pending job */
386 if (streq(u
->active_state
, "inactive"))
392 static int output_units_list(const UnitInfo
*unit_infos
, unsigned c
) {
393 _cleanup_(table_unrefp
) Table
*table
= NULL
;
398 table
= table_new("", "unit", "load", "active", "sub", "job", "description");
402 table_set_header(table
, !arg_no_legend
);
404 table_set_width(table
, 0);
406 for (u
= unit_infos
; u
< unit_infos
+ c
; u
++) {
407 _cleanup_free_
char *j
= NULL
;
408 const char *on_underline
= "", *on_loaded
= "", *on_active
= "";
409 const char *on_circle
= "", *id
;
410 bool circle
= false, underline
= false;
412 if (u
+ 1 < unit_infos
+ c
&&
413 !streq(unit_type_suffix(u
->id
), unit_type_suffix((u
+ 1)->id
))) {
414 on_underline
= ansi_underline();
418 if (STR_IN_SET(u
->load_state
, "error", "not-found", "bad-setting", "masked") && !arg_plain
) {
419 on_circle
= ansi_highlight_yellow();
421 on_loaded
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
422 } else if (streq(u
->active_state
, "failed") && !arg_plain
) {
423 on_circle
= ansi_highlight_red();
425 on_active
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
427 on_active
= on_underline
;
428 on_loaded
= on_underline
;
432 j
= strjoin(u
->machine
, ":", u
->id
);
440 r
= table_add_many(table
,
441 TABLE_STRING
, circle
? special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
) : " ",
442 TABLE_SET_COLOR
, on_circle
,
444 TABLE_SET_COLOR
, on_active
,
445 TABLE_STRING
, u
->load_state
,
446 TABLE_SET_COLOR
, on_loaded
,
447 TABLE_STRING
, u
->active_state
,
448 TABLE_SET_COLOR
, on_active
,
449 TABLE_STRING
, u
->sub_state
,
450 TABLE_SET_COLOR
, on_active
,
451 TABLE_STRING
, u
->job_id
? u
->job_type
: "",
452 TABLE_SET_COLOR
, u
->job_id
? on_underline
: "",
453 TABLE_STRING
, u
->description
,
454 TABLE_SET_COLOR
, on_underline
);
456 return table_log_add_error(r
);
462 if (job_count
== 0) {
463 /* There's no data in the JOB column, so let's hide it */
464 /* Also, convert all number constants to size_t so va_arg()
465 * in table_set_display() fetches a correct number of bytes from
467 r
= table_set_display(table
, (size_t) 0, (size_t) 1, (size_t) 2, (size_t) 3, (size_t) 4, (size_t) 6, (size_t) -1);
469 return log_error_errno(r
, "Failed to set columns to display: %m");
472 r
= table_print(table
, NULL
);
474 return log_error_errno(r
, "Failed to print the table: %m");
476 if (!arg_no_legend
) {
477 const char *on
, *off
;
478 size_t records
= table_get_rows(table
) - 1;
482 "LOAD = Reflects whether the unit definition was properly loaded.\n"
483 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
484 "SUB = The low-level unit activation state, values depend on unit type.");
485 puts(job_count
? "JOB = Pending job for the unit.\n" : "");
486 on
= ansi_highlight();
489 on
= ansi_highlight_red();
493 if (arg_all
|| strv_contains(arg_states
, "inactive"))
494 printf("%s%zu loaded units listed.%s\n"
495 "To show all installed unit files use 'systemctl list-unit-files'.\n",
497 else if (!arg_states
)
498 printf("%s%zu loaded units listed.%s Pass --all to see loaded but inactive units, too.\n"
499 "To show all installed unit files use 'systemctl list-unit-files'.\n",
502 printf("%zu loaded units listed.\n", records
);
508 static int get_unit_list(
512 UnitInfo
**unit_infos
,
514 sd_bus_message
**_reply
) {
516 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
517 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
518 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
522 bool fallback
= false;
528 r
= sd_bus_message_new_method_call(
531 "org.freedesktop.systemd1",
532 "/org/freedesktop/systemd1",
533 "org.freedesktop.systemd1.Manager",
534 "ListUnitsByPatterns");
536 return bus_log_create_error(r
);
538 r
= sd_bus_message_append_strv(m
, arg_states
);
540 return bus_log_create_error(r
);
542 r
= sd_bus_message_append_strv(m
, patterns
);
544 return bus_log_create_error(r
);
546 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
547 if (r
< 0 && (sd_bus_error_has_name(&error
, SD_BUS_ERROR_UNKNOWN_METHOD
) ||
548 sd_bus_error_has_name(&error
, SD_BUS_ERROR_ACCESS_DENIED
))) {
549 /* Fallback to legacy ListUnitsFiltered method */
551 log_debug_errno(r
, "Failed to list units: %s Falling back to ListUnitsFiltered method.", bus_error_message(&error
, r
));
552 m
= sd_bus_message_unref(m
);
553 sd_bus_error_free(&error
);
555 r
= sd_bus_message_new_method_call(
558 "org.freedesktop.systemd1",
559 "/org/freedesktop/systemd1",
560 "org.freedesktop.systemd1.Manager",
561 "ListUnitsFiltered");
563 return bus_log_create_error(r
);
565 r
= sd_bus_message_append_strv(m
, arg_states
);
567 return bus_log_create_error(r
);
569 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
572 return log_error_errno(r
, "Failed to list units: %s", bus_error_message(&error
, r
));
574 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssssouso)");
576 return bus_log_parse_error(r
);
578 while ((r
= bus_parse_unit_info(reply
, &u
)) > 0) {
581 if (!output_show_unit(&u
, fallback
? patterns
: NULL
))
584 if (!GREEDY_REALLOC(*unit_infos
, size
, c
+1))
587 (*unit_infos
)[c
++] = u
;
590 return bus_log_parse_error(r
);
592 r
= sd_bus_message_exit_container(reply
);
594 return bus_log_parse_error(r
);
596 *_reply
= TAKE_PTR(reply
);
601 static void message_set_freep(Set
**set
) {
602 set_free_with_destructor(*set
, sd_bus_message_unref
);
605 static int get_unit_list_recursive(
608 UnitInfo
**_unit_infos
,
612 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
613 _cleanup_(message_set_freep
) Set
*replies
;
614 sd_bus_message
*reply
;
622 replies
= set_new(NULL
);
626 c
= get_unit_list(bus
, NULL
, patterns
, &unit_infos
, 0, &reply
);
630 r
= set_put(replies
, reply
);
632 sd_bus_message_unref(reply
);
637 _cleanup_strv_free_
char **machines
= NULL
;
640 r
= sd_get_machine_names(&machines
);
642 return log_error_errno(r
, "Failed to get machine names: %m");
644 STRV_FOREACH(i
, machines
) {
645 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*container
= NULL
;
648 r
= sd_bus_open_system_machine(&container
, *i
);
650 log_warning_errno(r
, "Failed to connect to container %s, ignoring: %m", *i
);
654 k
= get_unit_list(container
, *i
, patterns
, &unit_infos
, c
, &reply
);
660 r
= set_put(replies
, reply
);
662 sd_bus_message_unref(reply
);
667 *_machines
= TAKE_PTR(machines
);
671 *_unit_infos
= TAKE_PTR(unit_infos
);
672 *_replies
= TAKE_PTR(replies
);
677 static int expand_names(sd_bus
*bus
, char **names
, const char* suffix
, char ***ret
, bool *ret_expanded
) {
678 _cleanup_strv_free_
char **mangled
= NULL
, **globs
= NULL
;
685 STRV_FOREACH(name
, names
) {
687 UnitNameMangle options
= UNIT_NAME_MANGLE_GLOB
| (arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
);
689 r
= unit_name_mangle_with_suffix(*name
, NULL
, options
, suffix
?: ".service", &t
);
691 return log_error_errno(r
, "Failed to mangle name: %m");
693 if (string_is_glob(t
))
694 r
= strv_consume(&globs
, t
);
696 r
= strv_consume(&mangled
, t
);
701 /* Query the manager only if any of the names are a glob, since
702 * this is fairly expensive */
703 bool expanded
= !strv_isempty(globs
);
705 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
706 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
709 r
= get_unit_list(bus
, NULL
, globs
, &unit_infos
, 0, &reply
);
713 n
= strv_length(mangled
);
716 for (i
= 0; i
< r
; i
++) {
717 if (!GREEDY_REALLOC(mangled
, allocated
, n
+2))
720 mangled
[n
] = strdup(unit_infos
[i
].id
);
729 *ret_expanded
= expanded
;
731 *ret
= TAKE_PTR(mangled
);
735 static int list_dependencies_get_dependencies(sd_bus
*bus
, const char *name
, char ***ret
) {
736 _cleanup_strv_free_
char **deps
= NULL
;
738 static const struct bus_properties_map map
[_DEPENDENCY_MAX
][6] = {
739 [DEPENDENCY_FORWARD
] = {
740 { "Requires", "as", NULL
, 0 },
741 { "Requisite", "as", NULL
, 0 },
742 { "Wants", "as", NULL
, 0 },
743 { "ConsistsOf", "as", NULL
, 0 },
744 { "BindsTo", "as", NULL
, 0 },
747 [DEPENDENCY_REVERSE
] = {
748 { "RequiredBy", "as", NULL
, 0 },
749 { "RequisiteOf", "as", NULL
, 0 },
750 { "WantedBy", "as", NULL
, 0 },
751 { "PartOf", "as", NULL
, 0 },
752 { "BoundBy", "as", NULL
, 0 },
755 [DEPENDENCY_AFTER
] = {
756 { "After", "as", NULL
, 0 },
759 [DEPENDENCY_BEFORE
] = {
760 { "Before", "as", NULL
, 0 },
765 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
766 _cleanup_free_
char *dbus_path
= NULL
;
773 dbus_path
= unit_dbus_path_from_name(name
);
777 r
= bus_map_all_properties(bus
,
778 "org.freedesktop.systemd1",
786 return log_error_errno(r
, "Failed to get properties of %s: %s", name
, bus_error_message(&error
, r
));
788 strv_uniq(deps
); /* Sometimes a unit might have multiple deps on the other unit,
789 * but we still want to show it just once. */
790 *ret
= TAKE_PTR(deps
);
795 static int append_unit_dependencies(sd_bus
*bus
, char **names
, char ***ret
) {
796 _cleanup_strv_free_
char **with_deps
= NULL
;
802 STRV_FOREACH(name
, names
) {
803 _cleanup_strv_free_
char **deps
= NULL
;
805 if (strv_extend(&with_deps
, *name
) < 0)
808 (void) list_dependencies_get_dependencies(bus
, *name
, &deps
);
810 if (strv_extend_strv(&with_deps
, deps
, true) < 0)
814 *ret
= TAKE_PTR(with_deps
);
819 static int maybe_extend_with_unit_dependencies(sd_bus
*bus
, char ***list
) {
823 if (arg_with_dependencies
) {
825 _cleanup_strv_free_
char **list_with_deps
= NULL
;
827 r
= append_unit_dependencies(bus
, *list
, &list_with_deps
);
829 return log_error_errno(r
, "Failed to append unit dependencies: %m");
832 *list
= TAKE_PTR(list_with_deps
);
838 static int list_units(int argc
, char *argv
[], void *userdata
) {
839 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
840 _cleanup_(message_set_freep
) Set
*replies
= NULL
;
841 _cleanup_strv_free_
char **machines
= NULL
;
845 r
= acquire_bus(BUS_MANAGER
, &bus
);
849 (void) pager_open(arg_pager_flags
);
851 if (arg_with_dependencies
) {
852 _cleanup_strv_free_
char **names
= NULL
;
854 r
= append_unit_dependencies(bus
, strv_skip(argv
, 1), &names
);
858 r
= get_unit_list_recursive(bus
, names
, &unit_infos
, &replies
, &machines
);
862 r
= get_unit_list_recursive(bus
, strv_skip(argv
, 1), &unit_infos
, &replies
, &machines
);
867 typesafe_qsort(unit_infos
, r
, compare_unit_info
);
868 return output_units_list(unit_infos
, r
);
871 static int get_triggered_units(
876 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
883 r
= sd_bus_get_property_strv(
885 "org.freedesktop.systemd1",
887 "org.freedesktop.systemd1.Unit",
892 return log_error_errno(r
, "Failed to determine triggers: %s", bus_error_message(&error
, r
));
897 static int get_listening(
899 const char* unit_path
,
902 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
903 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
904 const char *type
, *path
;
907 r
= sd_bus_get_property(
909 "org.freedesktop.systemd1",
911 "org.freedesktop.systemd1.Socket",
917 return log_error_errno(r
, "Failed to get list of listening sockets: %s", bus_error_message(&error
, r
));
919 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ss)");
921 return bus_log_parse_error(r
);
923 while ((r
= sd_bus_message_read(reply
, "(ss)", &type
, &path
)) > 0) {
925 r
= strv_extend(listening
, type
);
929 r
= strv_extend(listening
, path
);
936 return bus_log_parse_error(r
);
938 r
= sd_bus_message_exit_container(reply
);
940 return bus_log_parse_error(r
);
952 /* Note: triggered is a list here, although it almost certainly
953 * will always be one unit. Nevertheless, dbus API allows for multiple
954 * values, so let's follow that. */
957 /* The strv above is shared. free is set only in the first one. */
961 static int socket_info_compare(const struct socket_info
*a
, const struct socket_info
*b
) {
967 if (!a
->machine
&& b
->machine
)
969 if (a
->machine
&& !b
->machine
)
971 if (a
->machine
&& b
->machine
) {
972 r
= strcasecmp(a
->machine
, b
->machine
);
977 r
= strcmp(a
->path
, b
->path
);
979 r
= strcmp(a
->type
, b
->type
);
984 static int output_sockets_list(struct socket_info
*socket_infos
, unsigned cs
) {
985 _cleanup_(table_unrefp
) Table
*table
= NULL
;
986 struct socket_info
*s
;
987 const char *on
, *off
;
990 table
= table_new("listen", "type", "units", "activates");
994 if (!arg_show_types
) {
995 /* Hide the second (TYPE) column */
996 r
= table_set_display(table
, (size_t) 0, (size_t) 2, (size_t) 3, (size_t) -1);
998 return log_error_errno(r
, "Failed to set columns to display: %m");
1001 table_set_header(table
, !arg_no_legend
);
1003 table_set_width(table
, 0);
1006 for (s
= socket_infos
; s
< socket_infos
+ cs
; s
++) {
1007 _cleanup_free_
char *j
= NULL
, *activates
= NULL
;
1011 j
= strjoin(s
->machine
, ":", s
->path
);
1018 activates
= strv_join(s
->triggered
, ", ");
1022 r
= table_add_many(table
,
1024 TABLE_STRING
, s
->type
,
1025 TABLE_STRING
, s
->id
,
1026 TABLE_STRING
, activates
);
1028 return table_log_add_error(r
);
1031 on
= ansi_highlight();
1032 off
= ansi_normal();
1034 on
= ansi_highlight_red();
1035 off
= ansi_normal();
1038 r
= table_print(table
, NULL
);
1040 return log_error_errno(r
, "Failed to print the table: %m");
1042 if (!arg_no_legend
) {
1043 printf("\n%s%u sockets listed.%s\n", on
, cs
, off
);
1045 printf("Pass --all to see loaded but inactive sockets, too.\n");
1051 static int list_sockets(int argc
, char *argv
[], void *userdata
) {
1052 _cleanup_(message_set_freep
) Set
*replies
= NULL
;
1053 _cleanup_strv_free_
char **machines
= NULL
;
1054 _cleanup_strv_free_
char **sockets_with_suffix
= NULL
;
1055 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
1056 _cleanup_free_
struct socket_info
*socket_infos
= NULL
;
1058 struct socket_info
*s
;
1064 r
= acquire_bus(BUS_MANAGER
, &bus
);
1068 (void) pager_open(arg_pager_flags
);
1070 r
= expand_names(bus
, strv_skip(argv
, 1), ".socket", &sockets_with_suffix
, NULL
);
1074 if (argc
== 1 || sockets_with_suffix
) {
1075 n
= get_unit_list_recursive(bus
, sockets_with_suffix
, &unit_infos
, &replies
, &machines
);
1079 for (u
= unit_infos
; u
< unit_infos
+ n
; u
++) {
1080 _cleanup_strv_free_
char **listening
= NULL
, **triggered
= NULL
;
1083 if (!endswith(u
->id
, ".socket"))
1086 r
= get_triggered_units(bus
, u
->unit_path
, &triggered
);
1090 c
= get_listening(bus
, u
->unit_path
, &listening
);
1096 if (!GREEDY_REALLOC(socket_infos
, size
, cs
+ c
)) {
1101 for (i
= 0; i
< c
; i
++)
1102 socket_infos
[cs
+ i
] = (struct socket_info
) {
1103 .machine
= u
->machine
,
1105 .type
= listening
[i
*2],
1106 .path
= listening
[i
*2 + 1],
1107 .triggered
= triggered
,
1108 .own_triggered
= i
==0,
1111 /* from this point on we will cleanup those socket_infos */
1114 listening
= triggered
= NULL
; /* avoid cleanup */
1117 typesafe_qsort(socket_infos
, cs
, socket_info_compare
);
1120 output_sockets_list(socket_infos
, cs
);
1123 assert(cs
== 0 || socket_infos
);
1124 for (s
= socket_infos
; s
< socket_infos
+ cs
; s
++) {
1127 if (s
->own_triggered
)
1128 strv_free(s
->triggered
);
1134 static int get_next_elapse(
1137 dual_timestamp
*next
) {
1139 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1147 r
= sd_bus_get_property_trivial(
1149 "org.freedesktop.systemd1",
1151 "org.freedesktop.systemd1.Timer",
1152 "NextElapseUSecMonotonic",
1157 return log_error_errno(r
, "Failed to get next elapse time: %s", bus_error_message(&error
, r
));
1159 r
= sd_bus_get_property_trivial(
1161 "org.freedesktop.systemd1",
1163 "org.freedesktop.systemd1.Timer",
1164 "NextElapseUSecRealtime",
1169 return log_error_errno(r
, "Failed to get next elapse time: %s", bus_error_message(&error
, r
));
1175 static int get_last_trigger(
1180 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1187 r
= sd_bus_get_property_trivial(
1189 "org.freedesktop.systemd1",
1191 "org.freedesktop.systemd1.Timer",
1197 return log_error_errno(r
, "Failed to get last trigger time: %s", bus_error_message(&error
, r
));
1203 const char* machine
;
1206 usec_t last_trigger
;
1210 static int timer_info_compare(const struct timer_info
*a
, const struct timer_info
*b
) {
1216 if (!a
->machine
&& b
->machine
)
1218 if (a
->machine
&& !b
->machine
)
1220 if (a
->machine
&& b
->machine
) {
1221 r
= strcasecmp(a
->machine
, b
->machine
);
1226 r
= CMP(a
->next_elapse
, b
->next_elapse
);
1230 return strcmp(a
->id
, b
->id
);
1233 static int output_timers_list(struct timer_info
*timer_infos
, unsigned n
) {
1234 _cleanup_(table_unrefp
) Table
*table
= NULL
;
1235 struct timer_info
*t
;
1236 const char *on
, *off
;
1239 assert(timer_infos
|| n
== 0);
1241 table
= table_new("next", "left", "last", "passed", "unit", "activates");
1245 table_set_header(table
, !arg_no_legend
);
1247 table_set_width(table
, 0);
1250 for (t
= timer_infos
; t
< timer_infos
+ n
; t
++) {
1251 _cleanup_free_
char *j
= NULL
, *activates
= NULL
;
1255 j
= strjoin(t
->machine
, ":", t
->id
);
1262 activates
= strv_join(t
->triggered
, ", ");
1266 r
= table_add_many(table
,
1267 TABLE_TIMESTAMP
, t
->next_elapse
,
1268 TABLE_TIMESTAMP_RELATIVE
, t
->next_elapse
,
1269 TABLE_TIMESTAMP
, t
->last_trigger
,
1270 TABLE_TIMESTAMP_RELATIVE
, t
->last_trigger
,
1272 TABLE_STRING
, activates
);
1274 return table_log_add_error(r
);
1277 on
= ansi_highlight();
1278 off
= ansi_normal();
1280 on
= ansi_highlight_red();
1281 off
= ansi_normal();
1284 r
= table_print(table
, NULL
);
1286 return log_error_errno(r
, "Failed to print the table: %m");
1288 if (!arg_no_legend
) {
1289 printf("\n%s%u timers listed.%s\n", on
, n
, off
);
1291 printf("Pass --all to see loaded but inactive timers, too.\n");
1297 static usec_t
calc_next_elapse(dual_timestamp
*nw
, dual_timestamp
*next
) {
1303 if (timestamp_is_set(next
->monotonic
)) {
1306 if (next
->monotonic
> nw
->monotonic
)
1307 converted
= nw
->realtime
+ (next
->monotonic
- nw
->monotonic
);
1309 converted
= nw
->realtime
- (nw
->monotonic
- next
->monotonic
);
1311 if (timestamp_is_set(next
->realtime
))
1312 next_elapse
= MIN(converted
, next
->realtime
);
1314 next_elapse
= converted
;
1317 next_elapse
= next
->realtime
;
1322 static int list_timers(int argc
, char *argv
[], void *userdata
) {
1323 _cleanup_(message_set_freep
) Set
*replies
= NULL
;
1324 _cleanup_strv_free_
char **machines
= NULL
;
1325 _cleanup_strv_free_
char **timers_with_suffix
= NULL
;
1326 _cleanup_free_
struct timer_info
*timer_infos
= NULL
;
1327 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
1328 struct timer_info
*t
;
1336 r
= acquire_bus(BUS_MANAGER
, &bus
);
1340 (void) pager_open(arg_pager_flags
);
1342 r
= expand_names(bus
, strv_skip(argv
, 1), ".timer", &timers_with_suffix
, NULL
);
1346 if (argc
== 1 || timers_with_suffix
) {
1347 n
= get_unit_list_recursive(bus
, timers_with_suffix
, &unit_infos
, &replies
, &machines
);
1351 dual_timestamp_get(&nw
);
1353 for (u
= unit_infos
; u
< unit_infos
+ n
; u
++) {
1354 _cleanup_strv_free_
char **triggered
= NULL
;
1355 dual_timestamp next
= DUAL_TIMESTAMP_NULL
;
1358 if (!endswith(u
->id
, ".timer"))
1361 r
= get_triggered_units(bus
, u
->unit_path
, &triggered
);
1365 r
= get_next_elapse(bus
, u
->unit_path
, &next
);
1369 get_last_trigger(bus
, u
->unit_path
, &last
);
1371 if (!GREEDY_REALLOC(timer_infos
, size
, c
+1)) {
1376 m
= calc_next_elapse(&nw
, &next
);
1378 timer_infos
[c
++] = (struct timer_info
) {
1379 .machine
= u
->machine
,
1382 .last_trigger
= last
,
1383 .triggered
= TAKE_PTR(triggered
),
1387 typesafe_qsort(timer_infos
, c
, timer_info_compare
);
1390 output_timers_list(timer_infos
, c
);
1393 for (t
= timer_infos
; t
< timer_infos
+ c
; t
++)
1394 strv_free(t
->triggered
);
1399 static int compare_unit_file_list(const UnitFileList
*a
, const UnitFileList
*b
) {
1400 const char *d1
, *d2
;
1402 d1
= strrchr(a
->path
, '.');
1403 d2
= strrchr(b
->path
, '.');
1408 r
= strcasecmp(d1
, d2
);
1413 return strcasecmp(basename(a
->path
), basename(b
->path
));
1416 static bool output_show_unit_file(const UnitFileList
*u
, char **states
, char **patterns
) {
1419 if (!strv_fnmatch_or_empty(patterns
, basename(u
->path
), FNM_NOESCAPE
))
1422 if (!strv_isempty(arg_types
)) {
1425 dot
= strrchr(u
->path
, '.');
1429 if (!strv_find(arg_types
, dot
+1))
1433 if (!strv_isempty(states
) &&
1434 !strv_find(states
, unit_file_state_to_string(u
->state
)))
1440 static int output_unit_file_list(const UnitFileList
*units
, unsigned c
) {
1441 _cleanup_(table_unrefp
) Table
*table
= NULL
;
1442 const UnitFileList
*u
;
1445 table
= table_new("unit file", "state", "vendor preset");
1449 table_set_header(table
, !arg_no_legend
);
1451 table_set_width(table
, 0);
1453 for (u
= units
; u
< units
+ c
; u
++) {
1454 const char *on_underline
= NULL
, *on_unit_color
= NULL
, *id
;
1455 const char *on_preset_color
= NULL
, *unit_preset_str
;
1458 underline
= u
+ 1 < units
+ c
&&
1459 !streq(unit_type_suffix(u
->path
), unit_type_suffix((u
+ 1)->path
));
1462 on_underline
= ansi_underline();
1464 if (IN_SET(u
->state
,
1466 UNIT_FILE_MASKED_RUNTIME
,
1469 on_unit_color
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
1470 else if (u
->state
== UNIT_FILE_ENABLED
)
1471 on_unit_color
= underline
? ansi_highlight_green_underline() : ansi_highlight_green();
1473 on_unit_color
= on_underline
;
1475 id
= basename(u
->path
);
1477 r
= unit_file_query_preset(arg_scope
, NULL
, id
);
1479 unit_preset_str
= "n/a";
1480 on_preset_color
= underline
? on_underline
: ansi_normal();
1481 } else if (r
== 0) {
1482 unit_preset_str
= "disabled";
1483 on_preset_color
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
1485 unit_preset_str
= "enabled";
1486 on_preset_color
= underline
? ansi_highlight_green_underline() : ansi_highlight_green();
1489 r
= table_add_many(table
,
1491 TABLE_SET_COLOR
, strempty(on_underline
),
1492 TABLE_STRING
, unit_file_state_to_string(u
->state
),
1493 TABLE_SET_COLOR
, strempty(on_unit_color
),
1494 TABLE_STRING
, unit_preset_str
,
1495 TABLE_SET_COLOR
, strempty(on_preset_color
));
1497 return table_log_add_error(r
);
1500 r
= table_print(table
, NULL
);
1502 return log_error_errno(r
, "Failed to print the table: %m");
1505 printf("\n%u unit files listed.\n", c
);
1510 static int list_unit_files(int argc
, char *argv
[], void *userdata
) {
1511 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1512 _cleanup_free_ UnitFileList
*units
= NULL
;
1519 bool fallback
= false;
1521 if (install_client_side()) {
1527 h
= hashmap_new(&string_hash_ops
);
1531 r
= unit_file_get_list(arg_scope
, arg_root
, h
, arg_states
, strv_skip(argv
, 1));
1533 unit_file_list_free(h
);
1534 return log_error_errno(r
, "Failed to get unit file list: %m");
1537 n_units
= hashmap_size(h
);
1539 units
= new(UnitFileList
, n_units
?: 1); /* avoid malloc(0) */
1541 unit_file_list_free(h
);
1545 HASHMAP_FOREACH(u
, h
, i
) {
1546 if (!output_show_unit_file(u
, NULL
, NULL
))
1553 assert(c
<= n_units
);
1558 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
1559 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1562 r
= acquire_bus(BUS_MANAGER
, &bus
);
1566 r
= sd_bus_message_new_method_call(
1569 "org.freedesktop.systemd1",
1570 "/org/freedesktop/systemd1",
1571 "org.freedesktop.systemd1.Manager",
1572 "ListUnitFilesByPatterns");
1574 return bus_log_create_error(r
);
1576 r
= sd_bus_message_append_strv(m
, arg_states
);
1578 return bus_log_create_error(r
);
1580 if (arg_with_dependencies
) {
1581 _cleanup_strv_free_
char **names_with_deps
= NULL
;
1583 r
= append_unit_dependencies(bus
, strv_skip(argv
, 1), &names_with_deps
);
1585 return log_error_errno(r
, "Failed to append unit dependencies: %m");
1587 r
= sd_bus_message_append_strv(m
, names_with_deps
);
1589 return bus_log_create_error(r
);
1591 r
= sd_bus_message_append_strv(m
, strv_skip(argv
, 1));
1593 return bus_log_create_error(r
);
1596 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1597 if (r
< 0 && sd_bus_error_has_name(&error
, SD_BUS_ERROR_UNKNOWN_METHOD
)) {
1598 /* Fallback to legacy ListUnitFiles method */
1600 log_debug_errno(r
, "Failed to list unit files: %s Falling back to ListUnitsFiles method.", bus_error_message(&error
, r
));
1601 m
= sd_bus_message_unref(m
);
1602 sd_bus_error_free(&error
);
1604 r
= sd_bus_message_new_method_call(
1607 "org.freedesktop.systemd1",
1608 "/org/freedesktop/systemd1",
1609 "org.freedesktop.systemd1.Manager",
1612 return bus_log_create_error(r
);
1614 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1617 return log_error_errno(r
, "Failed to list unit files: %s", bus_error_message(&error
, r
));
1619 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ss)");
1621 return bus_log_parse_error(r
);
1623 while ((r
= sd_bus_message_read(reply
, "(ss)", &path
, &state
)) > 0) {
1625 if (!GREEDY_REALLOC(units
, size
, c
+ 1))
1628 units
[c
] = (struct UnitFileList
) {
1630 unit_file_state_from_string(state
)
1633 if (output_show_unit_file(&units
[c
],
1634 fallback
? arg_states
: NULL
,
1635 fallback
? strv_skip(argv
, 1) : NULL
))
1640 return bus_log_parse_error(r
);
1642 r
= sd_bus_message_exit_container(reply
);
1644 return bus_log_parse_error(r
);
1647 (void) pager_open(arg_pager_flags
);
1649 typesafe_qsort(units
, c
, compare_unit_file_list
);
1650 r
= output_unit_file_list(units
, c
);
1654 if (install_client_side())
1655 for (unit
= units
; unit
< units
+ c
; unit
++)
1661 static int list_dependencies_print(const char *name
, int level
, unsigned branches
, bool last
) {
1662 _cleanup_free_
char *n
= NULL
;
1663 size_t max_len
= MAX(columns(),20u);
1669 for (i
= level
- 1; i
>= 0; i
--) {
1671 if (len
> max_len
- 3 && !arg_full
) {
1672 printf("%s...\n",max_len
% 2 ? "" : " ");
1675 printf("%s", special_glyph(branches
& (1 << i
) ? SPECIAL_GLYPH_TREE_VERTICAL
: SPECIAL_GLYPH_TREE_SPACE
));
1679 if (len
> max_len
- 3 && !arg_full
) {
1680 printf("%s...\n",max_len
% 2 ? "" : " ");
1684 printf("%s", special_glyph(last
? SPECIAL_GLYPH_TREE_RIGHT
: SPECIAL_GLYPH_TREE_BRANCH
));
1688 printf("%s\n", name
);
1692 n
= ellipsize(name
, max_len
-len
, 100);
1700 static int list_dependencies_compare(char * const *a
, char * const *b
) {
1701 if (unit_name_to_type(*a
) == UNIT_TARGET
&& unit_name_to_type(*b
) != UNIT_TARGET
)
1703 if (unit_name_to_type(*a
) != UNIT_TARGET
&& unit_name_to_type(*b
) == UNIT_TARGET
)
1706 return strcasecmp(*a
, *b
);
1709 static int list_dependencies_one(
1714 unsigned branches
) {
1716 _cleanup_strv_free_
char **deps
= NULL
;
1724 r
= strv_extend(units
, name
);
1728 r
= list_dependencies_get_dependencies(bus
, name
, &deps
);
1732 typesafe_qsort(deps
, strv_length(deps
), list_dependencies_compare
);
1734 STRV_FOREACH(c
, deps
) {
1735 if (strv_contains(*units
, *c
)) {
1738 r
= list_dependencies_print("...", level
+ 1, (branches
<< 1) | (c
[1] == NULL
? 0 : 1), 1);
1748 UnitActiveState active_state
= _UNIT_ACTIVE_STATE_INVALID
;
1751 (void) get_state_one_unit(bus
, *c
, &active_state
);
1753 switch (active_state
) {
1755 case UNIT_RELOADING
:
1756 case UNIT_ACTIVATING
:
1757 on
= ansi_highlight_green();
1761 case UNIT_DEACTIVATING
:
1766 on
= ansi_highlight_red();
1770 printf("%s%s%s ", on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), ansi_normal());
1773 r
= list_dependencies_print(*c
, level
, branches
, c
[1] == NULL
);
1777 if (arg_all
|| unit_name_to_type(*c
) == UNIT_TARGET
) {
1778 r
= list_dependencies_one(bus
, *c
, level
+ 1, units
, (branches
<< 1) | (c
[1] == NULL
? 0 : 1));
1785 strv_remove(*units
, name
);
1790 static int list_dependencies(int argc
, char *argv
[], void *userdata
) {
1791 _cleanup_strv_free_
char **units
= NULL
, **done
= NULL
;
1792 char **u
, **patterns
;
1796 r
= acquire_bus(BUS_MANAGER
, &bus
);
1800 patterns
= strv_skip(argv
, 1);
1801 if (strv_isempty(patterns
)) {
1802 units
= strv_new(SPECIAL_DEFAULT_TARGET
);
1806 r
= expand_names(bus
, patterns
, NULL
, &units
, NULL
);
1808 return log_error_errno(r
, "Failed to expand names: %m");
1811 (void) pager_open(arg_pager_flags
);
1813 STRV_FOREACH(u
, units
) {
1818 r
= list_dependencies_one(bus
, *u
, 0, &done
, 0);
1826 struct machine_info
{
1830 char *control_group
;
1831 uint32_t n_failed_units
;
1836 static const struct bus_properties_map machine_info_property_map
[] = {
1837 { "SystemState", "s", NULL
, offsetof(struct machine_info
, state
) },
1838 { "NJobs", "u", NULL
, offsetof(struct machine_info
, n_jobs
) },
1839 { "NFailedUnits", "u", NULL
, offsetof(struct machine_info
, n_failed_units
) },
1840 { "ControlGroup", "s", NULL
, offsetof(struct machine_info
, control_group
) },
1841 { "UserspaceTimestamp", "t", NULL
, offsetof(struct machine_info
, timestamp
) },
1845 static void machine_info_clear(struct machine_info
*info
) {
1850 free(info
->control_group
);
1854 static void free_machines_list(struct machine_info
*machine_infos
, int n
) {
1860 for (i
= 0; i
< n
; i
++)
1861 machine_info_clear(&machine_infos
[i
]);
1863 free(machine_infos
);
1866 static int compare_machine_info(const struct machine_info
*a
, const struct machine_info
*b
) {
1869 r
= CMP(b
->is_host
, a
->is_host
);
1873 return strcasecmp(a
->name
, b
->name
);
1876 static int get_machine_properties(sd_bus
*bus
, struct machine_info
*mi
) {
1877 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*container
= NULL
;
1883 r
= sd_bus_open_system_machine(&container
, mi
->name
);
1890 r
= bus_map_all_properties(
1892 "org.freedesktop.systemd1",
1893 "/org/freedesktop/systemd1",
1894 machine_info_property_map
,
1905 static bool output_show_machine(const char *name
, char **patterns
) {
1906 return strv_fnmatch_or_empty(patterns
, name
, FNM_NOESCAPE
);
1909 static int get_machine_list(
1911 struct machine_info
**_machine_infos
,
1914 struct machine_info
*machine_infos
= NULL
;
1915 _cleanup_strv_free_
char **m
= NULL
;
1916 _cleanup_free_
char *hn
= NULL
;
1921 hn
= gethostname_malloc();
1925 if (output_show_machine(hn
, patterns
)) {
1926 if (!GREEDY_REALLOC0(machine_infos
, sz
, c
+1))
1929 machine_infos
[c
].is_host
= true;
1930 machine_infos
[c
].name
= TAKE_PTR(hn
);
1932 (void) get_machine_properties(bus
, &machine_infos
[c
]);
1936 r
= sd_get_machine_names(&m
);
1938 return log_error_errno(r
, "Failed to get machine list: %m");
1940 STRV_FOREACH(i
, m
) {
1941 _cleanup_free_
char *class = NULL
;
1943 if (!output_show_machine(*i
, patterns
))
1946 sd_machine_get_class(*i
, &class);
1947 if (!streq_ptr(class, "container"))
1950 if (!GREEDY_REALLOC0(machine_infos
, sz
, c
+1)) {
1951 free_machines_list(machine_infos
, c
);
1955 machine_infos
[c
].is_host
= false;
1956 machine_infos
[c
].name
= strdup(*i
);
1957 if (!machine_infos
[c
].name
) {
1958 free_machines_list(machine_infos
, c
);
1962 (void) get_machine_properties(NULL
, &machine_infos
[c
]);
1966 *_machine_infos
= machine_infos
;
1970 static int output_machines_list(struct machine_info
*machine_infos
, unsigned n
) {
1971 _cleanup_(table_unrefp
) Table
*table
= NULL
;
1972 struct machine_info
*m
;
1973 bool state_missing
= false;
1976 assert(machine_infos
|| n
== 0);
1978 table
= table_new("", "name", "state", "failed", "jobs");
1982 table_set_header(table
, !arg_no_legend
);
1984 table_set_width(table
, 0);
1986 for (m
= machine_infos
; m
< machine_infos
+ n
; m
++) {
1987 _cleanup_free_
char *mname
= NULL
;
1988 const char *on_state
= "", *on_failed
= "";
1989 bool circle
= false;
1991 if (streq_ptr(m
->state
, "degraded")) {
1992 on_state
= ansi_highlight_red();
1994 } else if (!streq_ptr(m
->state
, "running")) {
1995 on_state
= ansi_highlight_yellow();
1999 if (m
->n_failed_units
> 0)
2000 on_failed
= ansi_highlight_red();
2005 state_missing
= true;
2008 mname
= strjoin(strna(m
->name
), " (host)");
2010 r
= table_add_many(table
,
2011 TABLE_STRING
, circle
? special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
) : " ",
2012 TABLE_SET_COLOR
, on_state
,
2013 TABLE_STRING
, m
->is_host
? mname
: strna(m
->name
),
2014 TABLE_STRING
, strna(m
->state
),
2015 TABLE_SET_COLOR
, on_state
,
2016 TABLE_UINT32
, m
->n_failed_units
,
2017 TABLE_SET_COLOR
, on_failed
,
2018 TABLE_UINT32
, m
->n_jobs
);
2020 return table_log_add_error(r
);
2023 r
= table_print(table
, NULL
);
2025 return log_error_errno(r
, "Failed to print the table: %m");
2027 if (!arg_no_legend
) {
2029 if (state_missing
&& geteuid() != 0)
2030 printf("Notice: some information only available to privileged users was not shown.\n");
2031 printf("%u machines listed.\n", n
);
2037 static int list_machines(int argc
, char *argv
[], void *userdata
) {
2038 struct machine_info
*machine_infos
= NULL
;
2042 r
= acquire_bus(BUS_MANAGER
, &bus
);
2046 r
= get_machine_list(bus
, &machine_infos
, strv_skip(argv
, 1));
2050 (void) pager_open(arg_pager_flags
);
2052 typesafe_qsort(machine_infos
, r
, compare_machine_info
);
2053 rc
= output_machines_list(machine_infos
, r
);
2054 free_machines_list(machine_infos
, r
);
2059 static int get_default(int argc
, char *argv
[], void *userdata
) {
2060 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2061 _cleanup_free_
char *_path
= NULL
;
2065 if (install_client_side()) {
2066 r
= unit_file_get_default(arg_scope
, arg_root
, &_path
);
2068 return log_error_errno(r
, "Failed to get default target: %m");
2073 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2076 r
= acquire_bus(BUS_MANAGER
, &bus
);
2080 r
= sd_bus_call_method(
2082 "org.freedesktop.systemd1",
2083 "/org/freedesktop/systemd1",
2084 "org.freedesktop.systemd1.Manager",
2090 return log_error_errno(r
, "Failed to get default target: %s", bus_error_message(&error
, r
));
2092 r
= sd_bus_message_read(reply
, "s", &path
);
2094 return bus_log_parse_error(r
);
2098 printf("%s\n", path
);
2103 static int set_default(int argc
, char *argv
[], void *userdata
) {
2104 _cleanup_free_
char *unit
= NULL
;
2105 UnitFileChange
*changes
= NULL
;
2106 size_t n_changes
= 0;
2112 r
= unit_name_mangle_with_suffix(argv
[1], "set-default",
2113 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
2116 return log_error_errno(r
, "Failed to mangle unit name: %m");
2118 if (install_client_side()) {
2119 r
= unit_file_set_default(arg_scope
, UNIT_FILE_FORCE
, arg_root
, unit
, &changes
, &n_changes
);
2120 unit_file_dump_changes(r
, "set default", changes
, n_changes
, arg_quiet
);
2125 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2126 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2129 polkit_agent_open_maybe();
2131 r
= acquire_bus(BUS_MANAGER
, &bus
);
2135 r
= sd_bus_call_method(
2137 "org.freedesktop.systemd1",
2138 "/org/freedesktop/systemd1",
2139 "org.freedesktop.systemd1.Manager",
2145 return log_error_errno(r
, "Failed to set default target: %s", bus_error_message(&error
, r
));
2147 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
2151 /* Try to reload if enabled */
2153 r
= daemon_reload(argc
, argv
, userdata
);
2159 unit_file_changes_free(changes
, n_changes
);
2164 static int output_waiting_jobs(sd_bus
*bus
, Table
*table
, uint32_t id
, const char *method
, const char *prefix
) {
2165 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2166 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2167 const char *name
, *type
;
2173 r
= sd_bus_call_method(
2175 "org.freedesktop.systemd1",
2176 "/org/freedesktop/systemd1",
2177 "org.freedesktop.systemd1.Manager",
2183 return log_debug_errno(r
, "Failed to get waiting jobs for job %" PRIu32
, id
);
2185 r
= sd_bus_message_enter_container(reply
, 'a', "(usssoo)");
2187 return bus_log_parse_error(r
);
2189 while ((r
= sd_bus_message_read(reply
, "(usssoo)", &other_id
, &name
, &type
, NULL
, NULL
, NULL
)) > 0) {
2190 _cleanup_free_
char *row
= NULL
;
2193 if (asprintf(&row
, "%s %u (%s/%s)", prefix
, other_id
, name
, type
) < 0)
2196 rc
= table_add_many(table
,
2197 TABLE_STRING
, special_glyph(SPECIAL_GLYPH_TREE_RIGHT
),
2202 return table_log_add_error(r
);
2206 return bus_log_parse_error(r
);
2208 r
= sd_bus_message_exit_container(reply
);
2210 return bus_log_parse_error(r
);
2217 const char *name
, *type
, *state
;
2220 static int output_jobs_list(sd_bus
*bus
, const struct job_info
* jobs
, unsigned n
, bool skipped
) {
2221 _cleanup_(table_unrefp
) Table
*table
= NULL
;
2222 const struct job_info
*j
;
2223 const char *on
, *off
;
2226 assert(n
== 0 || jobs
);
2229 if (!arg_no_legend
) {
2230 on
= ansi_highlight_green();
2231 off
= ansi_normal();
2233 printf("%sNo jobs %s.%s\n", on
, skipped
? "listed" : "running", off
);
2238 (void) pager_open(arg_pager_flags
);
2240 table
= table_new("job", "unit", "type", "state");
2244 table_set_header(table
, !arg_no_legend
);
2246 table_set_width(table
, 0);
2248 for (j
= jobs
; j
< jobs
+ n
; j
++) {
2249 if (streq(j
->state
, "running"))
2250 on
= ansi_highlight();
2255 r
= table_add_many(table
,
2257 TABLE_STRING
, j
->name
,
2258 TABLE_SET_COLOR
, on
,
2259 TABLE_STRING
, j
->type
,
2260 TABLE_STRING
, j
->state
,
2261 TABLE_SET_COLOR
, on
);
2263 return table_log_add_error(r
);
2266 output_waiting_jobs(bus
, table
, j
->id
, "GetJobAfter", "\twaiting for job");
2267 if (arg_jobs_before
)
2268 output_waiting_jobs(bus
, table
, j
->id
, "GetJobBefore", "\tblocking job");
2271 r
= table_print(table
, NULL
);
2273 return log_error_errno(r
, "Failed to print the table: %m");
2275 if (!arg_no_legend
) {
2276 on
= ansi_highlight();
2277 off
= ansi_normal();
2279 printf("\n%s%u jobs listed%s.\n", on
, n
, off
);
2285 static bool output_show_job(struct job_info
*job
, char **patterns
) {
2286 return strv_fnmatch_or_empty(patterns
, job
->name
, FNM_NOESCAPE
);
2289 static int list_jobs(int argc
, char *argv
[], void *userdata
) {
2290 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2291 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2292 _cleanup_free_
struct job_info
*jobs
= NULL
;
2293 const char *name
, *type
, *state
;
2294 bool skipped
= false;
2301 r
= acquire_bus(BUS_MANAGER
, &bus
);
2305 r
= sd_bus_call_method(
2307 "org.freedesktop.systemd1",
2308 "/org/freedesktop/systemd1",
2309 "org.freedesktop.systemd1.Manager",
2315 return log_error_errno(r
, "Failed to list jobs: %s", bus_error_message(&error
, r
));
2317 r
= sd_bus_message_enter_container(reply
, 'a', "(usssoo)");
2319 return bus_log_parse_error(r
);
2321 while ((r
= sd_bus_message_read(reply
, "(usssoo)", &id
, &name
, &type
, &state
, NULL
, NULL
)) > 0) {
2322 struct job_info job
= { id
, name
, type
, state
};
2324 if (!output_show_job(&job
, strv_skip(argv
, 1))) {
2329 if (!GREEDY_REALLOC(jobs
, size
, c
+ 1))
2335 return bus_log_parse_error(r
);
2337 r
= sd_bus_message_exit_container(reply
);
2339 return bus_log_parse_error(r
);
2341 (void) pager_open(arg_pager_flags
);
2343 return output_jobs_list(bus
, jobs
, c
, skipped
);
2346 static int cancel_job(int argc
, char *argv
[], void *userdata
) {
2352 return trivial_method(argc
, argv
, userdata
);
2354 r
= acquire_bus(BUS_MANAGER
, &bus
);
2358 polkit_agent_open_maybe();
2360 STRV_FOREACH(name
, strv_skip(argv
, 1)) {
2361 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2365 q
= safe_atou32(*name
, &id
);
2367 return log_error_errno(q
, "Failed to parse job id \"%s\": %m", *name
);
2369 q
= sd_bus_call_method(
2371 "org.freedesktop.systemd1",
2372 "/org/freedesktop/systemd1",
2373 "org.freedesktop.systemd1.Manager",
2379 log_error_errno(q
, "Failed to cancel job %"PRIu32
": %s", id
, bus_error_message(&error
, q
));
2388 static int need_daemon_reload(sd_bus
*bus
, const char *unit
) {
2389 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2393 /* We ignore all errors here, since this is used to show a
2396 /* We don't use unit_dbus_path_from_name() directly since we
2397 * don't want to load the unit if it isn't loaded. */
2399 r
= sd_bus_call_method(
2401 "org.freedesktop.systemd1",
2402 "/org/freedesktop/systemd1",
2403 "org.freedesktop.systemd1.Manager",
2411 r
= sd_bus_message_read(reply
, "o", &path
);
2415 r
= sd_bus_get_property_trivial(
2417 "org.freedesktop.systemd1",
2419 "org.freedesktop.systemd1.Unit",
2429 static void warn_unit_file_changed(const char *name
) {
2432 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.",
2433 ansi_highlight_red(),
2436 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user");
2439 static int unit_file_find_path(LookupPaths
*lp
, const char *unit_name
, char **ret_unit_path
) {
2445 STRV_FOREACH(p
, lp
->search_path
) {
2446 _cleanup_free_
char *path
= NULL
, *lpath
= NULL
;
2449 path
= path_join(*p
, unit_name
);
2453 r
= chase_symlinks(path
, arg_root
, 0, &lpath
, NULL
);
2459 return log_error_errno(r
, "Failed to access path \"%s\": %m", path
);
2462 *ret_unit_path
= TAKE_PTR(lpath
);
2468 *ret_unit_path
= NULL
;
2473 static int unit_find_template_path(
2474 const char *unit_name
,
2476 char **ret_fragment_path
,
2477 char **ret_template
) {
2479 _cleanup_free_
char *t
= NULL
, *f
= NULL
;
2482 /* Returns 1 if a fragment was found, 0 if not found, negative on error. */
2484 r
= unit_file_find_path(lp
, unit_name
, &f
);
2488 if (ret_fragment_path
)
2489 *ret_fragment_path
= TAKE_PTR(f
);
2491 *ret_template
= NULL
;
2492 return r
; /* found a real unit */
2495 r
= unit_name_template(unit_name
, &t
);
2497 if (ret_fragment_path
)
2498 *ret_fragment_path
= NULL
;
2500 *ret_template
= NULL
;
2502 return 0; /* not a template, does not exist */
2505 return log_error_errno(r
, "Failed to determine template name: %m");
2507 r
= unit_file_find_path(lp
, t
, ret_fragment_path
);
2512 *ret_template
= r
> 0 ? TAKE_PTR(t
) : NULL
;
2517 static int unit_find_paths(
2519 const char *unit_name
,
2521 bool force_client_side
,
2522 char **ret_fragment_path
,
2523 char ***ret_dropin_paths
) {
2525 _cleanup_strv_free_
char **dropins
= NULL
;
2526 _cleanup_free_
char *path
= NULL
;
2530 * Finds where the unit is defined on disk. Returns 0 if the unit is not found. Returns 1 if it is
2532 * - the path to the unit in *ret_frament_path, if it exists on disk,
2533 * - and a strv of existing drop-ins in *ret_dropin_paths, if the arg is not NULL and any dropins
2536 * Returns -ERFKILL if the unit is masked, and -EKEYREJECTED if the unit file could not be loaded for
2537 * some reason (the latter only applies if we are going through the service manager).
2541 assert(ret_fragment_path
);
2544 /* Go via the bus to acquire the path, unless we are explicitly told not to, or when the unit name is a template */
2545 if (!force_client_side
&&
2546 !install_client_side() &&
2547 !unit_name_is_valid(unit_name
, UNIT_NAME_TEMPLATE
)) {
2548 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2549 _cleanup_free_
char *load_state
= NULL
, *dbus_path
= NULL
;
2551 dbus_path
= unit_dbus_path_from_name(unit_name
);
2555 r
= sd_bus_get_property_string(
2557 "org.freedesktop.systemd1",
2559 "org.freedesktop.systemd1.Unit",
2564 return log_error_errno(r
, "Failed to get LoadState: %s", bus_error_message(&error
, r
));
2566 if (streq(load_state
, "masked"))
2568 if (streq(load_state
, "not-found")) {
2572 if (!STR_IN_SET(load_state
, "loaded", "bad-setting"))
2573 return -EKEYREJECTED
;
2575 r
= sd_bus_get_property_string(
2577 "org.freedesktop.systemd1",
2579 "org.freedesktop.systemd1.Unit",
2584 return log_error_errno(r
, "Failed to get FragmentPath: %s", bus_error_message(&error
, r
));
2586 if (ret_dropin_paths
) {
2587 r
= sd_bus_get_property_strv(
2589 "org.freedesktop.systemd1",
2591 "org.freedesktop.systemd1.Unit",
2596 return log_error_errno(r
, "Failed to get DropInPaths: %s", bus_error_message(&error
, r
));
2600 _cleanup_set_free_free_ Set
*names
= NULL
;
2602 if (!cached_name_map
) {
2603 r
= unit_file_build_name_map(lp
, NULL
, &cached_id_map
, &cached_name_map
, NULL
);
2608 r
= unit_file_find_fragment(cached_id_map
, cached_name_map
, unit_name
, &_path
, &names
);
2613 path
= strdup(_path
);
2618 if (ret_dropin_paths
) {
2619 r
= unit_file_find_dropin_paths(arg_root
, lp
->search_path
, NULL
,
2627 if (isempty(path
)) {
2628 *ret_fragment_path
= NULL
;
2631 *ret_fragment_path
= TAKE_PTR(path
);
2635 if (ret_dropin_paths
) {
2636 if (!strv_isempty(dropins
)) {
2637 *ret_dropin_paths
= TAKE_PTR(dropins
);
2640 *ret_dropin_paths
= NULL
;
2644 if (r
== 0 && !arg_force
)
2645 log_error("No files found for %s.", unit_name
);
2650 static int get_state_one_unit(sd_bus
*bus
, const char *name
, UnitActiveState
*active_state
) {
2651 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2652 _cleanup_free_
char *buf
= NULL
, *dbus_path
= NULL
;
2653 UnitActiveState state
;
2657 assert(active_state
);
2659 dbus_path
= unit_dbus_path_from_name(name
);
2663 r
= sd_bus_get_property_string(
2665 "org.freedesktop.systemd1",
2667 "org.freedesktop.systemd1.Unit",
2672 return log_error_errno(r
, "Failed to retrieve unit state: %s", bus_error_message(&error
, r
));
2674 state
= unit_active_state_from_string(buf
);
2676 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid unit state '%s' for: %s", buf
, name
);
2678 *active_state
= state
;
2682 static int unit_is_masked(sd_bus
*bus
, LookupPaths
*lp
, const char *name
) {
2683 _cleanup_free_
char *load_state
= NULL
;
2686 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
2687 _cleanup_free_
char *path
= NULL
;
2689 /* A template cannot be loaded, but it can be still masked, so
2690 * we need to use a different method. */
2692 r
= unit_file_find_path(lp
, name
, &path
);
2697 return null_or_empty_path(path
);
2700 r
= unit_load_state(bus
, name
, &load_state
);
2704 return streq(load_state
, "masked");
2707 static int check_triggering_units(sd_bus
*bus
, const char *name
) {
2708 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2709 _cleanup_free_
char *n
= NULL
, *dbus_path
= NULL
, *load_state
= NULL
;
2710 _cleanup_strv_free_
char **triggered_by
= NULL
;
2711 bool print_warning_label
= true;
2712 UnitActiveState active_state
;
2716 r
= unit_name_mangle(name
, 0, &n
);
2718 return log_error_errno(r
, "Failed to mangle unit name: %m");
2720 r
= unit_load_state(bus
, name
, &load_state
);
2724 if (streq(load_state
, "masked"))
2727 dbus_path
= unit_dbus_path_from_name(n
);
2731 r
= sd_bus_get_property_strv(
2733 "org.freedesktop.systemd1",
2735 "org.freedesktop.systemd1.Unit",
2740 return log_error_errno(r
, "Failed to get triggered by array of %s: %s", n
, bus_error_message(&error
, r
));
2742 STRV_FOREACH(i
, triggered_by
) {
2743 r
= get_state_one_unit(bus
, *i
, &active_state
);
2747 if (!IN_SET(active_state
, UNIT_ACTIVE
, UNIT_RELOADING
))
2750 if (print_warning_label
) {
2751 log_warning("Warning: Stopping %s, but it can still be activated by:", n
);
2752 print_warning_label
= false;
2755 log_warning(" %s", *i
);
2761 static const struct {
2762 const char *verb
; /* systemctl verb */
2763 const char *method
; /* Name of the specific D-Bus method */
2764 const char *job_type
; /* Job type when passing to the generic EnqueueUnitJob() method */
2765 } unit_actions
[] = {
2766 { "start", "StartUnit", "start" },
2767 { "stop", "StopUnit", "stop" },
2768 { "condstop", "StopUnit", "stop" }, /* legacy alias */
2769 { "reload", "ReloadUnit", "reload" },
2770 { "restart", "RestartUnit", "restart" },
2771 { "try-restart", "TryRestartUnit", "try-restart" },
2772 { "condrestart", "TryRestartUnit", "try-restart" }, /* legacy alias */
2773 { "reload-or-restart", "ReloadOrRestartUnit", "reload-or-restart" },
2774 { "try-reload-or-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" },
2775 { "reload-or-try-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2776 { "condreload", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2777 { "force-reload", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2780 static const char *verb_to_method(const char *verb
) {
2783 for (i
= 0; i
< ELEMENTSOF(unit_actions
); i
++)
2784 if (streq_ptr(unit_actions
[i
].verb
, verb
))
2785 return unit_actions
[i
].method
;
2790 static const char *verb_to_job_type(const char *verb
) {
2793 for (i
= 0; i
< ELEMENTSOF(unit_actions
); i
++)
2794 if (streq_ptr(unit_actions
[i
].verb
, verb
))
2795 return unit_actions
[i
].job_type
;
2800 static int start_unit_one(
2802 const char *method
, /* When using classic per-job bus methods */
2803 const char *job_type
, /* When using new-style EnqueueUnitJob() */
2806 sd_bus_error
*error
,
2808 BusWaitForUnits
*wu
) {
2810 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2820 log_debug("%s dbus call org.freedesktop.systemd1.Manager %s(%s, %s)",
2821 arg_dry_run
? "Would execute" : "Executing",
2822 method
, name
, mode
);
2827 if (arg_show_transaction
) {
2828 _cleanup_(sd_bus_error_free
) sd_bus_error enqueue_error
= SD_BUS_ERROR_NULL
;
2830 /* Use the new, fancy EnqueueUnitJob() API if the user wants us to print the transaction */
2831 r
= sd_bus_call_method(
2833 "org.freedesktop.systemd1",
2834 "/org/freedesktop/systemd1",
2835 "org.freedesktop.systemd1.Manager",
2840 name
, job_type
, mode
);
2842 if (!sd_bus_error_has_name(&enqueue_error
, SD_BUS_ERROR_UNKNOWN_METHOD
)) {
2843 (void) sd_bus_error_move(error
, &enqueue_error
);
2847 /* Hmm, the API is not yet available. Let's use the classic API instead (see below). */
2848 log_notice("--show-transaction not supported by this service manager, proceeding without.");
2853 r
= sd_bus_message_read(reply
, "uosos", &id
, &path
, &u
, NULL
, &jt
);
2855 return bus_log_parse_error(r
);
2857 log_info("Enqueued anchor job %" PRIu32
" %s/%s.", id
, u
, jt
);
2859 r
= sd_bus_message_enter_container(reply
, 'a', "(uosos)");
2861 return bus_log_parse_error(r
);
2863 r
= sd_bus_message_read(reply
, "(uosos)", &id
, NULL
, &u
, NULL
, &jt
);
2865 return bus_log_parse_error(r
);
2869 log_info("Enqueued auxiliary job %" PRIu32
" %s/%s.", id
, u
, jt
);
2872 r
= sd_bus_message_exit_container(reply
);
2874 return bus_log_parse_error(r
);
2881 r
= sd_bus_call_method(
2883 "org.freedesktop.systemd1",
2884 "/org/freedesktop/systemd1",
2885 "org.freedesktop.systemd1.Manager",
2893 r
= sd_bus_message_read(reply
, "o", &path
);
2895 return bus_log_parse_error(r
);
2898 if (need_daemon_reload(bus
, name
) > 0)
2899 warn_unit_file_changed(name
);
2902 log_debug("Adding %s to the set", path
);
2903 r
= bus_wait_for_jobs_add(w
, path
);
2905 return log_error_errno(r
, "Failed to watch job for %s: %m", name
);
2909 r
= bus_wait_for_units_add_unit(wu
, name
, BUS_WAIT_FOR_INACTIVE
|BUS_WAIT_NO_JOB
, NULL
, NULL
);
2911 return log_error_errno(r
, "Failed to watch unit %s: %m", name
);
2917 /* There's always a fallback possible for legacy actions. */
2918 if (arg_action
!= ACTION_SYSTEMCTL
)
2921 log_error_errno(r
, "Failed to %s %s: %s", job_type
, name
, bus_error_message(error
, r
));
2923 if (!sd_bus_error_has_name(error
, BUS_ERROR_NO_SUCH_UNIT
) &&
2924 !sd_bus_error_has_name(error
, BUS_ERROR_UNIT_MASKED
) &&
2925 !sd_bus_error_has_name(error
, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE
))
2926 log_error("See %s logs and 'systemctl%s status%s %s' for details.",
2927 arg_scope
== UNIT_FILE_SYSTEM
? "system" : "user",
2928 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user",
2929 name
[0] == '-' ? " --" : "",
2935 static const struct {
2939 } action_table
[_ACTION_MAX
] = {
2940 [ACTION_HALT
] = { SPECIAL_HALT_TARGET
, "halt", "replace-irreversibly" },
2941 [ACTION_POWEROFF
] = { SPECIAL_POWEROFF_TARGET
, "poweroff", "replace-irreversibly" },
2942 [ACTION_REBOOT
] = { SPECIAL_REBOOT_TARGET
, "reboot", "replace-irreversibly" },
2943 [ACTION_KEXEC
] = { SPECIAL_KEXEC_TARGET
, "kexec", "replace-irreversibly" },
2944 [ACTION_RUNLEVEL2
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
2945 [ACTION_RUNLEVEL3
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
2946 [ACTION_RUNLEVEL4
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
2947 [ACTION_RUNLEVEL5
] = { SPECIAL_GRAPHICAL_TARGET
, NULL
, "isolate" },
2948 [ACTION_RESCUE
] = { SPECIAL_RESCUE_TARGET
, "rescue", "isolate" },
2949 [ACTION_EMERGENCY
] = { SPECIAL_EMERGENCY_TARGET
, "emergency", "isolate" },
2950 [ACTION_DEFAULT
] = { SPECIAL_DEFAULT_TARGET
, "default", "isolate" },
2951 [ACTION_EXIT
] = { SPECIAL_EXIT_TARGET
, "exit", "replace-irreversibly" },
2952 [ACTION_SUSPEND
] = { SPECIAL_SUSPEND_TARGET
, "suspend", "replace-irreversibly" },
2953 [ACTION_HIBERNATE
] = { SPECIAL_HIBERNATE_TARGET
, "hibernate", "replace-irreversibly" },
2954 [ACTION_HYBRID_SLEEP
] = { SPECIAL_HYBRID_SLEEP_TARGET
, "hybrid-sleep", "replace-irreversibly" },
2955 [ACTION_SUSPEND_THEN_HIBERNATE
] = { SPECIAL_SUSPEND_THEN_HIBERNATE_TARGET
, "suspend-then-hibernate", "replace-irreversibly" },
2958 static enum action
verb_to_action(const char *verb
) {
2961 for (i
= 0; i
< _ACTION_MAX
; i
++)
2962 if (streq_ptr(action_table
[i
].verb
, verb
))
2965 return _ACTION_INVALID
;
2968 static const char** make_extra_args(const char *extra_args
[static 4]) {
2973 if (arg_scope
!= UNIT_FILE_SYSTEM
)
2974 extra_args
[n
++] = "--user";
2976 if (arg_transport
== BUS_TRANSPORT_REMOTE
) {
2977 extra_args
[n
++] = "-H";
2978 extra_args
[n
++] = arg_host
;
2979 } else if (arg_transport
== BUS_TRANSPORT_MACHINE
) {
2980 extra_args
[n
++] = "-M";
2981 extra_args
[n
++] = arg_host
;
2983 assert(arg_transport
== BUS_TRANSPORT_LOCAL
);
2985 extra_args
[n
] = NULL
;
2989 static int start_unit(int argc
, char *argv
[], void *userdata
) {
2990 _cleanup_(bus_wait_for_units_freep
) BusWaitForUnits
*wu
= NULL
;
2991 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
2992 const char *method
, *job_type
, *mode
, *one_name
, *suffix
= NULL
;
2993 _cleanup_free_
char **stopped_units
= NULL
; /* Do not use _cleanup_strv_free_ */
2994 _cleanup_strv_free_
char **names
= NULL
;
2995 int r
, ret
= EXIT_SUCCESS
;
2999 if (arg_wait
&& !STR_IN_SET(argv
[0], "start", "restart"))
3000 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3001 "--wait may only be used with the 'start' or 'restart' commands.");
3003 /* we cannot do sender tracking on the private bus, so we need the full
3004 * one for RefUnit to implement --wait */
3005 r
= acquire_bus(arg_wait
? BUS_FULL
: BUS_MANAGER
, &bus
);
3009 ask_password_agent_open_maybe();
3010 polkit_agent_open_maybe();
3012 if (arg_action
== ACTION_SYSTEMCTL
) {
3015 action
= verb_to_action(argv
[0]);
3017 if (action
!= _ACTION_INVALID
) {
3018 /* A command in style "systemctl reboot", "systemctl poweroff", … */
3019 method
= "StartUnit";
3021 mode
= action_table
[action
].mode
;
3022 one_name
= action_table
[action
].target
;
3024 if (streq(argv
[0], "isolate")) {
3025 /* A "systemctl isolate <unit1> <unit2> …" command */
3026 method
= "StartUnit";
3031 /* A command in style of "systemctl start <unit1> <unit2> …", "sysemctl stop <unit1> <unit2> …" and so on */
3032 method
= verb_to_method(argv
[0]);
3033 job_type
= verb_to_job_type(argv
[0]);
3034 mode
= arg_job_mode
;
3039 /* A SysV legacy command such as "halt", "reboot", "poweroff", … */
3040 assert(arg_action
>= 0 && arg_action
< _ACTION_MAX
);
3041 assert(action_table
[arg_action
].target
);
3042 assert(action_table
[arg_action
].mode
);
3044 method
= "StartUnit";
3046 mode
= action_table
[arg_action
].mode
;
3047 one_name
= action_table
[arg_action
].target
;
3051 names
= strv_new(one_name
);
3057 r
= expand_names(bus
, strv_skip(argv
, 1), suffix
, &names
, &expanded
);
3059 return log_error_errno(r
, "Failed to expand names: %m");
3061 if (!arg_all
&& expanded
&& streq(job_type
, "start") && !arg_quiet
) {
3062 log_warning("Warning: %ssystemctl start called with a glob pattern.%s",
3063 ansi_highlight_red(),
3065 log_notice("Hint: unit globs expand to loaded units, so start will usually have no effect.\n"
3066 " Passing --all will also load units which are pulled in by other units.\n"
3067 " See systemctl(1) for more details.");
3071 if (!arg_no_block
) {
3072 r
= bus_wait_for_jobs_new(bus
, &w
);
3074 return log_error_errno(r
, "Could not watch jobs: %m");
3078 r
= sd_bus_call_method_async(
3081 "org.freedesktop.systemd1",
3082 "/org/freedesktop/systemd1",
3083 "org.freedesktop.systemd1.Manager",
3088 return log_error_errno(r
, "Failed to enable subscription: %m");
3090 r
= bus_wait_for_units_new(bus
, &wu
);
3092 return log_error_errno(r
, "Failed to allocate unit watch context: %m");
3095 STRV_FOREACH(name
, names
) {
3096 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3098 r
= start_unit_one(bus
, method
, job_type
, *name
, mode
, &error
, w
, wu
);
3099 if (ret
== EXIT_SUCCESS
&& r
< 0)
3100 ret
= translate_bus_error_to_exit_status(r
, &error
);
3102 if (r
>= 0 && streq(method
, "StopUnit")) {
3103 r
= strv_push(&stopped_units
, *name
);
3109 if (!arg_no_block
) {
3110 const char* extra_args
[4];
3112 r
= bus_wait_for_jobs(w
, arg_quiet
, make_extra_args(extra_args
));
3116 /* When stopping units, warn if they can still be triggered by
3117 * another active unit (socket, path, timer) */
3119 STRV_FOREACH(name
, stopped_units
)
3120 (void) check_triggering_units(bus
, *name
);
3124 r
= bus_wait_for_units_run(wu
);
3126 return log_error_errno(r
, "Failed to wait for units: %m");
3127 if (r
== BUS_WAIT_FAILURE
&& ret
== EXIT_SUCCESS
)
3135 static int logind_set_wall_message(void) {
3136 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3138 _cleanup_free_
char *m
= NULL
;
3141 r
= acquire_bus(BUS_FULL
, &bus
);
3145 m
= strv_join(arg_wall
, " ");
3149 log_debug("%s wall message \"%s\".", arg_dry_run
? "Would set" : "Setting", m
);
3153 r
= sd_bus_call_method(
3155 "org.freedesktop.login1",
3156 "/org/freedesktop/login1",
3157 "org.freedesktop.login1.Manager",
3166 return log_warning_errno(r
, "Failed to set wall message, ignoring: %s", bus_error_message(&error
, r
));
3171 /* Ask systemd-logind, which might grant access to unprivileged users through polkit */
3172 static int logind_reboot(enum action a
) {
3174 static const struct {
3176 const char *description
;
3177 } actions
[_ACTION_MAX
] = {
3178 [ACTION_POWEROFF
] = { "PowerOff", "power off system" },
3179 [ACTION_REBOOT
] = { "Reboot", "reboot system" },
3180 [ACTION_HALT
] = { "Halt", "halt system" },
3181 [ACTION_SUSPEND
] = { "Suspend", "suspend system" },
3182 [ACTION_HIBERNATE
] = { "Hibernate", "hibernate system" },
3183 [ACTION_HYBRID_SLEEP
] = { "HybridSleep", "put system into hybrid sleep" },
3184 [ACTION_SUSPEND_THEN_HIBERNATE
] = { "SuspendThenHibernate", "suspend system, hibernate later" },
3187 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3191 if (a
< 0 || a
>= _ACTION_MAX
|| !actions
[a
].method
)
3194 r
= acquire_bus(BUS_FULL
, &bus
);
3198 polkit_agent_open_maybe();
3199 (void) logind_set_wall_message();
3201 log_debug("%s org.freedesktop.login1.Manager %s dbus call.", arg_dry_run
? "Would execute" : "Executing", actions
[a
].method
);
3206 r
= sd_bus_call_method(
3208 "org.freedesktop.login1",
3209 "/org/freedesktop/login1",
3210 "org.freedesktop.login1.Manager",
3214 "b", arg_ask_password
);
3216 return log_error_errno(r
, "Failed to %s via logind: %s", actions
[a
].description
, bus_error_message(&error
, r
));
3224 static int logind_check_inhibitors(enum action a
) {
3226 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
3227 _cleanup_strv_free_
char **sessions
= NULL
;
3228 const char *what
, *who
, *why
, *mode
;
3235 if (arg_ignore_inhibitors
|| arg_force
> 0)
3247 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
3250 r
= acquire_bus(BUS_FULL
, &bus
);
3254 r
= sd_bus_call_method(
3256 "org.freedesktop.login1",
3257 "/org/freedesktop/login1",
3258 "org.freedesktop.login1.Manager",
3264 /* If logind is not around, then there are no inhibitors... */
3267 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssuu)");
3269 return bus_log_parse_error(r
);
3271 while ((r
= sd_bus_message_read(reply
, "(ssssuu)", &what
, &who
, &why
, &mode
, &uid
, &pid
)) > 0) {
3272 _cleanup_free_
char *comm
= NULL
, *user
= NULL
;
3273 _cleanup_strv_free_
char **sv
= NULL
;
3275 if (!streq(mode
, "block"))
3278 sv
= strv_split(what
, ":");
3282 if (!pid_is_valid((pid_t
) pid
))
3283 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Invalid PID "PID_FMT
".", (pid_t
) pid
);
3285 if (!strv_contains(sv
,
3290 ACTION_KEXEC
) ? "shutdown" : "sleep"))
3293 get_process_comm(pid
, &comm
);
3294 user
= uid_to_name(uid
);
3296 log_warning("Operation inhibited by \"%s\" (PID "PID_FMT
" \"%s\", user %s), reason is \"%s\".",
3297 who
, (pid_t
) pid
, strna(comm
), strna(user
), why
);
3302 return bus_log_parse_error(r
);
3304 r
= sd_bus_message_exit_container(reply
);
3306 return bus_log_parse_error(r
);
3308 /* Check for current sessions */
3309 sd_get_sessions(&sessions
);
3310 STRV_FOREACH(s
, sessions
) {
3311 _cleanup_free_
char *type
= NULL
, *tty
= NULL
, *seat
= NULL
, *user
= NULL
, *service
= NULL
, *class = NULL
;
3313 if (sd_session_get_uid(*s
, &uid
) < 0 || uid
== getuid())
3316 if (sd_session_get_class(*s
, &class) < 0 || !streq(class, "user"))
3319 if (sd_session_get_type(*s
, &type
) < 0 || !STR_IN_SET(type
, "x11", "wayland", "tty", "mir"))
3322 sd_session_get_tty(*s
, &tty
);
3323 sd_session_get_seat(*s
, &seat
);
3324 sd_session_get_service(*s
, &service
);
3325 user
= uid_to_name(uid
);
3327 log_warning("User %s is logged in on %s.", strna(user
), isempty(tty
) ? (isempty(seat
) ? strna(service
) : seat
) : tty
);
3334 log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'systemctl %s -i'.",
3335 action_table
[a
].verb
);
3343 static int prepare_firmware_setup(void) {
3345 if (!arg_firmware_setup
)
3349 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3353 r
= acquire_bus(BUS_FULL
, &bus
);
3357 r
= sd_bus_call_method(
3359 "org.freedesktop.login1",
3360 "/org/freedesktop/login1",
3361 "org.freedesktop.login1.Manager",
3362 "SetRebootToFirmwareSetup",
3367 return log_error_errno(r
, "Cannot indicate to EFI to boot into setup mode: %s", bus_error_message(&error
, r
));
3371 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3372 "Booting into firmware setup not supported.");
3376 static int prepare_boot_loader_menu(void) {
3378 if (arg_boot_loader_menu
== USEC_INFINITY
)
3382 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3386 r
= acquire_bus(BUS_FULL
, &bus
);
3390 r
= sd_bus_call_method(
3392 "org.freedesktop.login1",
3393 "/org/freedesktop/login1",
3394 "org.freedesktop.login1.Manager",
3395 "SetRebootToBootLoaderMenu",
3398 "t", arg_boot_loader_menu
);
3400 return log_error_errno(r
, "Cannot indicate to boot loader to enter boot loader entry menu: %s", bus_error_message(&error
, r
));
3404 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3405 "Booting into boot loader menu not supported.");
3409 static int prepare_boot_loader_entry(void) {
3411 if (!arg_boot_loader_entry
)
3415 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3419 r
= acquire_bus(BUS_FULL
, &bus
);
3423 r
= sd_bus_call_method(
3425 "org.freedesktop.login1",
3426 "/org/freedesktop/login1",
3427 "org.freedesktop.login1.Manager",
3428 "SetRebootToBootLoaderEntry",
3431 "s", arg_boot_loader_entry
);
3433 return log_error_errno(r
, "Cannot set boot into loader entry '%s': %s", arg_boot_loader_entry
, bus_error_message(&error
, r
));
3437 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3438 "Booting into boot loader entry not supported.");
3442 static int load_kexec_kernel(void) {
3443 _cleanup_(boot_config_free
) BootConfig config
= {};
3444 _cleanup_free_
char *kernel
= NULL
, *initrd
= NULL
, *options
= NULL
;
3449 if (kexec_loaded()) {
3450 log_debug("Kexec kernel already loaded.");
3454 if (access(KEXEC
, X_OK
) < 0)
3455 return log_error_errno(errno
, KEXEC
" is not available: %m");
3457 r
= boot_entries_load_config_auto(NULL
, NULL
, &config
);
3459 /* The call doesn't log about ENOKEY, let's do so here. */
3460 return log_error_errno(r
,
3461 "No kexec kernel loaded and autodetection failed.\n%s",
3463 ? "Cannot automatically load kernel: ESP partition mount point not found."
3464 : "Automatic loading works only on systems booted with EFI.");
3468 e
= boot_config_default_entry(&config
);
3470 return log_error_errno(SYNTHETIC_ERRNO(ENOENT
),
3471 "No boot loader entry suitable as default, refusing to guess.");
3473 log_debug("Found default boot loader entry in file \"%s\"", e
->path
);
3476 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3477 "Boot entry does not refer to Linux kernel, which is not supported currently.");
3478 if (strv_length(e
->initrd
) > 1)
3479 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3480 "Boot entry specifies multiple initrds, which is not supported currently.");
3482 kernel
= path_join(e
->root
, e
->kernel
);
3486 if (!strv_isempty(e
->initrd
)) {
3487 initrd
= path_join(e
->root
, e
->initrd
[0]);
3492 options
= strv_join(e
->options
, " ");
3496 log_full(arg_quiet
? LOG_DEBUG
: LOG_INFO
,
3497 "%s "KEXEC
" --load \"%s\" --append \"%s\"%s%s%s",
3498 arg_dry_run
? "Would run" : "Running",
3501 initrd
? " --initrd \"" : NULL
, strempty(initrd
), initrd
? "\"" : "");
3505 r
= safe_fork("(kexec)", FORK_WAIT
|FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
, &pid
);
3509 const char* const args
[] = {
3512 "--append", options
,
3513 initrd
? "--initrd" : NULL
, initrd
,
3518 execv(args
[0], (char * const *) args
);
3519 _exit(EXIT_FAILURE
);
3525 static int set_exit_code(uint8_t code
) {
3526 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3530 r
= acquire_bus(BUS_MANAGER
, &bus
);
3534 r
= sd_bus_call_method(
3536 "org.freedesktop.systemd1",
3537 "/org/freedesktop/systemd1",
3538 "org.freedesktop.systemd1.Manager",
3544 return log_error_errno(r
, "Failed to set exit code: %s", bus_error_message(&error
, r
));
3549 static int start_special(int argc
, char *argv
[], void *userdata
) {
3552 bool termination_action
; /* an action that terminates the manager,
3553 * can be performed also by signal. */
3557 a
= verb_to_action(argv
[0]);
3559 r
= logind_check_inhibitors(a
);
3563 if (arg_force
>= 2) {
3569 r
= prepare_firmware_setup();
3573 r
= prepare_boot_loader_menu();
3577 r
= prepare_boot_loader_entry();
3581 if (a
== ACTION_REBOOT
&& argc
> 1) {
3582 r
= update_reboot_parameter_and_warn(argv
[1], false);
3586 } else if (a
== ACTION_KEXEC
) {
3587 r
= load_kexec_kernel();
3588 if (r
< 0 && arg_force
>= 1)
3589 log_notice("Failed to load kexec kernel, continuing without.");
3593 } else if (a
== ACTION_EXIT
&& argc
> 1) {
3596 /* If the exit code is not given on the command line,
3597 * don't reset it to zero: just keep it as it might
3598 * have been set previously. */
3600 r
= safe_atou8(argv
[1], &code
);
3602 return log_error_errno(r
, "Invalid exit code.");
3604 r
= set_exit_code(code
);
3609 termination_action
= IN_SET(a
,
3613 if (termination_action
&& arg_force
>= 2)
3616 if (arg_force
>= 1 &&
3617 (termination_action
|| IN_SET(a
, ACTION_KEXEC
, ACTION_EXIT
)))
3618 r
= trivial_method(argc
, argv
, userdata
);
3620 /* First try logind, to allow authentication with polkit */
3627 ACTION_HYBRID_SLEEP
,
3628 ACTION_SUSPEND_THEN_HIBERNATE
)) {
3630 r
= logind_reboot(a
);
3633 if (IN_SET(r
, -EOPNOTSUPP
, -EINPROGRESS
))
3634 /* requested operation is not supported or already in progress */
3637 /* On all other errors, try low-level operation. In order to minimize the difference between
3638 * operation with and without logind, we explicitly enable non-blocking mode for this, as
3639 * logind's shutdown operations are always non-blocking. */
3641 arg_no_block
= true;
3643 } else if (IN_SET(a
, ACTION_EXIT
, ACTION_KEXEC
))
3644 /* Since exit/kexec are so close in behaviour to power-off/reboot, let's also make them
3645 * asynchronous, in order to not confuse the user needlessly with unexpected behaviour. */
3646 arg_no_block
= true;
3648 r
= start_unit(argc
, argv
, userdata
);
3651 if (termination_action
&& arg_force
< 2 &&
3652 IN_SET(r
, -ENOENT
, -ETIMEDOUT
))
3653 log_notice("It is possible to perform action directly, see discussion of --force --force in man:systemctl(1).");
3658 static int start_system_special(int argc
, char *argv
[], void *userdata
) {
3659 /* Like start_special above, but raises an error when running in user mode */
3661 if (arg_scope
!= UNIT_FILE_SYSTEM
)
3662 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3663 "Bad action for %s mode.",
3664 arg_scope
== UNIT_FILE_GLOBAL
? "--global" : "--user");
3666 return start_special(argc
, argv
, userdata
);
3669 static int check_unit_generic(int code
, const UnitActiveState good_states
[], int nb_states
, char **args
) {
3670 _cleanup_strv_free_
char **names
= NULL
;
3671 UnitActiveState active_state
;
3677 r
= acquire_bus(BUS_MANAGER
, &bus
);
3681 r
= expand_names(bus
, args
, NULL
, &names
, NULL
);
3683 return log_error_errno(r
, "Failed to expand names: %m");
3685 STRV_FOREACH(name
, names
) {
3686 r
= get_state_one_unit(bus
, *name
, &active_state
);
3691 puts(unit_active_state_to_string(active_state
));
3693 for (i
= 0; i
< nb_states
; ++i
)
3694 if (good_states
[i
] == active_state
)
3698 /* use the given return code for the case that we won't find
3699 * any unit which matches the list */
3700 return found
? 0 : code
;
3703 static int check_unit_active(int argc
, char *argv
[], void *userdata
) {
3704 static const UnitActiveState states
[] = {
3709 /* According to LSB: 3, "program is not running" */
3710 return check_unit_generic(EXIT_PROGRAM_NOT_RUNNING
, states
, ELEMENTSOF(states
), strv_skip(argv
, 1));
3713 static int check_unit_failed(int argc
, char *argv
[], void *userdata
) {
3714 static const UnitActiveState states
[] = {
3718 return check_unit_generic(EXIT_PROGRAM_DEAD_AND_PID_EXISTS
, states
, ELEMENTSOF(states
), strv_skip(argv
, 1));
3721 static int kill_unit(int argc
, char *argv
[], void *userdata
) {
3722 _cleanup_strv_free_
char **names
= NULL
;
3723 char *kill_who
= NULL
, **name
;
3727 r
= acquire_bus(BUS_MANAGER
, &bus
);
3731 polkit_agent_open_maybe();
3734 arg_kill_who
= "all";
3736 /* --fail was specified */
3737 if (streq(arg_job_mode
, "fail"))
3738 kill_who
= strjoina(arg_kill_who
, "-fail");
3740 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
3742 return log_error_errno(r
, "Failed to expand names: %m");
3744 STRV_FOREACH(name
, names
) {
3745 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3747 q
= sd_bus_call_method(
3749 "org.freedesktop.systemd1",
3750 "/org/freedesktop/systemd1",
3751 "org.freedesktop.systemd1.Manager",
3755 "ssi", *name
, kill_who
? kill_who
: arg_kill_who
, arg_signal
);
3757 log_error_errno(q
, "Failed to kill unit %s: %s", *name
, bus_error_message(&error
, q
));
3766 static int clean_unit(int argc
, char *argv
[], void *userdata
) {
3767 _cleanup_(bus_wait_for_units_freep
) BusWaitForUnits
*w
= NULL
;
3768 _cleanup_strv_free_
char **names
= NULL
;
3769 int r
, ret
= EXIT_SUCCESS
;
3773 r
= acquire_bus(BUS_FULL
, &bus
);
3777 polkit_agent_open_maybe();
3779 if (!arg_clean_what
) {
3780 arg_clean_what
= strv_new("cache", "runtime");
3781 if (!arg_clean_what
)
3785 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
3787 return log_error_errno(r
, "Failed to expand names: %m");
3789 if (!arg_no_block
) {
3790 r
= bus_wait_for_units_new(bus
, &w
);
3792 return log_error_errno(r
, "Failed to allocate unit waiter: %m");
3795 STRV_FOREACH(name
, names
) {
3796 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3797 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
3800 /* If we shall wait for the cleaning to complete, let's add a ref on the unit first */
3801 r
= sd_bus_call_method(
3803 "org.freedesktop.systemd1",
3804 "/org/freedesktop/systemd1",
3805 "org.freedesktop.systemd1.Manager",
3811 log_error_errno(r
, "Failed to add reference to unit %s: %s", *name
, bus_error_message(&error
, r
));
3812 if (ret
== EXIT_SUCCESS
)
3818 r
= sd_bus_message_new_method_call(
3821 "org.freedesktop.systemd1",
3822 "/org/freedesktop/systemd1",
3823 "org.freedesktop.systemd1.Manager",
3826 return bus_log_create_error(r
);
3828 r
= sd_bus_message_append(m
, "s", *name
);
3830 return bus_log_create_error(r
);
3832 r
= sd_bus_message_append_strv(m
, arg_clean_what
);
3834 return bus_log_create_error(r
);
3836 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
3838 log_error_errno(r
, "Failed to clean unit %s: %s", *name
, bus_error_message(&error
, r
));
3839 if (ret
== EXIT_SUCCESS
) {
3846 r
= bus_wait_for_units_add_unit(w
, *name
, BUS_WAIT_REFFED
|BUS_WAIT_FOR_MAINTENANCE_END
, NULL
, NULL
);
3848 return log_error_errno(r
, "Failed to watch unit %s: %m", *name
);
3852 r
= bus_wait_for_units_run(w
);
3854 return log_error_errno(r
, "Failed to wait for units: %m");
3855 if (r
== BUS_WAIT_FAILURE
)
3861 typedef struct ExecStatusInfo
{
3869 usec_t start_timestamp
;
3870 usec_t exit_timestamp
;
3875 ExecCommandFlags flags
;
3877 LIST_FIELDS(struct ExecStatusInfo
, exec
);
3880 static void exec_status_info_free(ExecStatusInfo
*i
) {
3889 static int exec_status_info_deserialize(sd_bus_message
*m
, ExecStatusInfo
*i
, bool is_ex_prop
) {
3890 _cleanup_strv_free_
char **ex_opts
= NULL
;
3891 uint64_t start_timestamp
, exit_timestamp
, start_timestamp_monotonic
, exit_timestamp_monotonic
;
3894 int32_t code
, status
;
3900 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_STRUCT
, is_ex_prop
? "sasasttttuii" : "sasbttttuii");
3902 return bus_log_parse_error(r
);
3906 r
= sd_bus_message_read(m
, "s", &path
);
3908 return bus_log_parse_error(r
);
3910 i
->path
= strdup(path
);
3914 r
= sd_bus_message_read_strv(m
, &i
->argv
);
3916 return bus_log_parse_error(r
);
3918 r
= is_ex_prop
? sd_bus_message_read_strv(m
, &ex_opts
) : sd_bus_message_read(m
, "b", &ignore
);
3920 return bus_log_parse_error(r
);
3922 r
= sd_bus_message_read(m
,
3924 &start_timestamp
, &start_timestamp_monotonic
,
3925 &exit_timestamp
, &exit_timestamp_monotonic
,
3929 return bus_log_parse_error(r
);
3932 r
= exec_command_flags_from_strv(ex_opts
, &i
->flags
);
3934 return log_error_errno(r
, "Failed to convert strv to ExecCommandFlags: %m");
3936 i
->ignore
= FLAGS_SET(i
->flags
, EXEC_COMMAND_IGNORE_FAILURE
);
3940 i
->start_timestamp
= (usec_t
) start_timestamp
;
3941 i
->exit_timestamp
= (usec_t
) exit_timestamp
;
3942 i
->pid
= (pid_t
) pid
;
3946 r
= sd_bus_message_exit_container(m
);
3948 return bus_log_parse_error(r
);
3953 typedef struct UnitCondition
{
3960 LIST_FIELDS(struct UnitCondition
, conditions
);
3963 static void unit_condition_free(UnitCondition
*c
) {
3972 DEFINE_TRIVIAL_CLEANUP_FUNC(UnitCondition
*, unit_condition_free
);
3974 typedef struct UnitStatusInfo
{
3976 const char *load_state
;
3977 const char *active_state
;
3978 const char *sub_state
;
3979 const char *unit_file_state
;
3980 const char *unit_file_preset
;
3982 const char *description
;
3983 const char *following
;
3985 char **documentation
;
3987 const char *fragment_path
;
3988 const char *source_path
;
3989 const char *control_group
;
3991 char **dropin_paths
;
3993 char **triggered_by
;
3996 const char *load_error
;
3999 usec_t inactive_exit_timestamp
;
4000 usec_t inactive_exit_timestamp_monotonic
;
4001 usec_t active_enter_timestamp
;
4002 usec_t active_exit_timestamp
;
4003 usec_t inactive_enter_timestamp
;
4005 bool need_daemon_reload
;
4011 const char *status_text
;
4012 const char *pid_file
;
4016 usec_t start_timestamp
;
4017 usec_t exit_timestamp
;
4019 int exit_code
, exit_status
;
4021 const char *log_namespace
;
4023 usec_t condition_timestamp
;
4024 bool condition_result
;
4025 LIST_HEAD(UnitCondition
, conditions
);
4027 usec_t assert_timestamp
;
4029 bool failed_assert_trigger
;
4030 bool failed_assert_negate
;
4031 const char *failed_assert
;
4032 const char *failed_assert_parameter
;
4033 usec_t next_elapse_real
;
4034 usec_t next_elapse_monotonic
;
4037 unsigned n_accepted
;
4038 unsigned n_connections
;
4042 /* Pairs of type, path */
4046 const char *sysfs_path
;
4048 /* Mount, Automount */
4055 uint64_t memory_current
;
4056 uint64_t memory_min
;
4057 uint64_t memory_low
;
4058 uint64_t memory_high
;
4059 uint64_t memory_max
;
4060 uint64_t memory_swap_max
;
4061 uint64_t memory_limit
;
4062 uint64_t cpu_usage_nsec
;
4063 uint64_t tasks_current
;
4065 uint64_t ip_ingress_bytes
;
4066 uint64_t ip_egress_bytes
;
4067 uint64_t io_read_bytes
;
4068 uint64_t io_write_bytes
;
4070 uint64_t default_memory_min
;
4071 uint64_t default_memory_low
;
4073 LIST_HEAD(ExecStatusInfo
, exec
);
4076 static void unit_status_info_free(UnitStatusInfo
*info
) {
4080 strv_free(info
->documentation
);
4081 strv_free(info
->dropin_paths
);
4082 strv_free(info
->triggered_by
);
4083 strv_free(info
->triggers
);
4084 strv_free(info
->listen
);
4086 while ((c
= info
->conditions
)) {
4087 LIST_REMOVE(conditions
, info
->conditions
, c
);
4088 unit_condition_free(c
);
4091 while ((p
= info
->exec
)) {
4092 LIST_REMOVE(exec
, info
->exec
, p
);
4093 exec_status_info_free(p
);
4097 static void format_active_state(const char *active_state
, const char **active_on
, const char **active_off
) {
4098 if (streq_ptr(active_state
, "failed")) {
4099 *active_on
= ansi_highlight_red();
4100 *active_off
= ansi_normal();
4101 } else if (STRPTR_IN_SET(active_state
, "active", "reloading")) {
4102 *active_on
= ansi_highlight_green();
4103 *active_off
= ansi_normal();
4105 *active_on
= *active_off
= "";
4108 static void print_status_info(
4113 char since1
[FORMAT_TIMESTAMP_RELATIVE_MAX
], since2
[FORMAT_TIMESTAMP_MAX
];
4114 const char *s1
, *s2
, *active_on
, *active_off
, *on
, *off
, *ss
;
4115 _cleanup_free_
char *formatted_path
= NULL
;
4124 /* This shows pretty information about a unit. See
4125 * print_property() for a low-level property printer */
4127 format_active_state(i
->active_state
, &active_on
, &active_off
);
4129 printf("%s%s%s %s", active_on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), active_off
, strna(i
->id
));
4131 if (i
->description
&& !streq_ptr(i
->id
, i
->description
))
4132 printf(" - %s", i
->description
);
4137 printf(" Follow: unit currently follows state of %s\n", i
->following
);
4139 if (STRPTR_IN_SET(i
->load_state
, "error", "not-found", "bad-setting")) {
4140 on
= ansi_highlight_red();
4141 off
= ansi_normal();
4145 path
= i
->source_path
?: i
->fragment_path
;
4146 if (path
&& terminal_urlify_path(path
, NULL
, &formatted_path
) >= 0)
4147 path
= formatted_path
;
4149 if (!isempty(i
->load_error
))
4150 printf(" Loaded: %s%s%s (Reason: %s)\n",
4151 on
, strna(i
->load_state
), off
, i
->load_error
);
4152 else if (path
&& !isempty(i
->unit_file_state
) && !isempty(i
->unit_file_preset
) &&
4153 !STR_IN_SET(i
->unit_file_state
, "generated", "transient"))
4154 printf(" Loaded: %s%s%s (%s; %s; vendor preset: %s)\n",
4155 on
, strna(i
->load_state
), off
, path
, i
->unit_file_state
, i
->unit_file_preset
);
4156 else if (path
&& !isempty(i
->unit_file_state
))
4157 printf(" Loaded: %s%s%s (%s; %s)\n",
4158 on
, strna(i
->load_state
), off
, path
, i
->unit_file_state
);
4160 printf(" Loaded: %s%s%s (%s)\n",
4161 on
, strna(i
->load_state
), off
, path
);
4163 printf(" Loaded: %s%s%s\n",
4164 on
, strna(i
->load_state
), off
);
4167 printf(" Transient: yes\n");
4169 if (!strv_isempty(i
->dropin_paths
)) {
4170 _cleanup_free_
char *dir
= NULL
;
4174 STRV_FOREACH(dropin
, i
->dropin_paths
) {
4175 _cleanup_free_
char *dropin_formatted
= NULL
;
4184 dir
= dirname_malloc(*dropin
);
4192 special_glyph(SPECIAL_GLYPH_TREE_RIGHT
));
4195 last
= ! (*(dropin
+ 1) && startswith(*(dropin
+ 1), dir
));
4197 if (terminal_urlify_path(*dropin
, basename(*dropin
), &dropin_formatted
) >= 0)
4198 df
= dropin_formatted
;
4202 printf("%s%s", df
, last
? "\n" : ", ");
4206 ss
= streq_ptr(i
->active_state
, i
->sub_state
) ? NULL
: i
->sub_state
;
4208 printf(" Active: %s%s (%s)%s",
4209 active_on
, strna(i
->active_state
), ss
, active_off
);
4211 printf(" Active: %s%s%s",
4212 active_on
, strna(i
->active_state
), active_off
);
4214 if (!isempty(i
->result
) && !streq(i
->result
, "success"))
4215 printf(" (Result: %s)", i
->result
);
4217 timestamp
= STRPTR_IN_SET(i
->active_state
, "active", "reloading") ? i
->active_enter_timestamp
:
4218 STRPTR_IN_SET(i
->active_state
, "inactive", "failed") ? i
->inactive_enter_timestamp
:
4219 STRPTR_IN_SET(i
->active_state
, "activating") ? i
->inactive_exit_timestamp
:
4220 i
->active_exit_timestamp
;
4222 s1
= format_timestamp_relative(since1
, sizeof(since1
), timestamp
);
4223 s2
= format_timestamp(since2
, sizeof(since2
), timestamp
);
4226 printf(" since %s; %s\n", s2
, s1
);
4228 printf(" since %s\n", s2
);
4232 STRV_FOREACH(t
, i
->triggered_by
) {
4233 UnitActiveState state
= _UNIT_ACTIVE_STATE_INVALID
;
4235 (void) get_state_one_unit(bus
, *t
, &state
);
4236 format_active_state(unit_active_state_to_string(state
), &on
, &off
);
4238 printf("%s %s%s%s %s\n",
4239 t
== i
->triggered_by
? "TriggeredBy:" : " ",
4240 on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
,
4244 if (endswith(i
->id
, ".timer")) {
4245 char tstamp1
[FORMAT_TIMESTAMP_RELATIVE_MAX
],
4246 tstamp2
[FORMAT_TIMESTAMP_MAX
];
4247 const char *next_rel_time
, *next_time
;
4248 dual_timestamp nw
, next
= {i
->next_elapse_real
,
4249 i
->next_elapse_monotonic
};
4252 printf(" Trigger: ");
4254 dual_timestamp_get(&nw
);
4255 next_elapse
= calc_next_elapse(&nw
, &next
);
4256 next_rel_time
= format_timestamp_relative(tstamp1
, sizeof tstamp1
, next_elapse
);
4257 next_time
= format_timestamp(tstamp2
, sizeof tstamp2
, next_elapse
);
4259 if (next_time
&& next_rel_time
)
4260 printf("%s; %s\n", next_time
, next_rel_time
);
4265 STRV_FOREACH(t
, i
->triggers
) {
4266 UnitActiveState state
= _UNIT_ACTIVE_STATE_INVALID
;
4268 (void) get_state_one_unit(bus
, *t
, &state
);
4269 format_active_state(unit_active_state_to_string(state
), &on
, &off
);
4271 printf("%s %s%s%s %s\n",
4272 t
== i
->triggers
? " Triggers:" : " ",
4273 on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
,
4277 if (!i
->condition_result
&& i
->condition_timestamp
> 0) {
4281 s1
= format_timestamp_relative(since1
, sizeof(since1
), i
->condition_timestamp
);
4282 s2
= format_timestamp(since2
, sizeof(since2
), i
->condition_timestamp
);
4284 printf(" Condition: start %scondition failed%s at %s%s%s\n",
4285 ansi_highlight_yellow(), ansi_normal(),
4286 s2
, s1
? "; " : "", strempty(s1
));
4288 LIST_FOREACH(conditions
, c
, i
->conditions
)
4289 if (c
->tristate
< 0)
4292 LIST_FOREACH(conditions
, c
, i
->conditions
)
4293 if (c
->tristate
< 0)
4294 printf(" %s %s=%s%s%s was not met\n",
4295 --n
? special_glyph(SPECIAL_GLYPH_TREE_BRANCH
) : special_glyph(SPECIAL_GLYPH_TREE_RIGHT
),
4297 c
->trigger
? "|" : "",
4298 c
->negate
? "!" : "",
4302 if (!i
->assert_result
&& i
->assert_timestamp
> 0) {
4303 s1
= format_timestamp_relative(since1
, sizeof(since1
), i
->assert_timestamp
);
4304 s2
= format_timestamp(since2
, sizeof(since2
), i
->assert_timestamp
);
4306 printf(" Assert: start %sassertion failed%s at %s%s%s\n",
4307 ansi_highlight_red(), ansi_normal(),
4308 s2
, s1
? "; " : "", strempty(s1
));
4309 if (i
->failed_assert_trigger
)
4310 printf(" none of the trigger assertions were met\n");
4311 else if (i
->failed_assert
)
4312 printf(" %s=%s%s was not met\n",
4314 i
->failed_assert_negate
? "!" : "",
4315 i
->failed_assert_parameter
);
4319 printf(" Device: %s\n", i
->sysfs_path
);
4321 printf(" Where: %s\n", i
->where
);
4323 printf(" What: %s\n", i
->what
);
4325 STRV_FOREACH(t
, i
->documentation
) {
4326 _cleanup_free_
char *formatted
= NULL
;
4329 if (terminal_urlify(*t
, NULL
, &formatted
) >= 0)
4334 printf(" %*s %s\n", 9, t
== i
->documentation
? "Docs:" : "", q
);
4337 STRV_FOREACH_PAIR(t
, t2
, i
->listen
)
4338 printf(" %*s %s (%s)\n", 9, t
== i
->listen
? "Listen:" : "", *t2
, *t
);
4341 printf(" Accepted: %u; Connected: %u;", i
->n_accepted
, i
->n_connections
);
4343 printf(" Refused: %u", i
->n_refused
);
4347 LIST_FOREACH(exec
, p
, i
->exec
) {
4348 _cleanup_free_
char *argv
= NULL
;
4351 /* Only show exited processes here */
4355 /* Don't print ExecXYZEx= properties here since it will appear as a
4356 * duplicate of the non-Ex= variant. */
4357 if (endswith(p
->name
, "Ex"))
4360 argv
= strv_join(p
->argv
, " ");
4361 printf(" Process: "PID_FMT
" %s=%s ", p
->pid
, p
->name
, strna(argv
));
4363 good
= is_clean_exit(p
->code
, p
->status
, EXIT_CLEAN_DAEMON
, NULL
);
4365 on
= ansi_highlight_red();
4366 off
= ansi_normal();
4370 printf("%s(code=%s, ", on
, sigchld_code_to_string(p
->code
));
4372 if (p
->code
== CLD_EXITED
) {
4375 printf("status=%i", p
->status
);
4377 c
= exit_status_to_string(p
->status
, EXIT_STATUS_LIBC
| EXIT_STATUS_SYSTEMD
);
4382 printf("signal=%s", signal_to_string(p
->status
));
4384 printf(")%s\n", off
);
4386 if (i
->main_pid
== p
->pid
&&
4387 i
->start_timestamp
== p
->start_timestamp
&&
4388 i
->exit_timestamp
== p
->start_timestamp
)
4389 /* Let's not show this twice */
4392 if (p
->pid
== i
->control_pid
)
4396 if (i
->main_pid
> 0 || i
->control_pid
> 0) {
4397 if (i
->main_pid
> 0) {
4398 printf(" Main PID: "PID_FMT
, i
->main_pid
);
4402 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
4403 _cleanup_free_
char *comm
= NULL
;
4405 (void) get_process_comm(i
->main_pid
, &comm
);
4407 printf(" (%s)", comm
);
4410 } else if (i
->exit_code
> 0) {
4411 printf(" (code=%s, ", sigchld_code_to_string(i
->exit_code
));
4413 if (i
->exit_code
== CLD_EXITED
) {
4416 printf("status=%i", i
->exit_status
);
4418 c
= exit_status_to_string(i
->exit_status
,
4419 EXIT_STATUS_LIBC
| EXIT_STATUS_SYSTEMD
);
4424 printf("signal=%s", signal_to_string(i
->exit_status
));
4429 if (i
->control_pid
> 0) {
4430 _cleanup_free_
char *c
= NULL
;
4432 if (i
->main_pid
> 0)
4433 fputs("; Control PID: ", stdout
);
4435 fputs("Cntrl PID: ", stdout
); /* if first in column, abbreviated so it fits alignment */
4437 printf(PID_FMT
, i
->control_pid
);
4439 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
4440 (void) get_process_comm(i
->control_pid
, &c
);
4450 printf(" Status: \"%s\"\n", i
->status_text
);
4451 if (i
->status_errno
> 0)
4452 printf(" Error: %i (%s)\n", i
->status_errno
, strerror_safe(i
->status_errno
));
4454 if (i
->ip_ingress_bytes
!= (uint64_t) -1 && i
->ip_egress_bytes
!= (uint64_t) -1) {
4455 char buf_in
[FORMAT_BYTES_MAX
], buf_out
[FORMAT_BYTES_MAX
];
4457 printf(" IP: %s in, %s out\n",
4458 format_bytes(buf_in
, sizeof(buf_in
), i
->ip_ingress_bytes
),
4459 format_bytes(buf_out
, sizeof(buf_out
), i
->ip_egress_bytes
));
4462 if (i
->io_read_bytes
!= UINT64_MAX
&& i
->io_write_bytes
!= UINT64_MAX
) {
4463 char buf_in
[FORMAT_BYTES_MAX
], buf_out
[FORMAT_BYTES_MAX
];
4465 printf(" IO: %s read, %s written\n",
4466 format_bytes(buf_in
, sizeof(buf_in
), i
->io_read_bytes
),
4467 format_bytes(buf_out
, sizeof(buf_out
), i
->io_write_bytes
));
4470 if (i
->tasks_current
!= (uint64_t) -1) {
4471 printf(" Tasks: %" PRIu64
, i
->tasks_current
);
4473 if (i
->tasks_max
!= (uint64_t) -1)
4474 printf(" (limit: %" PRIu64
")\n", i
->tasks_max
);
4479 if (i
->memory_current
!= (uint64_t) -1) {
4480 char buf
[FORMAT_BYTES_MAX
];
4482 printf(" Memory: %s", format_bytes(buf
, sizeof(buf
), i
->memory_current
));
4484 if (i
->memory_min
> 0 || i
->memory_low
> 0 ||
4485 i
->memory_high
!= CGROUP_LIMIT_MAX
|| i
->memory_max
!= CGROUP_LIMIT_MAX
||
4486 i
->memory_swap_max
!= CGROUP_LIMIT_MAX
||
4487 i
->memory_limit
!= CGROUP_LIMIT_MAX
) {
4488 const char *prefix
= "";
4491 if (i
->memory_min
> 0) {
4492 printf("%smin: %s", prefix
, format_bytes_cgroup_protection(buf
, sizeof(buf
), i
->memory_min
));
4495 if (i
->memory_low
> 0) {
4496 printf("%slow: %s", prefix
, format_bytes_cgroup_protection(buf
, sizeof(buf
), i
->memory_low
));
4499 if (i
->memory_high
!= CGROUP_LIMIT_MAX
) {
4500 printf("%shigh: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_high
));
4503 if (i
->memory_max
!= CGROUP_LIMIT_MAX
) {
4504 printf("%smax: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_max
));
4507 if (i
->memory_swap_max
!= CGROUP_LIMIT_MAX
) {
4508 printf("%sswap max: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_swap_max
));
4511 if (i
->memory_limit
!= CGROUP_LIMIT_MAX
) {
4512 printf("%slimit: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_limit
));
4520 if (i
->cpu_usage_nsec
!= (uint64_t) -1) {
4521 char buf
[FORMAT_TIMESPAN_MAX
];
4522 printf(" CPU: %s\n", format_timespan(buf
, sizeof(buf
), i
->cpu_usage_nsec
/ NSEC_PER_USEC
, USEC_PER_MSEC
));
4525 if (i
->control_group
) {
4526 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
4527 static const char prefix
[] = " ";
4530 printf(" CGroup: %s\n", i
->control_group
);
4533 if (c
> sizeof(prefix
) - 1)
4534 c
-= sizeof(prefix
) - 1;
4538 r
= unit_show_processes(bus
, i
->id
, i
->control_group
, prefix
, c
, get_output_flags(), &error
);
4543 /* Fallback for older systemd versions where the GetUnitProcesses() call is not yet available */
4545 if (i
->main_pid
> 0)
4546 extra
[k
++] = i
->main_pid
;
4548 if (i
->control_pid
> 0)
4549 extra
[k
++] = i
->control_pid
;
4551 show_cgroup_and_extra(SYSTEMD_CGROUP_CONTROLLER
, i
->control_group
, prefix
, c
, extra
, k
, get_output_flags());
4553 log_warning_errno(r
, "Failed to dump process list for '%s', ignoring: %s",
4554 i
->id
, bus_error_message(&error
, r
));
4557 if (i
->id
&& arg_transport
== BUS_TRANSPORT_LOCAL
)
4558 show_journal_by_unit(
4564 i
->inactive_exit_timestamp_monotonic
,
4567 get_output_flags() | OUTPUT_BEGIN_NEWLINE
,
4568 SD_JOURNAL_LOCAL_ONLY
,
4569 arg_scope
== UNIT_FILE_SYSTEM
,
4572 if (i
->need_daemon_reload
)
4573 warn_unit_file_changed(i
->id
);
4576 static void show_unit_help(UnitStatusInfo
*i
) {
4581 if (!i
->documentation
) {
4582 log_info("Documentation for %s not known.", i
->id
);
4586 STRV_FOREACH(p
, i
->documentation
)
4587 if (startswith(*p
, "man:"))
4588 show_man_page(*p
+ 4, false);
4590 log_info("Can't show: %s", *p
);
4593 static int map_main_pid(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4594 UnitStatusInfo
*i
= userdata
;
4598 r
= sd_bus_message_read(m
, "u", &u
);
4602 i
->main_pid
= (pid_t
) u
;
4608 static int map_load_error(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4609 const char *message
, **p
= userdata
;
4612 r
= sd_bus_message_read(m
, "(ss)", NULL
, &message
);
4616 if (!isempty(message
))
4622 static int map_listen(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4623 const char *type
, *path
;
4624 char ***p
= userdata
;
4627 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
4631 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0) {
4633 r
= strv_extend(p
, type
);
4637 r
= strv_extend(p
, path
);
4644 r
= sd_bus_message_exit_container(m
);
4651 static int map_conditions(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4652 UnitStatusInfo
*i
= userdata
;
4653 const char *cond
, *param
;
4654 int trigger
, negate
;
4658 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sbbsi)");
4662 while ((r
= sd_bus_message_read(m
, "(sbbsi)", &cond
, &trigger
, &negate
, ¶m
, &state
)) > 0) {
4663 _cleanup_(unit_condition_freep
) UnitCondition
*c
= NULL
;
4665 c
= new(UnitCondition
, 1);
4669 *c
= (UnitCondition
) {
4670 .name
= strdup(cond
),
4671 .param
= strdup(param
),
4677 if (!c
->name
|| !c
->param
)
4680 LIST_PREPEND(conditions
, i
->conditions
, TAKE_PTR(c
));
4685 r
= sd_bus_message_exit_container(m
);
4692 static int map_asserts(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4693 UnitStatusInfo
*i
= userdata
;
4694 const char *cond
, *param
;
4695 int trigger
, negate
;
4699 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sbbsi)");
4703 while ((r
= sd_bus_message_read(m
, "(sbbsi)", &cond
, &trigger
, &negate
, ¶m
, &state
)) > 0) {
4704 if (state
< 0 && (!trigger
|| !i
->failed_assert
)) {
4705 i
->failed_assert
= cond
;
4706 i
->failed_assert_trigger
= trigger
;
4707 i
->failed_assert_negate
= negate
;
4708 i
->failed_assert_parameter
= param
;
4714 r
= sd_bus_message_exit_container(m
);
4721 static int map_exec(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4722 _cleanup_free_ ExecStatusInfo
*info
= NULL
;
4723 ExecStatusInfo
*last
;
4724 UnitStatusInfo
*i
= userdata
;
4725 bool is_ex_prop
= endswith(member
, "Ex");
4728 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, is_ex_prop
? "(sasasttttuii)" : "(sasbttttuii)");
4732 info
= new0(ExecStatusInfo
, 1);
4736 LIST_FIND_TAIL(exec
, i
->exec
, last
);
4738 while ((r
= exec_status_info_deserialize(m
, info
, is_ex_prop
)) > 0) {
4740 info
->name
= strdup(member
);
4744 LIST_INSERT_AFTER(exec
, i
->exec
, last
, info
);
4747 info
= new0(ExecStatusInfo
, 1);
4754 r
= sd_bus_message_exit_container(m
);
4761 static int print_property(const char *name
, const char *expected_value
, sd_bus_message
*m
, bool value
, bool all
) {
4763 const char *contents
;
4769 /* This is a low-level property printer, see
4770 * print_status_info() for the nicer output */
4772 r
= sd_bus_message_peek_type(m
, &bus_type
, &contents
);
4778 case SD_BUS_TYPE_INT32
:
4779 if (endswith(name
, "ActionExitStatus")) {
4782 r
= sd_bus_message_read_basic(m
, bus_type
, &i
);
4786 if (i
>= 0 && i
<= 255)
4787 bus_print_property_valuef(name
, expected_value
, value
, "%"PRIi32
, i
);
4789 bus_print_property_value(name
, expected_value
, value
, "[not set]");
4792 } else if (streq(name
, "NUMAPolicy")) {
4795 r
= sd_bus_message_read_basic(m
, bus_type
, &i
);
4799 bus_print_property_valuef(name
, expected_value
, value
, "%s", strna(mpol_to_string(i
)));
4805 case SD_BUS_TYPE_STRUCT
:
4807 if (contents
[0] == SD_BUS_TYPE_UINT32
&& streq(name
, "Job")) {
4810 r
= sd_bus_message_read(m
, "(uo)", &u
, NULL
);
4812 return bus_log_parse_error(r
);
4815 bus_print_property_valuef(name
, expected_value
, value
, "%"PRIu32
, u
);
4817 bus_print_property_value(name
, expected_value
, value
, "");
4821 } else if (contents
[0] == SD_BUS_TYPE_STRING
&& streq(name
, "Unit")) {
4824 r
= sd_bus_message_read(m
, "(so)", &s
, NULL
);
4826 return bus_log_parse_error(r
);
4828 if (all
|| !isempty(s
))
4829 bus_print_property_value(name
, expected_value
, value
, s
);
4833 } else if (contents
[0] == SD_BUS_TYPE_STRING
&& streq(name
, "LoadError")) {
4834 const char *a
= NULL
, *b
= NULL
;
4836 r
= sd_bus_message_read(m
, "(ss)", &a
, &b
);
4838 return bus_log_parse_error(r
);
4840 if (!isempty(a
) || !isempty(b
))
4841 bus_print_property_valuef(name
, expected_value
, value
, "%s \"%s\"", strempty(a
), strempty(b
));
4843 bus_print_property_value(name
, expected_value
, value
, "");
4847 } else if (STR_IN_SET(name
, "SystemCallFilter", "RestrictAddressFamilies")) {
4848 _cleanup_strv_free_
char **l
= NULL
;
4851 r
= sd_bus_message_enter_container(m
, 'r', "bas");
4853 return bus_log_parse_error(r
);
4855 r
= sd_bus_message_read(m
, "b", &whitelist
);
4857 return bus_log_parse_error(r
);
4859 r
= sd_bus_message_read_strv(m
, &l
);
4861 return bus_log_parse_error(r
);
4863 r
= sd_bus_message_exit_container(m
);
4865 return bus_log_parse_error(r
);
4867 if (all
|| whitelist
|| !strv_isempty(l
)) {
4872 fputs(name
, stdout
);
4879 STRV_FOREACH(i
, l
) {
4887 fputc('\n', stdout
);
4892 } else if (STR_IN_SET(name
, "SELinuxContext", "AppArmorProfile", "SmackProcessLabel")) {
4896 r
= sd_bus_message_read(m
, "(bs)", &ignore
, &s
);
4898 return bus_log_parse_error(r
);
4901 bus_print_property_valuef(name
, expected_value
, value
, "%s%s", ignore
? "-" : "", s
);
4903 bus_print_property_value(name
, expected_value
, value
, "");
4907 } else if (endswith(name
, "ExitStatus") && streq(contents
, "aiai")) {
4908 const int32_t *status
, *signal
;
4909 size_t n_status
, n_signal
, i
;
4911 r
= sd_bus_message_enter_container(m
, 'r', "aiai");
4913 return bus_log_parse_error(r
);
4915 r
= sd_bus_message_read_array(m
, 'i', (const void **) &status
, &n_status
);
4917 return bus_log_parse_error(r
);
4919 r
= sd_bus_message_read_array(m
, 'i', (const void **) &signal
, &n_signal
);
4921 return bus_log_parse_error(r
);
4923 r
= sd_bus_message_exit_container(m
);
4925 return bus_log_parse_error(r
);
4927 n_status
/= sizeof(int32_t);
4928 n_signal
/= sizeof(int32_t);
4930 if (all
|| n_status
> 0 || n_signal
> 0) {
4934 fputs(name
, stdout
);
4938 for (i
= 0; i
< n_status
; i
++) {
4944 printf("%"PRIi32
, status
[i
]);
4947 for (i
= 0; i
< n_signal
; i
++) {
4950 str
= signal_to_string((int) signal
[i
]);
4960 printf("%"PRIi32
, status
[i
]);
4963 fputc('\n', stdout
);
4970 case SD_BUS_TYPE_ARRAY
:
4972 if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "EnvironmentFiles")) {
4976 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sb)");
4978 return bus_log_parse_error(r
);
4980 while ((r
= sd_bus_message_read(m
, "(sb)", &path
, &ignore
)) > 0)
4981 bus_print_property_valuef(name
, expected_value
, value
, "%s (ignore_errors=%s)", path
, yes_no(ignore
));
4984 return bus_log_parse_error(r
);
4986 r
= sd_bus_message_exit_container(m
);
4988 return bus_log_parse_error(r
);
4992 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "Paths")) {
4993 const char *type
, *path
;
4995 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
4997 return bus_log_parse_error(r
);
4999 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0)
5000 bus_print_property_valuef(name
, expected_value
, value
, "%s (%s)", path
, type
);
5002 return bus_log_parse_error(r
);
5004 r
= sd_bus_message_exit_container(m
);
5006 return bus_log_parse_error(r
);
5010 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "Listen")) {
5011 const char *type
, *path
;
5013 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5015 return bus_log_parse_error(r
);
5017 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0)
5018 bus_print_property_valuef(name
, expected_value
, value
, "%s (%s)", path
, type
);
5020 return bus_log_parse_error(r
);
5022 r
= sd_bus_message_exit_container(m
);
5024 return bus_log_parse_error(r
);
5028 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "TimersMonotonic")) {
5030 uint64_t v
, next_elapse
;
5032 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(stt)");
5034 return bus_log_parse_error(r
);
5036 while ((r
= sd_bus_message_read(m
, "(stt)", &base
, &v
, &next_elapse
)) > 0) {
5037 char timespan1
[FORMAT_TIMESPAN_MAX
] = "n/a", timespan2
[FORMAT_TIMESPAN_MAX
] = "n/a";
5039 (void) format_timespan(timespan1
, sizeof timespan1
, v
, 0);
5040 (void) format_timespan(timespan2
, sizeof timespan2
, next_elapse
, 0);
5042 bus_print_property_valuef(name
, expected_value
, value
,
5043 "{ %s=%s ; next_elapse=%s }", base
, timespan1
, timespan2
);
5046 return bus_log_parse_error(r
);
5048 r
= sd_bus_message_exit_container(m
);
5050 return bus_log_parse_error(r
);
5054 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "TimersCalendar")) {
5055 const char *base
, *spec
;
5056 uint64_t next_elapse
;
5058 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sst)");
5060 return bus_log_parse_error(r
);
5062 while ((r
= sd_bus_message_read(m
, "(sst)", &base
, &spec
, &next_elapse
)) > 0) {
5063 char timestamp
[FORMAT_TIMESTAMP_MAX
] = "n/a";
5065 (void) format_timestamp(timestamp
, sizeof(timestamp
), next_elapse
);
5066 bus_print_property_valuef(name
, expected_value
, value
,
5067 "{ %s=%s ; next_elapse=%s }", base
, spec
, timestamp
);
5070 return bus_log_parse_error(r
);
5072 r
= sd_bus_message_exit_container(m
);
5074 return bus_log_parse_error(r
);
5078 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& startswith(name
, "Exec")) {
5079 ExecStatusInfo info
= {};
5080 bool is_ex_prop
= endswith(name
, "Ex");
5082 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, is_ex_prop
? "(sasasttttuii)" : "(sasbttttuii)");
5084 return bus_log_parse_error(r
);
5086 while ((r
= exec_status_info_deserialize(m
, &info
, is_ex_prop
)) > 0) {
5087 char timestamp1
[FORMAT_TIMESTAMP_MAX
], timestamp2
[FORMAT_TIMESTAMP_MAX
];
5088 _cleanup_strv_free_
char **optv
= NULL
;
5089 _cleanup_free_
char *tt
, *o
= NULL
;
5091 tt
= strv_join(info
.argv
, " ");
5094 r
= exec_command_flags_to_strv(info
.flags
, &optv
);
5096 return log_error_errno(r
, "Failed to convert ExecCommandFlags to strv: %m");
5098 o
= strv_join(optv
, " ");
5100 bus_print_property_valuef(name
, expected_value
, value
,
5101 "{ path=%s ; argv[]=%s ; flags=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT
" ; code=%s ; status=%i%s%s }",
5105 strna(format_timestamp(timestamp1
, sizeof(timestamp1
), info
.start_timestamp
)),
5106 strna(format_timestamp(timestamp2
, sizeof(timestamp2
), info
.exit_timestamp
)),
5108 sigchld_code_to_string(info
.code
),
5110 info
.code
== CLD_EXITED
? "" : "/",
5111 strempty(info
.code
== CLD_EXITED
? NULL
: signal_to_string(info
.status
)));
5113 bus_print_property_valuef(name
, expected_value
, value
,
5114 "{ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT
" ; code=%s ; status=%i%s%s }",
5117 yes_no(info
.ignore
),
5118 strna(format_timestamp(timestamp1
, sizeof(timestamp1
), info
.start_timestamp
)),
5119 strna(format_timestamp(timestamp2
, sizeof(timestamp2
), info
.exit_timestamp
)),
5121 sigchld_code_to_string(info
.code
),
5123 info
.code
== CLD_EXITED
? "" : "/",
5124 strempty(info
.code
== CLD_EXITED
? NULL
: signal_to_string(info
.status
)));
5127 strv_free(info
.argv
);
5131 r
= sd_bus_message_exit_container(m
);
5133 return bus_log_parse_error(r
);
5137 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "DeviceAllow")) {
5138 const char *path
, *rwm
;
5140 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5142 return bus_log_parse_error(r
);
5144 while ((r
= sd_bus_message_read(m
, "(ss)", &path
, &rwm
)) > 0)
5145 bus_print_property_valuef(name
, expected_value
, value
, "%s %s", strna(path
), strna(rwm
));
5147 return bus_log_parse_error(r
);
5149 r
= sd_bus_message_exit_container(m
);
5151 return bus_log_parse_error(r
);
5155 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5156 STR_IN_SET(name
, "IODeviceWeight", "BlockIODeviceWeight")) {
5160 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5162 return bus_log_parse_error(r
);
5164 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &weight
)) > 0)
5165 bus_print_property_valuef(name
, expected_value
, value
, "%s %"PRIu64
, strna(path
), weight
);
5167 return bus_log_parse_error(r
);
5169 r
= sd_bus_message_exit_container(m
);
5171 return bus_log_parse_error(r
);
5175 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5176 (cgroup_io_limit_type_from_string(name
) >= 0 ||
5177 STR_IN_SET(name
, "BlockIOReadBandwidth", "BlockIOWriteBandwidth"))) {
5181 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5183 return bus_log_parse_error(r
);
5185 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &bandwidth
)) > 0)
5186 bus_print_property_valuef(name
, expected_value
, value
, "%s %"PRIu64
, strna(path
), bandwidth
);
5188 return bus_log_parse_error(r
);
5190 r
= sd_bus_message_exit_container(m
);
5192 return bus_log_parse_error(r
);
5196 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5197 streq(name
, "IODeviceLatencyTargetUSec")) {
5198 char ts
[FORMAT_TIMESPAN_MAX
];
5202 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5204 return bus_log_parse_error(r
);
5206 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &target
)) > 0)
5207 bus_print_property_valuef(name
, expected_value
, value
, "%s %s", strna(path
),
5208 format_timespan(ts
, sizeof(ts
), target
, 1));
5210 return bus_log_parse_error(r
);
5212 r
= sd_bus_message_exit_container(m
);
5214 return bus_log_parse_error(r
);
5218 } else if (contents
[0] == SD_BUS_TYPE_BYTE
&& streq(name
, "StandardInputData")) {
5219 _cleanup_free_
char *h
= NULL
;
5224 r
= sd_bus_message_read_array(m
, 'y', &p
, &sz
);
5226 return bus_log_parse_error(r
);
5228 n
= base64mem(p
, sz
, &h
);
5232 bus_print_property_value(name
, expected_value
, value
, h
);
5236 } else if (STR_IN_SET(name
, "IPAddressAllow", "IPAddressDeny")) {
5237 _cleanup_free_
char *addresses
= NULL
;
5239 r
= sd_bus_message_enter_container(m
, 'a', "(iayu)");
5241 return bus_log_parse_error(r
);
5244 _cleanup_free_
char *str
= NULL
;
5250 r
= sd_bus_message_enter_container(m
, 'r', "iayu");
5252 return bus_log_parse_error(r
);
5256 r
= sd_bus_message_read(m
, "i", &family
);
5258 return bus_log_parse_error(r
);
5260 r
= sd_bus_message_read_array(m
, 'y', &ap
, &an
);
5262 return bus_log_parse_error(r
);
5264 r
= sd_bus_message_read(m
, "u", &prefixlen
);
5266 return bus_log_parse_error(r
);
5268 r
= sd_bus_message_exit_container(m
);
5270 return bus_log_parse_error(r
);
5272 if (!IN_SET(family
, AF_INET
, AF_INET6
))
5275 if (an
!= FAMILY_ADDRESS_SIZE(family
))
5278 if (prefixlen
> FAMILY_ADDRESS_SIZE(family
) * 8)
5281 if (in_addr_prefix_to_string(family
, (union in_addr_union
*) ap
, prefixlen
, &str
) < 0)
5284 if (!strextend_with_separator(&addresses
, " ", str
, NULL
))
5288 r
= sd_bus_message_exit_container(m
);
5290 return bus_log_parse_error(r
);
5292 if (all
|| !isempty(addresses
))
5293 bus_print_property_value(name
, expected_value
, value
, strempty(addresses
));
5297 } else if (STR_IN_SET(name
, "BindPaths", "BindReadOnlyPaths")) {
5298 _cleanup_free_
char *paths
= NULL
;
5299 const char *source
, *dest
;
5303 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ssbt)");
5305 return bus_log_parse_error(r
);
5307 while ((r
= sd_bus_message_read(m
, "(ssbt)", &source
, &dest
, &ignore_enoent
, &rbind
)) > 0) {
5308 _cleanup_free_
char *str
= NULL
;
5310 if (isempty(source
))
5313 if (asprintf(&str
, "%s%s%s%s%s",
5314 ignore_enoent
? "-" : "",
5316 isempty(dest
) ? "" : ":",
5318 rbind
== MS_REC
? ":rbind" : "") < 0)
5321 if (!strextend_with_separator(&paths
, " ", str
, NULL
))
5325 return bus_log_parse_error(r
);
5327 r
= sd_bus_message_exit_container(m
);
5329 return bus_log_parse_error(r
);
5331 if (all
|| !isempty(paths
))
5332 bus_print_property_value(name
, expected_value
, value
, strempty(paths
));
5336 } else if (streq(name
, "TemporaryFileSystem")) {
5337 _cleanup_free_
char *paths
= NULL
;
5338 const char *target
, *option
;
5340 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5342 return bus_log_parse_error(r
);
5344 while ((r
= sd_bus_message_read(m
, "(ss)", &target
, &option
)) > 0) {
5345 _cleanup_free_
char *str
= NULL
;
5347 if (isempty(target
))
5350 if (asprintf(&str
, "%s%s%s", target
, isempty(option
) ? "" : ":", strempty(option
)) < 0)
5353 if (!strextend_with_separator(&paths
, " ", str
, NULL
))
5357 return bus_log_parse_error(r
);
5359 r
= sd_bus_message_exit_container(m
);
5361 return bus_log_parse_error(r
);
5363 if (all
|| !isempty(paths
))
5364 bus_print_property_value(name
, expected_value
, value
, strempty(paths
));
5368 } else if (streq(name
, "LogExtraFields")) {
5369 _cleanup_free_
char *fields
= NULL
;
5373 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "ay");
5375 return bus_log_parse_error(r
);
5377 while ((r
= sd_bus_message_read_array(m
, 'y', &p
, &sz
)) > 0) {
5378 _cleanup_free_
char *str
= NULL
;
5381 if (memchr(p
, 0, sz
))
5384 eq
= memchr(p
, '=', sz
);
5388 if (!journal_field_valid(p
, eq
- (const char*) p
, false))
5391 str
= malloc(sz
+ 1);
5398 if (!utf8_is_valid(str
))
5401 if (!strextend_with_separator(&fields
, " ", str
, NULL
))
5405 return bus_log_parse_error(r
);
5407 r
= sd_bus_message_exit_container(m
);
5409 return bus_log_parse_error(r
);
5411 if (all
|| !isempty(fields
))
5412 bus_print_property_value(name
, expected_value
, value
, strempty(fields
));
5415 } else if (contents
[0] == SD_BUS_TYPE_BYTE
&& STR_IN_SET(name
, "CPUAffinity", "NUMAMask", "AllowedCPUs", "AllowedMemoryNodes", "EffectiveCPUs", "EffectiveMemoryNodes")) {
5416 _cleanup_free_
char *affinity
= NULL
;
5417 _cleanup_(cpu_set_reset
) CPUSet set
= {};
5421 r
= sd_bus_message_read_array(m
, 'y', &a
, &n
);
5423 return bus_log_parse_error(r
);
5425 r
= cpu_set_from_dbus(a
, n
, &set
);
5427 return log_error_errno(r
, "Failed to deserialize %s: %m", name
);
5429 affinity
= cpu_set_to_range_string(&set
);
5433 bus_print_property_value(name
, expected_value
, value
, affinity
);
5444 typedef enum SystemctlShowMode
{
5445 SYSTEMCTL_SHOW_PROPERTIES
,
5446 SYSTEMCTL_SHOW_STATUS
,
5447 SYSTEMCTL_SHOW_HELP
,
5448 _SYSTEMCTL_SHOW_MODE_MAX
,
5449 _SYSTEMCTL_SHOW_MODE_INVALID
= -1,
5450 } SystemctlShowMode
;
5452 static const char* const systemctl_show_mode_table
[_SYSTEMCTL_SHOW_MODE_MAX
] = {
5453 [SYSTEMCTL_SHOW_PROPERTIES
] = "show",
5454 [SYSTEMCTL_SHOW_STATUS
] = "status",
5455 [SYSTEMCTL_SHOW_HELP
] = "help",
5458 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(systemctl_show_mode
, SystemctlShowMode
);
5460 static int show_one(
5464 SystemctlShowMode show_mode
,
5468 static const struct bus_properties_map property_map
[] = {
5469 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
5470 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
) },
5471 { "Documentation", "as", NULL
, offsetof(UnitStatusInfo
, documentation
) },
5474 { "Id", "s", NULL
, offsetof(UnitStatusInfo
, id
) },
5475 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
5476 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
) },
5477 { "SubState", "s", NULL
, offsetof(UnitStatusInfo
, sub_state
) },
5478 { "UnitFileState", "s", NULL
, offsetof(UnitStatusInfo
, unit_file_state
) },
5479 { "UnitFilePreset", "s", NULL
, offsetof(UnitStatusInfo
, unit_file_preset
) },
5480 { "Description", "s", NULL
, offsetof(UnitStatusInfo
, description
) },
5481 { "Following", "s", NULL
, offsetof(UnitStatusInfo
, following
) },
5482 { "Documentation", "as", NULL
, offsetof(UnitStatusInfo
, documentation
) },
5483 { "FragmentPath", "s", NULL
, offsetof(UnitStatusInfo
, fragment_path
) },
5484 { "SourcePath", "s", NULL
, offsetof(UnitStatusInfo
, source_path
) },
5485 { "ControlGroup", "s", NULL
, offsetof(UnitStatusInfo
, control_group
) },
5486 { "DropInPaths", "as", NULL
, offsetof(UnitStatusInfo
, dropin_paths
) },
5487 { "LoadError", "(ss)", map_load_error
, offsetof(UnitStatusInfo
, load_error
) },
5488 { "Result", "s", NULL
, offsetof(UnitStatusInfo
, result
) },
5489 { "TriggeredBy", "as", NULL
, offsetof(UnitStatusInfo
, triggered_by
) },
5490 { "Triggers", "as", NULL
, offsetof(UnitStatusInfo
, triggers
) },
5491 { "InactiveExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, inactive_exit_timestamp
) },
5492 { "InactiveExitTimestampMonotonic", "t", NULL
, offsetof(UnitStatusInfo
, inactive_exit_timestamp_monotonic
) },
5493 { "ActiveEnterTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, active_enter_timestamp
) },
5494 { "ActiveExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, active_exit_timestamp
) },
5495 { "InactiveEnterTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, inactive_enter_timestamp
) },
5496 { "NeedDaemonReload", "b", NULL
, offsetof(UnitStatusInfo
, need_daemon_reload
) },
5497 { "Transient", "b", NULL
, offsetof(UnitStatusInfo
, transient
) },
5498 { "ExecMainPID", "u", NULL
, offsetof(UnitStatusInfo
, main_pid
) },
5499 { "MainPID", "u", map_main_pid
, 0 },
5500 { "ControlPID", "u", NULL
, offsetof(UnitStatusInfo
, control_pid
) },
5501 { "StatusText", "s", NULL
, offsetof(UnitStatusInfo
, status_text
) },
5502 { "PIDFile", "s", NULL
, offsetof(UnitStatusInfo
, pid_file
) },
5503 { "StatusErrno", "i", NULL
, offsetof(UnitStatusInfo
, status_errno
) },
5504 { "ExecMainStartTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, start_timestamp
) },
5505 { "ExecMainExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, exit_timestamp
) },
5506 { "ExecMainCode", "i", NULL
, offsetof(UnitStatusInfo
, exit_code
) },
5507 { "ExecMainStatus", "i", NULL
, offsetof(UnitStatusInfo
, exit_status
) },
5508 { "LogNamespace", "s", NULL
, offsetof(UnitStatusInfo
, log_namespace
) },
5509 { "ConditionTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, condition_timestamp
) },
5510 { "ConditionResult", "b", NULL
, offsetof(UnitStatusInfo
, condition_result
) },
5511 { "Conditions", "a(sbbsi)", map_conditions
, 0 },
5512 { "AssertTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, assert_timestamp
) },
5513 { "AssertResult", "b", NULL
, offsetof(UnitStatusInfo
, assert_result
) },
5514 { "Asserts", "a(sbbsi)", map_asserts
, 0 },
5515 { "NextElapseUSecRealtime", "t", NULL
, offsetof(UnitStatusInfo
, next_elapse_real
) },
5516 { "NextElapseUSecMonotonic", "t", NULL
, offsetof(UnitStatusInfo
, next_elapse_monotonic
) },
5517 { "NAccepted", "u", NULL
, offsetof(UnitStatusInfo
, n_accepted
) },
5518 { "NConnections", "u", NULL
, offsetof(UnitStatusInfo
, n_connections
) },
5519 { "NRefused", "u", NULL
, offsetof(UnitStatusInfo
, n_refused
) },
5520 { "Accept", "b", NULL
, offsetof(UnitStatusInfo
, accept
) },
5521 { "Listen", "a(ss)", map_listen
, offsetof(UnitStatusInfo
, listen
) },
5522 { "SysFSPath", "s", NULL
, offsetof(UnitStatusInfo
, sysfs_path
) },
5523 { "Where", "s", NULL
, offsetof(UnitStatusInfo
, where
) },
5524 { "What", "s", NULL
, offsetof(UnitStatusInfo
, what
) },
5525 { "MemoryCurrent", "t", NULL
, offsetof(UnitStatusInfo
, memory_current
) },
5526 { "DefaultMemoryMin", "t", NULL
, offsetof(UnitStatusInfo
, default_memory_min
) },
5527 { "DefaultMemoryLow", "t", NULL
, offsetof(UnitStatusInfo
, default_memory_low
) },
5528 { "MemoryMin", "t", NULL
, offsetof(UnitStatusInfo
, memory_min
) },
5529 { "MemoryLow", "t", NULL
, offsetof(UnitStatusInfo
, memory_low
) },
5530 { "MemoryHigh", "t", NULL
, offsetof(UnitStatusInfo
, memory_high
) },
5531 { "MemoryMax", "t", NULL
, offsetof(UnitStatusInfo
, memory_max
) },
5532 { "MemorySwapMax", "t", NULL
, offsetof(UnitStatusInfo
, memory_swap_max
) },
5533 { "MemoryLimit", "t", NULL
, offsetof(UnitStatusInfo
, memory_limit
) },
5534 { "CPUUsageNSec", "t", NULL
, offsetof(UnitStatusInfo
, cpu_usage_nsec
) },
5535 { "TasksCurrent", "t", NULL
, offsetof(UnitStatusInfo
, tasks_current
) },
5536 { "TasksMax", "t", NULL
, offsetof(UnitStatusInfo
, tasks_max
) },
5537 { "IPIngressBytes", "t", NULL
, offsetof(UnitStatusInfo
, ip_ingress_bytes
) },
5538 { "IPEgressBytes", "t", NULL
, offsetof(UnitStatusInfo
, ip_egress_bytes
) },
5539 { "IOReadBytes", "t", NULL
, offsetof(UnitStatusInfo
, io_read_bytes
) },
5540 { "IOWriteBytes", "t", NULL
, offsetof(UnitStatusInfo
, io_write_bytes
) },
5541 { "ExecCondition", "a(sasbttttuii)", map_exec
, 0 },
5542 { "ExecConditionEx", "a(sasasttttuii)", map_exec
, 0 },
5543 { "ExecStartPre", "a(sasbttttuii)", map_exec
, 0 },
5544 { "ExecStartPreEx", "a(sasasttttuii)", map_exec
, 0 },
5545 { "ExecStart", "a(sasbttttuii)", map_exec
, 0 },
5546 { "ExecStartEx", "a(sasasttttuii)", map_exec
, 0 },
5547 { "ExecStartPost", "a(sasbttttuii)", map_exec
, 0 },
5548 { "ExecStartPostEx", "a(sasasttttuii)", map_exec
, 0 },
5549 { "ExecReload", "a(sasbttttuii)", map_exec
, 0 },
5550 { "ExecReloadEx", "a(sasasttttuii)", map_exec
, 0 },
5551 { "ExecStopPre", "a(sasbttttuii)", map_exec
, 0 },
5552 { "ExecStop", "a(sasbttttuii)", map_exec
, 0 },
5553 { "ExecStopEx", "a(sasasttttuii)", map_exec
, 0 },
5554 { "ExecStopPost", "a(sasbttttuii)", map_exec
, 0 },
5555 { "ExecStopPostEx", "a(sasasttttuii)", map_exec
, 0 },
5559 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5560 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5561 _cleanup_set_free_ Set
*found_properties
= NULL
;
5562 _cleanup_(unit_status_info_free
) UnitStatusInfo info
= {
5563 .memory_current
= (uint64_t) -1,
5564 .memory_high
= CGROUP_LIMIT_MAX
,
5565 .memory_max
= CGROUP_LIMIT_MAX
,
5566 .memory_swap_max
= CGROUP_LIMIT_MAX
,
5567 .memory_limit
= (uint64_t) -1,
5568 .cpu_usage_nsec
= (uint64_t) -1,
5569 .tasks_current
= (uint64_t) -1,
5570 .tasks_max
= (uint64_t) -1,
5571 .ip_ingress_bytes
= (uint64_t) -1,
5572 .ip_egress_bytes
= (uint64_t) -1,
5573 .io_read_bytes
= UINT64_MAX
,
5574 .io_write_bytes
= UINT64_MAX
,
5582 log_debug("Showing one %s", path
);
5584 r
= bus_map_all_properties(
5586 "org.freedesktop.systemd1",
5588 show_mode
== SYSTEMCTL_SHOW_STATUS
? status_map
: property_map
,
5589 BUS_MAP_BOOLEAN_AS_BOOL
,
5594 return log_error_errno(r
, "Failed to get properties: %s", bus_error_message(&error
, r
));
5596 if (unit
&& streq_ptr(info
.load_state
, "not-found") && streq_ptr(info
.active_state
, "inactive")) {
5597 log_full(show_mode
== SYSTEMCTL_SHOW_STATUS
? LOG_ERR
: LOG_DEBUG
,
5598 "Unit %s could not be found.", unit
);
5600 if (show_mode
== SYSTEMCTL_SHOW_STATUS
)
5601 return EXIT_PROGRAM_OR_SERVICES_STATUS_UNKNOWN
;
5602 else if (show_mode
== SYSTEMCTL_SHOW_HELP
)
5611 if (show_mode
== SYSTEMCTL_SHOW_STATUS
) {
5612 print_status_info(bus
, &info
, ellipsized
);
5614 if (info
.active_state
&& !STR_IN_SET(info
.active_state
, "active", "reloading"))
5615 return EXIT_PROGRAM_NOT_RUNNING
;
5617 return EXIT_PROGRAM_RUNNING_OR_SERVICE_OK
;
5619 } else if (show_mode
== SYSTEMCTL_SHOW_HELP
) {
5620 show_unit_help(&info
);
5624 r
= sd_bus_message_rewind(reply
, true);
5626 return log_error_errno(r
, "Failed to rewind: %s", bus_error_message(&error
, r
));
5628 r
= bus_message_print_all_properties(reply
, print_property
, arg_properties
, arg_value
, arg_all
, &found_properties
);
5630 return bus_log_parse_error(r
);
5632 STRV_FOREACH(pp
, arg_properties
)
5633 if (!set_contains(found_properties
, *pp
))
5634 log_debug("Property %s does not exist.", *pp
);
5639 static int get_unit_dbus_path_by_pid(
5644 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5645 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5649 r
= sd_bus_call_method(
5651 "org.freedesktop.systemd1",
5652 "/org/freedesktop/systemd1",
5653 "org.freedesktop.systemd1.Manager",
5659 return log_error_errno(r
, "Failed to get unit for PID %"PRIu32
": %s", pid
, bus_error_message(&error
, r
));
5661 r
= sd_bus_message_read(reply
, "o", &u
);
5663 return bus_log_parse_error(r
);
5673 static int show_all(
5678 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5679 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
5684 r
= get_unit_list(bus
, NULL
, NULL
, &unit_infos
, 0, &reply
);
5688 (void) pager_open(arg_pager_flags
);
5692 typesafe_qsort(unit_infos
, c
, compare_unit_info
);
5694 for (u
= unit_infos
; u
< unit_infos
+ c
; u
++) {
5695 _cleanup_free_
char *p
= NULL
;
5697 p
= unit_dbus_path_from_name(u
->id
);
5701 r
= show_one(bus
, p
, u
->id
, SYSTEMCTL_SHOW_STATUS
, new_line
, ellipsized
);
5704 else if (r
> 0 && ret
== 0)
5711 static int show_system_status(sd_bus
*bus
) {
5712 char since1
[FORMAT_TIMESTAMP_RELATIVE_MAX
], since2
[FORMAT_TIMESTAMP_MAX
];
5713 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5714 _cleanup_(machine_info_clear
) struct machine_info mi
= {};
5715 _cleanup_free_
char *hn
= NULL
;
5716 const char *on
, *off
;
5719 hn
= gethostname_malloc();
5723 r
= bus_map_all_properties(
5725 "org.freedesktop.systemd1",
5726 "/org/freedesktop/systemd1",
5727 machine_info_property_map
,
5733 return log_error_errno(r
, "Failed to read server status: %s", bus_error_message(&error
, r
));
5735 if (streq_ptr(mi
.state
, "degraded")) {
5736 on
= ansi_highlight_red();
5737 off
= ansi_normal();
5738 } else if (streq_ptr(mi
.state
, "running")) {
5739 on
= ansi_highlight_green();
5740 off
= ansi_normal();
5742 on
= ansi_highlight_yellow();
5743 off
= ansi_normal();
5746 printf("%s%s%s %s\n", on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
, arg_host
? arg_host
: hn
);
5748 printf(" State: %s%s%s\n",
5749 on
, strna(mi
.state
), off
);
5751 printf(" Jobs: %" PRIu32
" queued\n", mi
.n_jobs
);
5752 printf(" Failed: %" PRIu32
" units\n", mi
.n_failed_units
);
5754 printf(" Since: %s; %s\n",
5755 format_timestamp(since2
, sizeof(since2
), mi
.timestamp
),
5756 format_timestamp_relative(since1
, sizeof(since1
), mi
.timestamp
));
5758 printf(" CGroup: %s\n", mi
.control_group
?: "/");
5759 if (IN_SET(arg_transport
,
5760 BUS_TRANSPORT_LOCAL
,
5761 BUS_TRANSPORT_MACHINE
)) {
5762 static const char prefix
[] = " ";
5766 if (c
> sizeof(prefix
) - 1)
5767 c
-= sizeof(prefix
) - 1;
5771 show_cgroup(SYSTEMD_CGROUP_CONTROLLER
, strempty(mi
.control_group
), prefix
, c
, get_output_flags());
5777 static int show(int argc
, char *argv
[], void *userdata
) {
5778 bool new_line
= false, ellipsized
= false;
5779 SystemctlShowMode show_mode
;
5785 show_mode
= systemctl_show_mode_from_string(argv
[0]);
5787 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
5788 "Invalid argument.");
5790 if (show_mode
== SYSTEMCTL_SHOW_HELP
&& argc
<= 1)
5791 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
5792 "This command expects one or more unit names. Did you mean --help?");
5794 r
= acquire_bus(BUS_MANAGER
, &bus
);
5798 (void) pager_open(arg_pager_flags
);
5800 /* If no argument is specified inspect the manager itself */
5801 if (show_mode
== SYSTEMCTL_SHOW_PROPERTIES
&& argc
<= 1)
5802 return show_one(bus
, "/org/freedesktop/systemd1", NULL
, show_mode
, &new_line
, &ellipsized
);
5804 if (show_mode
== SYSTEMCTL_SHOW_STATUS
&& argc
<= 1) {
5806 show_system_status(bus
);
5810 ret
= show_all(bus
, &new_line
, &ellipsized
);
5812 _cleanup_free_
char **patterns
= NULL
;
5815 STRV_FOREACH(name
, strv_skip(argv
, 1)) {
5816 _cleanup_free_
char *path
= NULL
, *unit
= NULL
;
5819 if (safe_atou32(*name
, &id
) < 0) {
5820 if (strv_push(&patterns
, *name
) < 0)
5824 } else if (show_mode
== SYSTEMCTL_SHOW_PROPERTIES
) {
5825 /* Interpret as job id */
5826 if (asprintf(&path
, "/org/freedesktop/systemd1/job/%u", id
) < 0)
5830 /* Interpret as PID */
5831 r
= get_unit_dbus_path_by_pid(bus
, id
, &path
);
5837 r
= unit_name_from_dbus_path(path
, &unit
);
5842 r
= show_one(bus
, path
, unit
, show_mode
, &new_line
, &ellipsized
);
5845 else if (r
> 0 && ret
== 0)
5849 if (!strv_isempty(patterns
)) {
5850 _cleanup_strv_free_
char **names
= NULL
;
5852 r
= expand_names(bus
, patterns
, NULL
, &names
, NULL
);
5854 return log_error_errno(r
, "Failed to expand names: %m");
5856 r
= maybe_extend_with_unit_dependencies(bus
, &names
);
5860 STRV_FOREACH(name
, names
) {
5861 _cleanup_free_
char *path
;
5863 path
= unit_dbus_path_from_name(*name
);
5867 r
= show_one(bus
, path
, *name
, show_mode
, &new_line
, &ellipsized
);
5870 if (r
> 0 && ret
== 0)
5876 if (ellipsized
&& !arg_quiet
)
5877 printf("Hint: Some lines were ellipsized, use -l to show in full.\n");
5882 static int cat(int argc
, char *argv
[], void *userdata
) {
5883 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
5884 _cleanup_strv_free_
char **names
= NULL
;
5890 /* Include all units by default — i.e. continue as if the --all
5891 * option was used */
5892 if (strv_isempty(arg_states
))
5895 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
5896 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot remotely cat units.");
5898 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
5900 return log_error_errno(r
, "Failed to determine unit paths: %m");
5902 r
= acquire_bus(BUS_MANAGER
, &bus
);
5906 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
5908 return log_error_errno(r
, "Failed to expand names: %m");
5910 r
= maybe_extend_with_unit_dependencies(bus
, &names
);
5914 (void) pager_open(arg_pager_flags
);
5916 STRV_FOREACH(name
, names
) {
5917 _cleanup_free_
char *fragment_path
= NULL
;
5918 _cleanup_strv_free_
char **dropin_paths
= NULL
;
5920 r
= unit_find_paths(bus
, *name
, &lp
, false, &fragment_path
, &dropin_paths
);
5921 if (r
== -ERFKILL
) {
5922 printf("%s# Unit %s is masked%s.\n",
5923 ansi_highlight_magenta(),
5928 if (r
== -EKEYREJECTED
) {
5929 printf("%s# Unit %s could not be loaded.%s\n",
5930 ansi_highlight_magenta(),
5938 /* Skip units which have no on-disk counterpart, but
5939 * propagate the error to the user */
5949 if (need_daemon_reload(bus
, *name
) > 0) /* ignore errors (<0), this is informational output */
5951 "%s# Warning: %s changed on disk, the version systemd has loaded is outdated.\n"
5952 "%s# This output shows the current version of the unit's original fragment and drop-in files.\n"
5953 "%s# If fragments or drop-ins were added or removed, they are not properly reflected in this output.\n"
5954 "%s# Run 'systemctl%s daemon-reload' to reload units.%s\n",
5955 ansi_highlight_red(),
5957 ansi_highlight_red(),
5958 ansi_highlight_red(),
5959 ansi_highlight_red(),
5960 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user",
5963 r
= cat_files(fragment_path
, dropin_paths
, 0);
5971 static int set_property(int argc
, char *argv
[], void *userdata
) {
5972 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
5973 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5974 _cleanup_free_
char *n
= NULL
;
5979 r
= acquire_bus(BUS_MANAGER
, &bus
);
5983 polkit_agent_open_maybe();
5985 r
= sd_bus_message_new_method_call(
5988 "org.freedesktop.systemd1",
5989 "/org/freedesktop/systemd1",
5990 "org.freedesktop.systemd1.Manager",
5991 "SetUnitProperties");
5993 return bus_log_create_error(r
);
5995 r
= unit_name_mangle(argv
[1], arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, &n
);
5997 return log_error_errno(r
, "Failed to mangle unit name: %m");
5999 t
= unit_name_to_type(n
);
6001 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid unit type: %s", n
);
6003 r
= sd_bus_message_append(m
, "sb", n
, arg_runtime
);
6005 return bus_log_create_error(r
);
6007 r
= sd_bus_message_open_container(m
, SD_BUS_TYPE_ARRAY
, "(sv)");
6009 return bus_log_create_error(r
);
6011 r
= bus_append_unit_property_assignment_many(m
, t
, strv_skip(argv
, 2));
6015 r
= sd_bus_message_close_container(m
);
6017 return bus_log_create_error(r
);
6019 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6021 return log_error_errno(r
, "Failed to set unit properties on %s: %s", n
, bus_error_message(&error
, r
));
6026 static int daemon_reload(int argc
, char *argv
[], void *userdata
) {
6027 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6028 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6033 r
= acquire_bus(BUS_MANAGER
, &bus
);
6037 polkit_agent_open_maybe();
6039 switch (arg_action
) {
6046 method
= "Reexecute";
6049 case ACTION_SYSTEMCTL
:
6050 method
= streq(argv
[0], "daemon-reexec") ? "Reexecute" :
6051 /* "daemon-reload" */ "Reload";
6055 assert_not_reached("Unexpected action");
6058 r
= sd_bus_message_new_method_call(
6061 "org.freedesktop.systemd1",
6062 "/org/freedesktop/systemd1",
6063 "org.freedesktop.systemd1.Manager",
6066 return bus_log_create_error(r
);
6068 /* Note we use an extra-long timeout here. This is because a reload or reexec means generators are rerun which
6069 * are timed out after DEFAULT_TIMEOUT_USEC. Let's use twice that time here, so that the generators can have
6070 * their timeout, and for everything else there's the same time budget in place. */
6072 r
= sd_bus_call(bus
, m
, DEFAULT_TIMEOUT_USEC
* 2, &error
, NULL
);
6074 /* On reexecution, we expect a disconnect, not a reply */
6075 if (IN_SET(r
, -ETIMEDOUT
, -ECONNRESET
) && streq(method
, "Reexecute"))
6078 if (r
< 0 && arg_action
== ACTION_SYSTEMCTL
)
6079 return log_error_errno(r
, "Failed to reload daemon: %s", bus_error_message(&error
, r
));
6081 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
6082 * old ways of doing things, hence don't log any error in that case here. */
6084 return r
< 0 ? r
: 0;
6087 static int trivial_method(int argc
, char *argv
[], void *userdata
) {
6088 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6096 r
= acquire_bus(BUS_MANAGER
, &bus
);
6100 polkit_agent_open_maybe();
6103 streq(argv
[0], "clear-jobs") ||
6104 streq(argv
[0], "cancel") ? "ClearJobs" :
6105 streq(argv
[0], "reset-failed") ? "ResetFailed" :
6106 streq(argv
[0], "halt") ? "Halt" :
6107 streq(argv
[0], "reboot") ? "Reboot" :
6108 streq(argv
[0], "kexec") ? "KExec" :
6109 streq(argv
[0], "exit") ? "Exit" :
6110 /* poweroff */ "PowerOff";
6112 r
= sd_bus_call_method(
6114 "org.freedesktop.systemd1",
6115 "/org/freedesktop/systemd1",
6116 "org.freedesktop.systemd1.Manager",
6121 if (r
< 0 && arg_action
== ACTION_SYSTEMCTL
)
6122 return log_error_errno(r
, "Failed to execute operation: %s", bus_error_message(&error
, r
));
6124 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
6125 * old ways of doing things, hence don't log any error in that case here. */
6127 return r
< 0 ? r
: 0;
6130 static int reset_failed(int argc
, char *argv
[], void *userdata
) {
6131 _cleanup_strv_free_
char **names
= NULL
;
6137 return trivial_method(argc
, argv
, userdata
);
6139 r
= acquire_bus(BUS_MANAGER
, &bus
);
6143 polkit_agent_open_maybe();
6145 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
6147 return log_error_errno(r
, "Failed to expand names: %m");
6149 STRV_FOREACH(name
, names
) {
6150 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6152 q
= sd_bus_call_method(
6154 "org.freedesktop.systemd1",
6155 "/org/freedesktop/systemd1",
6156 "org.freedesktop.systemd1.Manager",
6162 log_error_errno(q
, "Failed to reset failed state of unit %s: %s", *name
, bus_error_message(&error
, q
));
6171 static int print_variable(const char *s
) {
6173 _cleanup_free_
char *esc
= NULL
;
6175 sep
= strchr(s
, '=');
6177 return log_error_errno(SYNTHETIC_ERRNO(EUCLEAN
),
6178 "Invalid environment block");
6180 esc
= shell_maybe_quote(sep
+ 1, ESCAPE_POSIX
);
6184 printf("%.*s=%s\n", (int)(sep
-s
), s
, esc
);
6188 static int show_environment(int argc
, char *argv
[], void *userdata
) {
6189 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6190 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
6195 r
= acquire_bus(BUS_MANAGER
, &bus
);
6199 (void) pager_open(arg_pager_flags
);
6201 r
= sd_bus_get_property(
6203 "org.freedesktop.systemd1",
6204 "/org/freedesktop/systemd1",
6205 "org.freedesktop.systemd1.Manager",
6211 return log_error_errno(r
, "Failed to get environment: %s", bus_error_message(&error
, r
));
6213 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "s");
6215 return bus_log_parse_error(r
);
6217 while ((r
= sd_bus_message_read_basic(reply
, SD_BUS_TYPE_STRING
, &text
)) > 0) {
6218 r
= print_variable(text
);
6223 return bus_log_parse_error(r
);
6225 r
= sd_bus_message_exit_container(reply
);
6227 return bus_log_parse_error(r
);
6232 static int switch_root(int argc
, char *argv
[], void *userdata
) {
6233 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6234 _cleanup_free_
char *cmdline_init
= NULL
;
6235 const char *root
, *init
;
6239 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
6240 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot switch root remotely.");
6242 if (argc
< 2 || argc
> 3)
6243 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Wrong number of arguments.");
6250 r
= proc_cmdline_get_key("init", 0, &cmdline_init
);
6252 log_debug_errno(r
, "Failed to parse /proc/cmdline: %m");
6254 init
= cmdline_init
;
6257 init
= empty_to_null(init
);
6259 const char *root_systemd_path
= NULL
, *root_init_path
= NULL
;
6261 root_systemd_path
= prefix_roota(root
, "/" SYSTEMD_BINARY_PATH
);
6262 root_init_path
= prefix_roota(root
, init
);
6264 /* If the passed init is actually the same as the
6265 * systemd binary, then let's suppress it. */
6266 if (files_same(root_init_path
, root_systemd_path
, 0) > 0)
6270 /* Instruct PID1 to exclude us from its killing spree applied during the transition. Otherwise we
6271 * would exit with a failure status even though the switch to the new root has succeed. */
6273 assert(saved_argv
[0]);
6274 saved_argv
[0][0] = '@';
6276 r
= acquire_bus(BUS_MANAGER
, &bus
);
6280 /* If we are slow to exit after the root switch, the new systemd instance
6281 * will send us a signal to terminate. Just ignore it and exit normally.
6282 * This way the unit does not end up as failed.
6284 r
= ignore_signals(SIGTERM
, -1);
6286 log_warning_errno(r
, "Failed to change disposition of SIGTERM to ignore: %m");
6288 log_debug("Switching root - root: %s; init: %s", root
, strna(init
));
6290 r
= sd_bus_call_method(
6292 "org.freedesktop.systemd1",
6293 "/org/freedesktop/systemd1",
6294 "org.freedesktop.systemd1.Manager",
6300 (void) default_signals(SIGTERM
, -1);
6302 return log_error_errno(r
, "Failed to switch root: %s", bus_error_message(&error
, r
));
6308 static int log_level(int argc
, char *argv
[], void *userdata
) {
6310 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6313 r
= acquire_bus(BUS_MANAGER
, &bus
);
6318 _cleanup_free_
char *level
= NULL
;
6320 r
= sd_bus_get_property_string(
6322 "org.freedesktop.systemd1",
6323 "/org/freedesktop/systemd1",
6324 "org.freedesktop.systemd1.Manager",
6329 return log_error_errno(r
, "Failed to get log level: %s", bus_error_message(&error
, r
));
6336 r
= sd_bus_set_property(
6338 "org.freedesktop.systemd1",
6339 "/org/freedesktop/systemd1",
6340 "org.freedesktop.systemd1.Manager",
6346 return log_error_errno(r
, "Failed to set log level: %s", bus_error_message(&error
, r
));
6352 static int log_target(int argc
, char *argv
[], void *userdata
) {
6354 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6357 r
= acquire_bus(BUS_MANAGER
, &bus
);
6362 _cleanup_free_
char *target
= NULL
;
6364 r
= sd_bus_get_property_string(
6366 "org.freedesktop.systemd1",
6367 "/org/freedesktop/systemd1",
6368 "org.freedesktop.systemd1.Manager",
6373 return log_error_errno(r
, "Failed to get log target: %s", bus_error_message(&error
, r
));
6380 r
= sd_bus_set_property(
6382 "org.freedesktop.systemd1",
6383 "/org/freedesktop/systemd1",
6384 "org.freedesktop.systemd1.Manager",
6390 return log_error_errno(r
, "Failed to set log target: %s", bus_error_message(&error
, r
));
6396 static int service_watchdogs(int argc
, char *argv
[], void *userdata
) {
6398 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6403 r
= acquire_bus(BUS_MANAGER
, &bus
);
6408 /* get ServiceWatchdogs */
6409 r
= sd_bus_get_property_trivial(
6411 "org.freedesktop.systemd1",
6412 "/org/freedesktop/systemd1",
6413 "org.freedesktop.systemd1.Manager",
6419 return log_error_errno(r
, "Failed to get service-watchdog state: %s", bus_error_message(&error
, r
));
6421 printf("%s\n", yes_no(!!b
));
6424 /* set ServiceWatchdogs */
6427 b
= parse_boolean(argv
[1]);
6429 return log_error_errno(b
, "Failed to parse service-watchdogs argument: %m");
6431 r
= sd_bus_set_property(
6433 "org.freedesktop.systemd1",
6434 "/org/freedesktop/systemd1",
6435 "org.freedesktop.systemd1.Manager",
6441 return log_error_errno(r
, "Failed to set service-watchdog state: %s", bus_error_message(&error
, r
));
6447 static int set_environment(int argc
, char *argv
[], void *userdata
) {
6448 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6449 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6457 r
= acquire_bus(BUS_MANAGER
, &bus
);
6461 polkit_agent_open_maybe();
6463 method
= streq(argv
[0], "set-environment")
6465 : "UnsetEnvironment";
6467 r
= sd_bus_message_new_method_call(
6470 "org.freedesktop.systemd1",
6471 "/org/freedesktop/systemd1",
6472 "org.freedesktop.systemd1.Manager",
6475 return bus_log_create_error(r
);
6477 r
= sd_bus_message_append_strv(m
, strv_skip(argv
, 1));
6479 return bus_log_create_error(r
);
6481 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6483 return log_error_errno(r
, "Failed to set environment: %s", bus_error_message(&error
, r
));
6488 static int import_environment(int argc
, char *argv
[], void *userdata
) {
6489 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6490 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6494 r
= acquire_bus(BUS_MANAGER
, &bus
);
6498 polkit_agent_open_maybe();
6500 r
= sd_bus_message_new_method_call(
6503 "org.freedesktop.systemd1",
6504 "/org/freedesktop/systemd1",
6505 "org.freedesktop.systemd1.Manager",
6508 return bus_log_create_error(r
);
6511 r
= sd_bus_message_append_strv(m
, environ
);
6515 r
= sd_bus_message_open_container(m
, 'a', "s");
6517 return bus_log_create_error(r
);
6519 STRV_FOREACH(a
, strv_skip(argv
, 1)) {
6521 if (!env_name_is_valid(*a
))
6522 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Not a valid environment variable name: %s", *a
);
6524 STRV_FOREACH(b
, environ
) {
6527 eq
= startswith(*b
, *a
);
6528 if (eq
&& *eq
== '=') {
6530 r
= sd_bus_message_append(m
, "s", *b
);
6532 return bus_log_create_error(r
);
6539 r
= sd_bus_message_close_container(m
);
6542 return bus_log_create_error(r
);
6544 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6546 return log_error_errno(r
, "Failed to import environment: %s", bus_error_message(&error
, r
));
6551 static int enable_sysv_units(const char *verb
, char **args
) {
6554 #if HAVE_SYSV_COMPAT
6555 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
6558 /* Processes all SysV units, and reshuffles the array so that afterwards only the native units remain */
6560 if (arg_scope
!= UNIT_FILE_SYSTEM
)
6563 if (getenv_bool("SYSTEMCTL_SKIP_SYSV") > 0)
6566 if (!STR_IN_SET(verb
,
6572 r
= lookup_paths_init(&paths
, arg_scope
, LOOKUP_PATHS_EXCLUDE_GENERATED
, arg_root
);
6579 const char *argv
[] = {
6580 ROOTLIBEXECDIR
"/systemd-sysv-install",
6587 _cleanup_free_
char *p
= NULL
, *q
= NULL
, *l
= NULL
, *v
= NULL
;
6588 bool found_native
= false, found_sysv
;
6596 if (!endswith(name
, ".service"))
6599 if (path_is_absolute(name
))
6602 j
= unit_file_exists(arg_scope
, &paths
, name
);
6603 if (j
< 0 && !IN_SET(j
, -ELOOP
, -ERFKILL
, -EADDRNOTAVAIL
))
6604 return log_error_errno(j
, "Failed to look up unit file state: %m");
6605 found_native
= j
!= 0;
6607 /* If we have both a native unit and a SysV script, enable/disable them both (below); for is-enabled,
6608 * prefer the native unit */
6609 if (found_native
&& streq(verb
, "is-enabled"))
6612 p
= path_join(arg_root
, SYSTEM_SYSVINIT_PATH
, name
);
6616 p
[strlen(p
) - STRLEN(".service")] = 0;
6617 found_sysv
= access(p
, F_OK
) >= 0;
6623 log_info("Synchronizing state of %s with SysV service script with %s.", name
, argv
[0]);
6625 log_info("%s is not a native service, redirecting to systemd-sysv-install.", name
);
6628 if (!isempty(arg_root
)) {
6629 q
= strjoin("--root=", arg_root
);
6636 /* Let's copy the verb, since it's still pointing directly into the original argv[] array we
6637 * got passed, but safe_fork() is likely going to rewrite that for the new child */
6643 argv
[c
++] = basename(p
);
6646 l
= strv_join((char**)argv
, " ");
6651 log_info("Executing: %s", l
);
6653 j
= safe_fork("(sysv-install)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
, &pid
);
6658 execv(argv
[0], (char**) argv
);
6659 log_error_errno(errno
, "Failed to execute %s: %m", argv
[0]);
6660 _exit(EXIT_FAILURE
);
6663 j
= wait_for_terminate_and_check("sysv-install", pid
, WAIT_LOG_ABNORMAL
);
6666 if (streq(verb
, "is-enabled")) {
6667 if (j
== EXIT_SUCCESS
) {
6676 } else if (j
!= EXIT_SUCCESS
)
6677 return -EBADE
; /* We don't warn here, under the assumption the script already showed an explanation */
6682 /* Remove this entry, so that we don't try enabling it as native unit */
6685 assert(args
[f
] == name
);
6686 strv_remove(args
+ f
, name
);
6693 static int mangle_names(const char *operation
, char **original_names
, char ***mangled_names
) {
6694 char **i
, **l
, **name
;
6697 l
= i
= new(char*, strv_length(original_names
) + 1);
6701 STRV_FOREACH(name
, original_names
) {
6703 /* When enabling units qualified path names are OK,
6704 * too, hence allow them explicitly. */
6706 if (is_path(*name
)) {
6713 r
= unit_name_mangle_with_suffix(*name
, operation
,
6714 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
6719 return log_error_errno(r
, "Failed to mangle unit name: %m");
6732 static int normalize_filenames(char **names
) {
6736 STRV_FOREACH(u
, names
)
6737 if (!path_is_absolute(*u
)) {
6738 char* normalized_path
;
6740 if (!isempty(arg_root
))
6741 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6742 "Non-absolute paths are not allowed when --root is used: %s",
6745 if (!strchr(*u
,'/'))
6746 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6747 "Link argument does contain at least one directory separator: %s",
6750 r
= path_make_absolute_cwd(*u
, &normalized_path
);
6754 free_and_replace(*u
, normalized_path
);
6760 static int normalize_names(char **names
, bool warn_if_path
) {
6762 bool was_path
= false;
6764 STRV_FOREACH(u
, names
) {
6770 r
= free_and_strdup(u
, basename(*u
));
6772 return log_error_errno(r
, "Failed to normalize unit file path: %m");
6777 if (warn_if_path
&& was_path
)
6778 log_warning("Warning: Can't execute disable on the unit file path. Proceeding with the unit name.");
6783 static int unit_exists(LookupPaths
*lp
, const char *unit
) {
6784 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6785 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6786 _cleanup_free_
char *path
= NULL
;
6787 static const struct bus_properties_map property_map
[] = {
6788 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
6789 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
)},
6792 UnitStatusInfo info
= {};
6796 if (unit_name_is_valid(unit
, UNIT_NAME_TEMPLATE
))
6797 return unit_find_template_path(unit
, lp
, NULL
, NULL
);
6799 path
= unit_dbus_path_from_name(unit
);
6803 r
= acquire_bus(BUS_MANAGER
, &bus
);
6807 r
= bus_map_all_properties(bus
, "org.freedesktop.systemd1", path
, property_map
, 0, &error
, &m
, &info
);
6809 return log_error_errno(r
, "Failed to get properties: %s", bus_error_message(&error
, r
));
6811 return !streq_ptr(info
.load_state
, "not-found") || !streq_ptr(info
.active_state
, "inactive");
6814 static int enable_unit(int argc
, char *argv
[], void *userdata
) {
6815 _cleanup_strv_free_
char **names
= NULL
;
6816 const char *verb
= argv
[0];
6817 UnitFileChange
*changes
= NULL
;
6818 size_t n_changes
= 0;
6819 int carries_install_info
= -1;
6820 bool ignore_carries_install_info
= arg_quiet
;
6826 r
= mangle_names("to enable", strv_skip(argv
, 1), &names
);
6830 r
= enable_sysv_units(verb
, names
);
6834 /* If the operation was fully executed by the SysV compat, let's finish early */
6835 if (strv_isempty(names
)) {
6836 if (arg_no_reload
|| install_client_side())
6838 return daemon_reload(argc
, argv
, userdata
);
6841 if (streq(verb
, "disable")) {
6842 r
= normalize_names(names
, true);
6847 if (streq(verb
, "link")) {
6848 r
= normalize_filenames(names
);
6853 if (install_client_side()) {
6854 UnitFileFlags flags
;
6856 flags
= args_to_flags();
6857 if (streq(verb
, "enable")) {
6858 r
= unit_file_enable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6859 carries_install_info
= r
;
6860 } else if (streq(verb
, "disable"))
6861 r
= unit_file_disable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6862 else if (streq(verb
, "reenable")) {
6863 r
= unit_file_reenable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6864 carries_install_info
= r
;
6865 } else if (streq(verb
, "link"))
6866 r
= unit_file_link(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6867 else if (streq(verb
, "preset")) {
6868 r
= unit_file_preset(arg_scope
, flags
, arg_root
, names
, arg_preset_mode
, &changes
, &n_changes
);
6869 } else if (streq(verb
, "mask"))
6870 r
= unit_file_mask(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6871 else if (streq(verb
, "unmask"))
6872 r
= unit_file_unmask(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6873 else if (streq(verb
, "revert"))
6874 r
= unit_file_revert(arg_scope
, arg_root
, names
, &changes
, &n_changes
);
6876 assert_not_reached("Unknown verb");
6878 unit_file_dump_changes(r
, verb
, changes
, n_changes
, arg_quiet
);
6883 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
, *m
= NULL
;
6884 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6885 bool expect_carries_install_info
= false;
6886 bool send_runtime
= true, send_force
= true, send_preset_mode
= false;
6890 if (STR_IN_SET(verb
, "mask", "unmask")) {
6892 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
6894 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
6898 STRV_FOREACH(name
, names
) {
6899 r
= unit_exists(&lp
, *name
);
6903 log_notice("Unit %s does not exist, proceeding anyway.", *name
);
6907 r
= acquire_bus(BUS_MANAGER
, &bus
);
6911 polkit_agent_open_maybe();
6913 if (streq(verb
, "enable")) {
6914 method
= "EnableUnitFiles";
6915 expect_carries_install_info
= true;
6916 } else if (streq(verb
, "disable")) {
6917 method
= "DisableUnitFiles";
6919 } else if (streq(verb
, "reenable")) {
6920 method
= "ReenableUnitFiles";
6921 expect_carries_install_info
= true;
6922 } else if (streq(verb
, "link"))
6923 method
= "LinkUnitFiles";
6924 else if (streq(verb
, "preset")) {
6926 if (arg_preset_mode
!= UNIT_FILE_PRESET_FULL
) {
6927 method
= "PresetUnitFilesWithMode";
6928 send_preset_mode
= true;
6930 method
= "PresetUnitFiles";
6932 expect_carries_install_info
= true;
6933 ignore_carries_install_info
= true;
6934 } else if (streq(verb
, "mask"))
6935 method
= "MaskUnitFiles";
6936 else if (streq(verb
, "unmask")) {
6937 method
= "UnmaskUnitFiles";
6939 } else if (streq(verb
, "revert")) {
6940 method
= "RevertUnitFiles";
6941 send_runtime
= send_force
= false;
6943 assert_not_reached("Unknown verb");
6945 r
= sd_bus_message_new_method_call(
6948 "org.freedesktop.systemd1",
6949 "/org/freedesktop/systemd1",
6950 "org.freedesktop.systemd1.Manager",
6953 return bus_log_create_error(r
);
6955 r
= sd_bus_message_append_strv(m
, names
);
6957 return bus_log_create_error(r
);
6959 if (send_preset_mode
) {
6960 r
= sd_bus_message_append(m
, "s", unit_file_preset_mode_to_string(arg_preset_mode
));
6962 return bus_log_create_error(r
);
6966 r
= sd_bus_message_append(m
, "b", arg_runtime
);
6968 return bus_log_create_error(r
);
6972 r
= sd_bus_message_append(m
, "b", arg_force
);
6974 return bus_log_create_error(r
);
6977 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
6979 return log_error_errno(r
, "Failed to %s unit: %s", verb
, bus_error_message(&error
, r
));
6981 if (expect_carries_install_info
) {
6982 r
= sd_bus_message_read(reply
, "b", &carries_install_info
);
6984 return bus_log_parse_error(r
);
6987 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
6991 /* Try to reload if enabled */
6993 r
= daemon_reload(argc
, argv
, userdata
);
6998 if (carries_install_info
== 0 && !ignore_carries_install_info
)
6999 log_notice("The unit files have no installation config (WantedBy=, RequiredBy=, Also=,\n"
7000 "Alias= settings in the [Install] section, and DefaultInstance= for template\n"
7001 "units). This means they are not meant to be enabled using systemctl.\n"
7002 " \n" /* trick: the space is needed so that the line does not get stripped from output */
7003 "Possible reasons for having this kind of units are:\n"
7004 "%1$s A unit may be statically enabled by being symlinked from another unit's\n"
7005 " .wants/ or .requires/ directory.\n"
7006 "%1$s A unit's purpose may be to act as a helper for some other unit which has\n"
7007 " a requirement dependency on it.\n"
7008 "%1$s A unit may be started when needed via activation (socket, path, timer,\n"
7009 " D-Bus, udev, scripted systemctl call, ...).\n"
7010 "%1$s In case of template units, the unit is meant to be enabled with some\n"
7011 " instance name specified.",
7012 special_glyph(SPECIAL_GLYPH_BULLET
));
7014 if (arg_now
&& STR_IN_SET(argv
[0], "enable", "disable", "mask")) {
7018 r
= acquire_bus(BUS_MANAGER
, &bus
);
7022 len
= strv_length(names
);
7024 char *new_args
[len
+ 2];
7026 new_args
[0] = (char*) (streq(argv
[0], "enable") ? "start" : "stop");
7027 for (i
= 0; i
< len
; i
++)
7028 new_args
[i
+ 1] = basename(names
[i
]);
7029 new_args
[i
+ 1] = NULL
;
7031 r
= start_unit(len
+ 1, new_args
, userdata
);
7036 unit_file_changes_free(changes
, n_changes
);
7041 static int add_dependency(int argc
, char *argv
[], void *userdata
) {
7042 _cleanup_strv_free_
char **names
= NULL
;
7043 _cleanup_free_
char *target
= NULL
;
7044 const char *verb
= argv
[0];
7045 UnitFileChange
*changes
= NULL
;
7046 size_t n_changes
= 0;
7053 r
= unit_name_mangle_with_suffix(argv
[1], "as target",
7054 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
7055 ".target", &target
);
7057 return log_error_errno(r
, "Failed to mangle unit name: %m");
7059 r
= mangle_names("as dependency", strv_skip(argv
, 2), &names
);
7063 if (streq(verb
, "add-wants"))
7065 else if (streq(verb
, "add-requires"))
7066 dep
= UNIT_REQUIRES
;
7068 assert_not_reached("Unknown verb");
7070 if (install_client_side()) {
7071 r
= unit_file_add_dependency(arg_scope
, args_to_flags(), arg_root
, names
, target
, dep
, &changes
, &n_changes
);
7072 unit_file_dump_changes(r
, "add dependency on", changes
, n_changes
, arg_quiet
);
7077 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
, *m
= NULL
;
7078 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7081 r
= acquire_bus(BUS_MANAGER
, &bus
);
7085 polkit_agent_open_maybe();
7087 r
= sd_bus_message_new_method_call(
7090 "org.freedesktop.systemd1",
7091 "/org/freedesktop/systemd1",
7092 "org.freedesktop.systemd1.Manager",
7093 "AddDependencyUnitFiles");
7095 return bus_log_create_error(r
);
7097 r
= sd_bus_message_append_strv(m
, names
);
7099 return bus_log_create_error(r
);
7101 r
= sd_bus_message_append(m
, "ssbb", target
, unit_dependency_to_string(dep
), arg_runtime
, arg_force
);
7103 return bus_log_create_error(r
);
7105 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
7107 return log_error_errno(r
, "Failed to add dependency: %s", bus_error_message(&error
, r
));
7109 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
7113 if (arg_no_reload
) {
7118 r
= daemon_reload(argc
, argv
, userdata
);
7122 unit_file_changes_free(changes
, n_changes
);
7127 static int preset_all(int argc
, char *argv
[], void *userdata
) {
7128 UnitFileChange
*changes
= NULL
;
7129 size_t n_changes
= 0;
7132 if (install_client_side()) {
7133 r
= unit_file_preset_all(arg_scope
, args_to_flags(), arg_root
, arg_preset_mode
, &changes
, &n_changes
);
7134 unit_file_dump_changes(r
, "preset", changes
, n_changes
, arg_quiet
);
7139 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7140 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7143 r
= acquire_bus(BUS_MANAGER
, &bus
);
7147 polkit_agent_open_maybe();
7149 r
= sd_bus_call_method(
7151 "org.freedesktop.systemd1",
7152 "/org/freedesktop/systemd1",
7153 "org.freedesktop.systemd1.Manager",
7154 "PresetAllUnitFiles",
7158 unit_file_preset_mode_to_string(arg_preset_mode
),
7162 return log_error_errno(r
, "Failed to preset all units: %s", bus_error_message(&error
, r
));
7164 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
7168 if (arg_no_reload
) {
7173 r
= daemon_reload(argc
, argv
, userdata
);
7177 unit_file_changes_free(changes
, n_changes
);
7182 static int show_installation_targets_client_side(const char *name
) {
7183 UnitFileChange
*changes
= NULL
;
7184 size_t n_changes
= 0, i
;
7185 UnitFileFlags flags
;
7189 p
= STRV_MAKE(name
);
7190 flags
= UNIT_FILE_DRY_RUN
|
7191 (arg_runtime
? UNIT_FILE_RUNTIME
: 0);
7193 r
= unit_file_disable(UNIT_FILE_SYSTEM
, flags
, NULL
, p
, &changes
, &n_changes
);
7195 return log_error_errno(r
, "Failed to get file links for %s: %m", name
);
7197 for (i
= 0; i
< n_changes
; i
++)
7198 if (changes
[i
].type
== UNIT_FILE_UNLINK
)
7199 printf(" %s\n", changes
[i
].path
);
7204 static int show_installation_targets(sd_bus
*bus
, const char *name
) {
7205 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7206 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7210 r
= sd_bus_call_method(
7212 "org.freedesktop.systemd1",
7213 "/org/freedesktop/systemd1",
7214 "org.freedesktop.systemd1.Manager",
7218 "sb", name
, arg_runtime
);
7220 return log_error_errno(r
, "Failed to get unit file links for %s: %s", name
, bus_error_message(&error
, r
));
7222 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "s");
7224 return bus_log_parse_error(r
);
7226 while ((r
= sd_bus_message_read(reply
, "s", &link
)) > 0)
7227 printf(" %s\n", link
);
7230 return bus_log_parse_error(r
);
7232 r
= sd_bus_message_exit_container(reply
);
7234 return bus_log_parse_error(r
);
7239 static int unit_is_enabled(int argc
, char *argv
[], void *userdata
) {
7240 _cleanup_strv_free_
char **names
= NULL
;
7245 r
= mangle_names("to check", strv_skip(argv
, 1), &names
);
7249 r
= enable_sysv_units(argv
[0], names
);
7255 if (install_client_side()) {
7256 STRV_FOREACH(name
, names
) {
7257 UnitFileState state
;
7259 r
= unit_file_get_state(arg_scope
, arg_root
, *name
, &state
);
7261 return log_error_errno(r
, "Failed to get unit file state for %s: %m", *name
);
7265 UNIT_FILE_ENABLED_RUNTIME
,
7268 UNIT_FILE_GENERATED
))
7272 puts(unit_file_state_to_string(state
));
7274 r
= show_installation_targets_client_side(*name
);
7283 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7286 r
= acquire_bus(BUS_MANAGER
, &bus
);
7290 STRV_FOREACH(name
, names
) {
7291 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7294 r
= sd_bus_call_method(
7296 "org.freedesktop.systemd1",
7297 "/org/freedesktop/systemd1",
7298 "org.freedesktop.systemd1.Manager",
7304 return log_error_errno(r
, "Failed to get unit file state for %s: %s", *name
, bus_error_message(&error
, r
));
7306 r
= sd_bus_message_read(reply
, "s", &s
);
7308 return bus_log_parse_error(r
);
7310 if (STR_IN_SET(s
, "enabled", "enabled-runtime", "static", "indirect", "generated"))
7316 r
= show_installation_targets(bus
, *name
);
7324 return enabled
? EXIT_SUCCESS
: EXIT_FAILURE
;
7327 static int match_startup_finished(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
7328 char **state
= userdata
;
7333 r
= sd_bus_get_property_string(
7334 sd_bus_message_get_bus(m
),
7335 "org.freedesktop.systemd1",
7336 "/org/freedesktop/systemd1",
7337 "org.freedesktop.systemd1.Manager",
7342 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m
)), r
);
7346 static int is_system_running(int argc
, char *argv
[], void *userdata
) {
7347 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7348 _cleanup_(sd_bus_slot_unrefp
) sd_bus_slot
*slot_startup_finished
= NULL
;
7349 _cleanup_(sd_event_unrefp
) sd_event
* event
= NULL
;
7350 _cleanup_free_
char *state
= NULL
;
7354 if (running_in_chroot() > 0 || (arg_transport
== BUS_TRANSPORT_LOCAL
&& !sd_booted())) {
7357 return EXIT_FAILURE
;
7360 r
= acquire_bus(BUS_MANAGER
, &bus
);
7365 r
= sd_event_default(&event
);
7367 r
= sd_bus_attach_event(bus
, event
, 0);
7369 r
= sd_bus_match_signal_async(
7371 &slot_startup_finished
,
7372 "org.freedesktop.systemd1",
7373 "/org/freedesktop/systemd1",
7374 "org.freedesktop.systemd1.Manager",
7376 match_startup_finished
, NULL
, &state
);
7378 log_warning_errno(r
, "Failed to request match for StartupFinished: %m");
7383 r
= sd_bus_get_property_string(
7385 "org.freedesktop.systemd1",
7386 "/org/freedesktop/systemd1",
7387 "org.freedesktop.systemd1.Manager",
7392 log_warning_errno(r
, "Failed to query system state: %s", bus_error_message(&error
, r
));
7396 return EXIT_FAILURE
;
7399 if (arg_wait
&& STR_IN_SET(state
, "initializing", "starting")) {
7400 r
= sd_event_loop(event
);
7402 log_warning_errno(r
, "Failed to get property from event loop: %m");
7405 return EXIT_FAILURE
;
7412 return streq(state
, "running") ? EXIT_SUCCESS
: EXIT_FAILURE
;
7415 static int create_edit_temp_file(const char *new_path
, const char *original_path
, char **ret_tmp_fn
) {
7416 _cleanup_free_
char *t
= NULL
;
7420 assert(original_path
);
7423 r
= tempfn_random(new_path
, NULL
, &t
);
7425 return log_error_errno(r
, "Failed to determine temporary filename for \"%s\": %m", new_path
);
7427 r
= mkdir_parents(new_path
, 0755);
7429 return log_error_errno(r
, "Failed to create directories for \"%s\": %m", new_path
);
7431 r
= copy_file(original_path
, t
, 0, 0644, 0, 0, COPY_REFLINK
);
7436 return log_error_errno(r
, "Failed to create temporary file \"%s\": %m", t
);
7439 return log_error_errno(r
, "Failed to create temporary file for \"%s\": %m", new_path
);
7441 *ret_tmp_fn
= TAKE_PTR(t
);
7446 static int get_file_to_edit(
7447 const LookupPaths
*paths
,
7451 _cleanup_free_
char *path
= NULL
, *run
= NULL
;
7456 path
= path_join(paths
->persistent_config
, name
);
7461 run
= path_join(paths
->runtime_config
, name
);
7467 if (access(path
, F_OK
) >= 0)
7468 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
7469 "Refusing to create \"%s\" because it would be overridden by \"%s\" anyway.",
7472 *ret_path
= TAKE_PTR(run
);
7474 *ret_path
= TAKE_PTR(path
);
7479 static int unit_file_create_new(
7480 const LookupPaths
*paths
,
7481 const char *unit_name
,
7483 char **ret_new_path
,
7484 char **ret_tmp_path
) {
7486 _cleanup_free_
char *new_path
= NULL
, *tmp_path
= NULL
;
7491 assert(ret_new_path
);
7492 assert(ret_tmp_path
);
7494 ending
= strjoina(unit_name
, suffix
);
7495 r
= get_file_to_edit(paths
, ending
, &new_path
);
7499 r
= create_edit_temp_file(new_path
, new_path
, &tmp_path
);
7503 *ret_new_path
= TAKE_PTR(new_path
);
7504 *ret_tmp_path
= TAKE_PTR(tmp_path
);
7509 static int unit_file_create_copy(
7510 const LookupPaths
*paths
,
7511 const char *unit_name
,
7512 const char *fragment_path
,
7513 char **ret_new_path
,
7514 char **ret_tmp_path
) {
7516 _cleanup_free_
char *new_path
= NULL
, *tmp_path
= NULL
;
7519 assert(fragment_path
);
7521 assert(ret_new_path
);
7522 assert(ret_tmp_path
);
7524 r
= get_file_to_edit(paths
, unit_name
, &new_path
);
7528 if (!path_equal(fragment_path
, new_path
) && access(new_path
, F_OK
) >= 0) {
7531 r
= ask_char(&response
, "yn", "\"%s\" already exists. Overwrite with \"%s\"? [(y)es, (n)o] ", new_path
, fragment_path
);
7534 if (response
!= 'y')
7535 return log_warning_errno(SYNTHETIC_ERRNO(EKEYREJECTED
), "%s skipped.", unit_name
);
7538 r
= create_edit_temp_file(new_path
, fragment_path
, &tmp_path
);
7542 *ret_new_path
= TAKE_PTR(new_path
);
7543 *ret_tmp_path
= TAKE_PTR(tmp_path
);
7548 static int run_editor(char **paths
) {
7553 r
= safe_fork("(editor)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
|FORK_WAIT
, NULL
);
7557 char **editor_args
= NULL
, **tmp_path
, **original_path
;
7558 size_t n_editor_args
= 0, i
= 1, argc
;
7559 const char **args
, *editor
, *p
;
7561 argc
= strv_length(paths
)/2 + 1;
7563 /* SYSTEMD_EDITOR takes precedence over EDITOR which takes precedence over VISUAL
7564 * If neither SYSTEMD_EDITOR nor EDITOR nor VISUAL are present,
7565 * we try to execute well known editors
7567 editor
= getenv("SYSTEMD_EDITOR");
7569 editor
= getenv("EDITOR");
7571 editor
= getenv("VISUAL");
7573 if (!isempty(editor
)) {
7574 editor_args
= strv_split(editor
, WHITESPACE
);
7577 _exit(EXIT_FAILURE
);
7579 n_editor_args
= strv_length(editor_args
);
7580 argc
+= n_editor_args
- 1;
7583 args
= newa(const char*, argc
+ 1);
7585 if (n_editor_args
> 0) {
7586 args
[0] = editor_args
[0];
7587 for (; i
< n_editor_args
; i
++)
7588 args
[i
] = editor_args
[i
];
7591 STRV_FOREACH_PAIR(original_path
, tmp_path
, paths
)
7592 args
[i
++] = *tmp_path
;
7595 if (n_editor_args
> 0)
7596 execvp(args
[0], (char* const*) args
);
7598 FOREACH_STRING(p
, "editor", "nano", "vim", "vi") {
7600 execvp(p
, (char* const*) args
);
7601 /* We do not fail if the editor doesn't exist
7602 * because we want to try each one of them before
7605 if (errno
!= ENOENT
) {
7606 log_error_errno(errno
, "Failed to execute %s: %m", editor
);
7607 _exit(EXIT_FAILURE
);
7611 log_error("Cannot edit unit(s), no editor available. Please set either $SYSTEMD_EDITOR, $EDITOR or $VISUAL.");
7612 _exit(EXIT_FAILURE
);
7618 static int find_paths_to_edit(sd_bus
*bus
, char **names
, char ***paths
) {
7619 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
7626 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
7630 STRV_FOREACH(name
, names
) {
7631 _cleanup_free_
char *path
= NULL
, *new_path
= NULL
, *tmp_path
= NULL
, *tmp_name
= NULL
;
7632 const char *unit_name
;
7634 r
= unit_find_paths(bus
, *name
, &lp
, false, &path
, NULL
);
7635 if (r
== -EKEYREJECTED
) {
7636 /* If loading of the unit failed server side complete, then the server won't tell us the unit
7637 * file path. In that case, find the file client side. */
7638 log_debug_errno(r
, "Unit '%s' was not loaded correctly, retrying client-side.", *name
);
7639 r
= unit_find_paths(bus
, *name
, &lp
, true, &path
, NULL
);
7642 return log_error_errno(r
, "Unit '%s' masked, cannot edit.", *name
);
7650 log_info("Run 'systemctl edit%s --force --full %s' to create a new unit.",
7651 arg_scope
== UNIT_FILE_GLOBAL
? " --global" :
7652 arg_scope
== UNIT_FILE_USER
? " --user" : "",
7657 /* Create a new unit from scratch */
7659 r
= unit_file_create_new(&lp
, unit_name
,
7660 arg_full
? NULL
: ".d/override.conf",
7661 &new_path
, &tmp_path
);
7665 unit_name
= basename(path
);
7666 /* We follow unit aliases, but we need to propagate the instance */
7667 if (unit_name_is_valid(*name
, UNIT_NAME_INSTANCE
) &&
7668 unit_name_is_valid(unit_name
, UNIT_NAME_TEMPLATE
)) {
7669 _cleanup_free_
char *instance
= NULL
;
7671 r
= unit_name_to_instance(*name
, &instance
);
7675 r
= unit_name_replace_instance(unit_name
, instance
, &tmp_name
);
7679 unit_name
= tmp_name
;
7683 r
= unit_file_create_copy(&lp
, unit_name
, path
, &new_path
, &tmp_path
);
7685 r
= unit_file_create_new(&lp
, unit_name
, ".d/override.conf", &new_path
, &tmp_path
);
7690 r
= strv_push_pair(paths
, new_path
, tmp_path
);
7694 new_path
= tmp_path
= NULL
;
7700 static int edit(int argc
, char *argv
[], void *userdata
) {
7701 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
7702 _cleanup_strv_free_
char **names
= NULL
;
7703 _cleanup_strv_free_
char **paths
= NULL
;
7704 char **original
, **tmp
;
7709 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit units if not on a tty.");
7711 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
7712 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit units remotely.");
7714 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
7716 return log_error_errno(r
, "Failed to determine unit paths: %m");
7718 r
= acquire_bus(BUS_MANAGER
, &bus
);
7722 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
7724 return log_error_errno(r
, "Failed to expand names: %m");
7726 STRV_FOREACH(tmp
, names
) {
7727 r
= unit_is_masked(bus
, &lp
, *tmp
);
7731 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit %s: unit is masked.", *tmp
);
7734 r
= find_paths_to_edit(bus
, names
, &paths
);
7738 if (strv_isempty(paths
))
7741 r
= run_editor(paths
);
7745 STRV_FOREACH_PAIR(original
, tmp
, paths
) {
7746 /* If the temporary file is empty we ignore it.
7747 * This allows the user to cancel the modification.
7749 if (null_or_empty_path(*tmp
)) {
7750 log_warning("Editing \"%s\" canceled: temporary file is empty.", *original
);
7754 r
= rename(*tmp
, *original
);
7756 r
= log_error_errno(errno
, "Failed to rename \"%s\" to \"%s\": %m", *tmp
, *original
);
7763 if (!arg_no_reload
&& !install_client_side())
7764 r
= daemon_reload(argc
, argv
, userdata
);
7767 STRV_FOREACH_PAIR(original
, tmp
, paths
) {
7768 (void) unlink(*tmp
);
7770 /* Removing empty dropin dirs */
7772 _cleanup_free_
char *dir
;
7774 dir
= dirname_malloc(*original
);
7778 /* no need to check if the dir is empty, rmdir
7779 * does nothing if it is not the case.
7788 static int systemctl_help(void) {
7789 _cleanup_free_
char *link
= NULL
;
7792 (void) pager_open(arg_pager_flags
);
7794 r
= terminal_urlify_man("systemctl", "1", &link
);
7798 printf("%1$s [OPTIONS...] COMMAND ...\n\n"
7799 "%5$sQuery or send control commands to the system manager.%6$s\n"
7800 "\n%3$sUnit Commands:%4$s\n"
7801 " list-units [PATTERN...] List units currently in memory\n"
7802 " list-sockets [PATTERN...] List socket units currently in memory,\n"
7803 " ordered by address\n"
7804 " list-timers [PATTERN...] List timer units currently in memory,\n"
7805 " ordered by next elapse\n"
7806 " start UNIT... Start (activate) one or more units\n"
7807 " stop UNIT... Stop (deactivate) one or more units\n"
7808 " reload UNIT... Reload one or more units\n"
7809 " restart UNIT... Start or restart one or more units\n"
7810 " try-restart UNIT... Restart one or more units if active\n"
7811 " reload-or-restart UNIT... Reload one or more units if possible,\n"
7812 " otherwise start or restart\n"
7813 " try-reload-or-restart UNIT... If active, reload one or more units,\n"
7814 " if supported, otherwise restart\n"
7815 " isolate UNIT Start one unit and stop all others\n"
7816 " kill UNIT... Send signal to processes of a unit\n"
7817 " clean UNIT... Clean runtime, cache, state, logs or\n"
7818 " configuration of unit\n"
7819 " is-active PATTERN... Check whether units are active\n"
7820 " is-failed PATTERN... Check whether units are failed\n"
7821 " status [PATTERN...|PID...] Show runtime status of one or more units\n"
7822 " show [PATTERN...|JOB...] Show properties of one or more\n"
7823 " units/jobs or the manager\n"
7824 " cat PATTERN... Show files and drop-ins of specified units\n"
7825 " set-property UNIT PROPERTY=VALUE... Sets one or more properties of a unit\n"
7826 " help PATTERN...|PID... Show manual for one or more units\n"
7827 " reset-failed [PATTERN...] Reset failed state for all, one, or more\n"
7829 " list-dependencies [UNIT...] Recursively show units which are required\n"
7830 " or wanted by the units or by which those\n"
7831 " units are required or wanted"
7832 "\n%3$sUnit File Commands:%4$s\n"
7833 " list-unit-files [PATTERN...] List installed unit files\n"
7834 " enable [UNIT...|PATH...] Enable one or more unit files\n"
7835 " disable UNIT... Disable one or more unit files\n"
7836 " reenable UNIT... Reenable one or more unit files\n"
7837 " preset UNIT... Enable/disable one or more unit files\n"
7838 " based on preset configuration\n"
7839 " preset-all Enable/disable all unit files based on\n"
7840 " preset configuration\n"
7841 " is-enabled UNIT... Check whether unit files are enabled\n"
7842 " mask UNIT... Mask one or more units\n"
7843 " unmask UNIT... Unmask one or more units\n"
7844 " link PATH... Link one or more units files into\n"
7845 " the search path\n"
7846 " revert UNIT... Revert one or more unit files to vendor\n"
7848 " add-wants TARGET UNIT... Add 'Wants' dependency for the target\n"
7849 " on specified one or more units\n"
7850 " add-requires TARGET UNIT... Add 'Requires' dependency for the target\n"
7851 " on specified one or more units\n"
7852 " edit UNIT... Edit one or more unit files\n"
7853 " get-default Get the name of the default target\n"
7854 " set-default TARGET Set the default target\n"
7855 "\n%3$sMachine Commands:%4$s\n"
7856 " list-machines [PATTERN...] List local containers and host\n"
7857 "\n%3$sJob Commands:%4$s\n"
7858 " list-jobs [PATTERN...] List jobs\n"
7859 " cancel [JOB...] Cancel all, one, or more jobs\n"
7860 "\n%3$sEnvironment Commands:%4$s\n"
7861 " show-environment Dump environment\n"
7862 " set-environment VARIABLE=VALUE... Set one or more environment variables\n"
7863 " unset-environment VARIABLE... Unset one or more environment variables\n"
7864 " import-environment [VARIABLE...] Import all or some environment variables\n"
7865 "\n%3$sManager State Commands:%4$s\n"
7866 " daemon-reload Reload systemd manager configuration\n"
7867 " daemon-reexec Reexecute systemd manager\n"
7868 " log-level [LEVEL] Get/set logging threshold for manager\n"
7869 " log-target [TARGET] Get/set logging target for manager\n"
7870 " service-watchdogs [BOOL] Get/set service watchdog state\n"
7871 "\n%3$sSystem Commands:%4$s\n"
7872 " is-system-running Check whether system is fully running\n"
7873 " default Enter system default mode\n"
7874 " rescue Enter system rescue mode\n"
7875 " emergency Enter system emergency mode\n"
7876 " halt Shut down and halt the system\n"
7877 " poweroff Shut down and power-off the system\n"
7878 " reboot [ARG] Shut down and reboot the system\n"
7879 " kexec Shut down and reboot the system with kexec\n"
7880 " exit [EXIT_CODE] Request user instance or container exit\n"
7881 " switch-root ROOT [INIT] Change to a different root file system\n"
7882 " suspend Suspend the system\n"
7883 " hibernate Hibernate the system\n"
7884 " hybrid-sleep Hibernate and suspend the system\n"
7885 " suspend-then-hibernate Suspend the system, wake after a period of\n"
7886 " time, and hibernate"
7887 "\n%3$sOptions:%4$s\n"
7888 " -h --help Show this help\n"
7889 " --version Show package version\n"
7890 " --system Connect to system manager\n"
7891 " --user Connect to user service manager\n"
7892 " -H --host=[USER@]HOST Operate on remote host\n"
7893 " -M --machine=CONTAINER Operate on a local container\n"
7894 " -t --type=TYPE List units of a particular type\n"
7895 " --state=STATE List units with particular LOAD or SUB or ACTIVE state\n"
7896 " --failed Shorcut for --state=failed\n"
7897 " -p --property=NAME Show only properties by this name\n"
7898 " -a --all Show all properties/all units currently in memory,\n"
7899 " including dead/empty ones. To list all units installed\n"
7900 " on the system, use 'list-unit-files' instead.\n"
7901 " -l --full Don't ellipsize unit names on output\n"
7902 " -r --recursive Show unit list of host and local containers\n"
7903 " --reverse Show reverse dependencies with 'list-dependencies'\n"
7904 " --with-dependencies Show unit dependencies with 'status', 'cat',\n"
7905 " 'list-units', and 'list-unit-files'.\n"
7906 " --job-mode=MODE Specify how to deal with already queued jobs, when\n"
7907 " queueing a new job\n"
7908 " -T --show-transaction When enqueuing a unit job, show full transaction\n"
7909 " --show-types When showing sockets, explicitly show their type\n"
7910 " --value When showing properties, only print the value\n"
7911 " -i --ignore-inhibitors When shutting down or sleeping, ignore inhibitors\n"
7912 " --kill-who=WHO Whom to send signal to\n"
7913 " -s --signal=SIGNAL Which signal to send\n"
7914 " --what=RESOURCES Which types of resources to remove\n"
7915 " --now Start or stop unit after enabling or disabling it\n"
7916 " --dry-run Only print what would be done\n"
7917 " Currently supported by verbs: halt, poweroff, reboot,\n"
7918 " kexec, suspend, hibernate, suspend-then-hibernate,\n"
7919 " hybrid-sleep, default, rescue, emergency, and exit.\n"
7920 " -q --quiet Suppress output\n"
7921 " --wait For (re)start, wait until service stopped again\n"
7922 " For is-system-running, wait until startup is completed\n"
7923 " --no-block Do not wait until operation finished\n"
7924 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7925 " --no-reload Don't reload daemon after en-/dis-abling unit files\n"
7926 " --no-legend Do not print a legend (column headers and hints)\n"
7927 " --no-pager Do not pipe output into a pager\n"
7928 " --no-ask-password Do not ask for system passwords\n"
7929 " --global Enable/disable/mask unit files globally\n"
7930 " --runtime Enable/disable/mask unit files temporarily until next\n"
7932 " -f --force When enabling unit files, override existing symlinks\n"
7933 " When shutting down, execute action immediately\n"
7934 " --preset-mode= Apply only enable, only disable, or all presets\n"
7935 " --root=PATH Enable/disable/mask unit files in the specified root\n"
7937 " -n --lines=INTEGER Number of journal entries to show\n"
7938 " -o --output=STRING Change journal output mode (short, short-precise,\n"
7939 " short-iso, short-iso-precise, short-full,\n"
7940 " short-monotonic, short-unix,\n"
7941 " verbose, export, json, json-pretty, json-sse, cat)\n"
7942 " --firmware-setup Tell the firmware to show the setup menu on next boot\n"
7943 " --boot-loader-menu=TIME\n"
7944 " Boot into boot loader menu on next boot\n"
7945 " --boot-loader-entry=NAME\n"
7946 " Boot into a specific boot loader entry on next boot\n"
7947 " --plain Print unit dependencies as a list instead of a tree\n"
7948 "\nSee the %2$s for details.\n"
7949 , program_invocation_short_name
7951 , ansi_underline(), ansi_normal()
7952 , ansi_highlight(), ansi_normal()
7958 static int halt_help(void) {
7959 _cleanup_free_
char *link
= NULL
;
7962 r
= terminal_urlify_man("halt", "8", &link
);
7966 printf("%s [OPTIONS...]%s\n"
7967 "\n%s%s the system.%s\n"
7969 " --help Show this help\n"
7970 " --halt Halt the machine\n"
7971 " -p --poweroff Switch off the machine\n"
7972 " --reboot Reboot the machine\n"
7973 " -f --force Force immediate halt/power-off/reboot\n"
7974 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
7975 " -d --no-wtmp Don't write wtmp record\n"
7976 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7977 "\nSee the %s for details.\n"
7978 , program_invocation_short_name
7979 , arg_action
== ACTION_REBOOT
? " [ARG]" : ""
7981 , arg_action
== ACTION_REBOOT
? "Reboot" :
7982 arg_action
== ACTION_POWEROFF
? "Power off" :
7991 static int shutdown_help(void) {
7992 _cleanup_free_
char *link
= NULL
;
7995 r
= terminal_urlify_man("shutdown", "8", &link
);
7999 printf("%s [OPTIONS...] [TIME] [WALL...]\n"
8000 "\n%sShut down the system.%s\n"
8002 " --help Show this help\n"
8003 " -H --halt Halt the machine\n"
8004 " -P --poweroff Power-off the machine\n"
8005 " -r --reboot Reboot the machine\n"
8006 " -h Equivalent to --poweroff, overridden by --halt\n"
8007 " -k Don't halt/power-off/reboot, just send warnings\n"
8008 " --no-wall Don't send wall message before halt/power-off/reboot\n"
8009 " -c Cancel a pending shutdown\n"
8010 "\nSee the %s for details.\n"
8011 , program_invocation_short_name
8012 , ansi_highlight(), ansi_normal()
8019 static int telinit_help(void) {
8020 _cleanup_free_
char *link
= NULL
;
8023 r
= terminal_urlify_man("telinit", "8", &link
);
8027 printf("%s [OPTIONS...] COMMAND\n\n"
8028 "%sSend control commands to the init daemon.%s\n"
8030 " 0 Power-off the machine\n"
8031 " 6 Reboot the machine\n"
8032 " 2, 3, 4, 5 Start runlevelX.target unit\n"
8033 " 1, s, S Enter rescue mode\n"
8034 " q, Q Reload init daemon configuration\n"
8035 " u, U Reexecute init daemon\n"
8037 " --help Show this help\n"
8038 " --no-wall Don't send wall message before halt/power-off/reboot\n"
8039 "\nSee the %s for details.\n"
8040 , program_invocation_short_name
8041 , ansi_highlight(), ansi_normal()
8048 static int runlevel_help(void) {
8049 _cleanup_free_
char *link
= NULL
;
8052 r
= terminal_urlify_man("runlevel", "8", &link
);
8056 printf("%s [OPTIONS...]\n"
8057 "\n%sPrints the previous and current runlevel of the init system.%s\n"
8059 " --help Show this help\n"
8060 "\nSee the %s for details.\n"
8061 , program_invocation_short_name
8062 , ansi_highlight(), ansi_normal()
8069 static void help_types(void) {
8071 puts("Available unit types:");
8073 DUMP_STRING_TABLE(unit_type
, UnitType
, _UNIT_TYPE_MAX
);
8076 static void help_states(void) {
8078 puts("Available unit load states:");
8079 DUMP_STRING_TABLE(unit_load_state
, UnitLoadState
, _UNIT_LOAD_STATE_MAX
);
8082 puts("\nAvailable unit active states:");
8083 DUMP_STRING_TABLE(unit_active_state
, UnitActiveState
, _UNIT_ACTIVE_STATE_MAX
);
8086 puts("\nAvailable unit file states:");
8087 DUMP_STRING_TABLE(unit_file_state
, UnitFileState
, _UNIT_FILE_STATE_MAX
);
8090 puts("\nAvailable automount unit substates:");
8091 DUMP_STRING_TABLE(automount_state
, AutomountState
, _AUTOMOUNT_STATE_MAX
);
8094 puts("\nAvailable device unit substates:");
8095 DUMP_STRING_TABLE(device_state
, DeviceState
, _DEVICE_STATE_MAX
);
8098 puts("\nAvailable mount unit substates:");
8099 DUMP_STRING_TABLE(mount_state
, MountState
, _MOUNT_STATE_MAX
);
8102 puts("\nAvailable path unit substates:");
8103 DUMP_STRING_TABLE(path_state
, PathState
, _PATH_STATE_MAX
);
8106 puts("\nAvailable scope unit substates:");
8107 DUMP_STRING_TABLE(scope_state
, ScopeState
, _SCOPE_STATE_MAX
);
8110 puts("\nAvailable service unit substates:");
8111 DUMP_STRING_TABLE(service_state
, ServiceState
, _SERVICE_STATE_MAX
);
8114 puts("\nAvailable slice unit substates:");
8115 DUMP_STRING_TABLE(slice_state
, SliceState
, _SLICE_STATE_MAX
);
8118 puts("\nAvailable socket unit substates:");
8119 DUMP_STRING_TABLE(socket_state
, SocketState
, _SOCKET_STATE_MAX
);
8122 puts("\nAvailable swap unit substates:");
8123 DUMP_STRING_TABLE(swap_state
, SwapState
, _SWAP_STATE_MAX
);
8126 puts("\nAvailable target unit substates:");
8127 DUMP_STRING_TABLE(target_state
, TargetState
, _TARGET_STATE_MAX
);
8130 puts("\nAvailable timer unit substates:");
8131 DUMP_STRING_TABLE(timer_state
, TimerState
, _TIMER_STATE_MAX
);
8134 static int help_boot_loader_entry(void) {
8135 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
8136 _cleanup_strv_free_
char **l
= NULL
;
8141 r
= acquire_bus(BUS_FULL
, &bus
);
8145 r
= sd_bus_get_property_strv(
8147 "org.freedesktop.login1",
8148 "/org/freedesktop/login1",
8149 "org.freedesktop.login1.Manager",
8150 "BootLoaderEntries",
8154 return log_error_errno(r
, "Failed to enumerate boot loader entries: %s", bus_error_message(&error
, r
));
8156 if (strv_isempty(l
))
8157 return log_error_errno(SYNTHETIC_ERRNO(ENODATA
), "No boot loader entries discovered.");
8165 static int systemctl_parse_argv(int argc
, char *argv
[]) {
8174 ARG_IGNORE_DEPENDENCIES
,
8187 ARG_NO_ASK_PASSWORD
,
8195 ARG_BOOT_LOADER_MENU
,
8196 ARG_BOOT_LOADER_ENTRY
,
8199 ARG_WITH_DEPENDENCIES
,
8204 static const struct option options
[] = {
8205 { "help", no_argument
, NULL
, 'h' },
8206 { "version", no_argument
, NULL
, ARG_VERSION
},
8207 { "type", required_argument
, NULL
, 't' },
8208 { "property", required_argument
, NULL
, 'p' },
8209 { "all", no_argument
, NULL
, 'a' },
8210 { "reverse", no_argument
, NULL
, ARG_REVERSE
},
8211 { "after", no_argument
, NULL
, ARG_AFTER
},
8212 { "before", no_argument
, NULL
, ARG_BEFORE
},
8213 { "show-types", no_argument
, NULL
, ARG_SHOW_TYPES
},
8214 { "failed", no_argument
, NULL
, ARG_FAILED
}, /* compatibility only */
8215 { "full", no_argument
, NULL
, 'l' },
8216 { "job-mode", required_argument
, NULL
, ARG_JOB_MODE
},
8217 { "fail", no_argument
, NULL
, ARG_FAIL
}, /* compatibility only */
8218 { "irreversible", no_argument
, NULL
, ARG_IRREVERSIBLE
}, /* compatibility only */
8219 { "ignore-dependencies", no_argument
, NULL
, ARG_IGNORE_DEPENDENCIES
}, /* compatibility only */
8220 { "ignore-inhibitors", no_argument
, NULL
, 'i' },
8221 { "value", no_argument
, NULL
, ARG_VALUE
},
8222 { "user", no_argument
, NULL
, ARG_USER
},
8223 { "system", no_argument
, NULL
, ARG_SYSTEM
},
8224 { "global", no_argument
, NULL
, ARG_GLOBAL
},
8225 { "wait", no_argument
, NULL
, ARG_WAIT
},
8226 { "no-block", no_argument
, NULL
, ARG_NO_BLOCK
},
8227 { "no-legend", no_argument
, NULL
, ARG_NO_LEGEND
},
8228 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
8229 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8230 { "dry-run", no_argument
, NULL
, ARG_DRY_RUN
},
8231 { "quiet", no_argument
, NULL
, 'q' },
8232 { "root", required_argument
, NULL
, ARG_ROOT
},
8233 { "force", no_argument
, NULL
, 'f' },
8234 { "no-reload", no_argument
, NULL
, ARG_NO_RELOAD
},
8235 { "kill-who", required_argument
, NULL
, ARG_KILL_WHO
},
8236 { "signal", required_argument
, NULL
, 's' },
8237 { "no-ask-password", no_argument
, NULL
, ARG_NO_ASK_PASSWORD
},
8238 { "host", required_argument
, NULL
, 'H' },
8239 { "machine", required_argument
, NULL
, 'M' },
8240 { "runtime", no_argument
, NULL
, ARG_RUNTIME
},
8241 { "lines", required_argument
, NULL
, 'n' },
8242 { "output", required_argument
, NULL
, 'o' },
8243 { "plain", no_argument
, NULL
, ARG_PLAIN
},
8244 { "state", required_argument
, NULL
, ARG_STATE
},
8245 { "recursive", no_argument
, NULL
, 'r' },
8246 { "with-dependencies", no_argument
, NULL
, ARG_WITH_DEPENDENCIES
},
8247 { "preset-mode", required_argument
, NULL
, ARG_PRESET_MODE
},
8248 { "firmware-setup", no_argument
, NULL
, ARG_FIRMWARE_SETUP
},
8249 { "boot-loader-menu", required_argument
, NULL
, ARG_BOOT_LOADER_MENU
},
8250 { "boot-loader-entry", required_argument
, NULL
, ARG_BOOT_LOADER_ENTRY
},
8251 { "now", no_argument
, NULL
, ARG_NOW
},
8252 { "message", required_argument
, NULL
, ARG_MESSAGE
},
8253 { "show-transaction", no_argument
, NULL
, 'T' },
8254 { "what", required_argument
, NULL
, ARG_WHAT
},
8263 /* we default to allowing interactive authorization only in systemctl (not in the legacy commands) */
8264 arg_ask_password
= true;
8266 while ((c
= getopt_long(argc
, argv
, "ht:p:alqfs:H:M:n:o:iTr.::", options
, NULL
)) >= 0)
8271 return systemctl_help();
8279 if (isempty(optarg
))
8280 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8281 "--type= requires arguments.");
8283 for (p
= optarg
;;) {
8284 _cleanup_free_
char *type
= NULL
;
8286 r
= extract_first_word(&p
, &type
, ",", 0);
8288 return log_error_errno(r
, "Failed to parse type: %s", optarg
);
8292 if (streq(type
, "help")) {
8297 if (unit_type_from_string(type
) >= 0) {
8298 if (strv_consume(&arg_types
, TAKE_PTR(type
)) < 0)
8303 /* It's much nicer to use --state= for
8304 * load states, but let's support this
8305 * in --types= too for compatibility
8306 * with old versions */
8307 if (unit_load_state_from_string(type
) >= 0) {
8308 if (strv_consume(&arg_states
, TAKE_PTR(type
)) < 0)
8313 log_error("Unknown unit type or load state '%s'.", type
);
8314 return log_info_errno(SYNTHETIC_ERRNO(EINVAL
),
8315 "Use -t help to see a list of allowed values.");
8322 /* Make sure that if the empty property list was specified, we won't show any
8324 if (isempty(optarg
) && !arg_properties
) {
8325 arg_properties
= new0(char*, 1);
8326 if (!arg_properties
)
8331 for (p
= optarg
;;) {
8332 _cleanup_free_
char *prop
= NULL
;
8334 r
= extract_first_word(&p
, &prop
, ",", 0);
8336 return log_error_errno(r
, "Failed to parse property: %s", optarg
);
8340 if (strv_consume(&arg_properties
, TAKE_PTR(prop
)) < 0)
8345 /* If the user asked for a particular
8346 * property, show it to him, even if it is
8357 arg_dependency
= DEPENDENCY_REVERSE
;
8361 arg_dependency
= DEPENDENCY_AFTER
;
8362 arg_jobs_after
= true;
8366 arg_dependency
= DEPENDENCY_BEFORE
;
8367 arg_jobs_before
= true;
8370 case ARG_SHOW_TYPES
:
8371 arg_show_types
= true;
8379 arg_job_mode
= optarg
;
8383 arg_job_mode
= "fail";
8386 case ARG_IRREVERSIBLE
:
8387 arg_job_mode
= "replace-irreversibly";
8390 case ARG_IGNORE_DEPENDENCIES
:
8391 arg_job_mode
= "ignore-dependencies";
8395 arg_scope
= UNIT_FILE_USER
;
8399 arg_scope
= UNIT_FILE_SYSTEM
;
8403 arg_scope
= UNIT_FILE_GLOBAL
;
8411 arg_no_block
= true;
8415 arg_no_legend
= true;
8419 arg_pager_flags
|= PAGER_DISABLE
;
8427 r
= parse_path_argument_and_warn(optarg
, false, &arg_root
);
8437 if (strv_extend(&arg_states
, "failed") < 0)
8455 arg_no_reload
= true;
8459 arg_kill_who
= optarg
;
8463 if (streq(optarg
, "help")) {
8464 DUMP_STRING_TABLE(signal
, int, _NSIG
);
8468 arg_signal
= signal_from_string(optarg
);
8470 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8471 "Failed to parse signal string %s.",
8475 case ARG_NO_ASK_PASSWORD
:
8476 arg_ask_password
= false;
8480 arg_transport
= BUS_TRANSPORT_REMOTE
;
8485 arg_transport
= BUS_TRANSPORT_MACHINE
;
8494 if (safe_atou(optarg
, &arg_lines
) < 0)
8495 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8496 "Failed to parse lines '%s'",
8501 if (streq(optarg
, "help")) {
8502 DUMP_STRING_TABLE(output_mode
, OutputMode
, _OUTPUT_MODE_MAX
);
8506 arg_output
= output_mode_from_string(optarg
);
8508 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8509 "Unknown output '%s'.",
8514 arg_ignore_inhibitors
= true;
8521 case ARG_FIRMWARE_SETUP
:
8522 arg_firmware_setup
= true;
8525 case ARG_BOOT_LOADER_MENU
:
8527 r
= parse_sec(optarg
, &arg_boot_loader_menu
);
8529 return log_error_errno(r
, "Failed to parse --boot-loader-menu= argument '%s': %m", optarg
);
8533 case ARG_BOOT_LOADER_ENTRY
:
8535 if (streq(optarg
, "help")) { /* Yes, this means, "help" is not a valid boot loader entry name we can deal with */
8536 r
= help_boot_loader_entry();
8543 arg_boot_loader_entry
= empty_to_null(optarg
);
8549 if (isempty(optarg
))
8550 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8551 "--state= requires arguments.");
8553 for (p
= optarg
;;) {
8554 _cleanup_free_
char *s
= NULL
;
8556 r
= extract_first_word(&p
, &s
, ",", 0);
8558 return log_error_errno(r
, "Failed to parse state: %s", optarg
);
8562 if (streq(s
, "help")) {
8567 if (strv_consume(&arg_states
, TAKE_PTR(s
)) < 0)
8575 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
8576 "--recursive requires root privileges.");
8578 arg_recursive
= true;
8581 case ARG_PRESET_MODE
:
8582 if (streq(optarg
, "help")) {
8583 DUMP_STRING_TABLE(unit_file_preset_mode
, UnitFilePresetMode
, _UNIT_FILE_PRESET_MAX
);
8587 arg_preset_mode
= unit_file_preset_mode_from_string(optarg
);
8588 if (arg_preset_mode
< 0)
8589 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8590 "Failed to parse preset mode: %s.", optarg
);
8599 if (strv_extend(&arg_wall
, optarg
) < 0)
8604 arg_show_transaction
= true;
8607 case ARG_WITH_DEPENDENCIES
:
8608 arg_with_dependencies
= true;
8614 if (isempty(optarg
))
8615 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "--what= requires arguments.");
8617 for (p
= optarg
;;) {
8618 _cleanup_free_
char *k
= NULL
;
8620 r
= extract_first_word(&p
, &k
, ",", 0);
8622 return log_error_errno(r
, "Failed to parse directory type: %s", optarg
);
8626 if (streq(k
, "help")) {
8635 r
= strv_consume(&arg_clean_what
, TAKE_PTR(k
));
8644 /* Output an error mimicking getopt, and print a hint afterwards */
8645 log_error("%s: invalid option -- '.'", program_invocation_name
);
8646 log_notice("Hint: to specify units starting with a dash, use \"--\":\n"
8647 " %s [OPTIONS...] COMMAND -- -.%s ...",
8648 program_invocation_name
, optarg
?: "mount");
8655 assert_not_reached("Unhandled option");
8658 if (arg_transport
!= BUS_TRANSPORT_LOCAL
&& arg_scope
!= UNIT_FILE_SYSTEM
)
8659 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8660 "Cannot access user instance remotely.");
8662 if (arg_wait
&& arg_no_block
)
8663 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8664 "--wait may not be combined with --no-block.");
8669 static int halt_parse_argv(int argc
, char *argv
[]) {
8677 static const struct option options
[] = {
8678 { "help", no_argument
, NULL
, ARG_HELP
},
8679 { "halt", no_argument
, NULL
, ARG_HALT
},
8680 { "poweroff", no_argument
, NULL
, 'p' },
8681 { "reboot", no_argument
, NULL
, ARG_REBOOT
},
8682 { "force", no_argument
, NULL
, 'f' },
8683 { "wtmp-only", no_argument
, NULL
, 'w' },
8684 { "no-wtmp", no_argument
, NULL
, 'd' },
8685 { "no-sync", no_argument
, NULL
, 'n' },
8686 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8695 if (utmp_get_runlevel(&runlevel
, NULL
) >= 0)
8696 if (IN_SET(runlevel
, '0', '6'))
8699 while ((c
= getopt_long(argc
, argv
, "pfwdnih", options
, NULL
)) >= 0)
8706 arg_action
= ACTION_HALT
;
8710 if (arg_action
!= ACTION_REBOOT
)
8711 arg_action
= ACTION_POWEROFF
;
8715 arg_action
= ACTION_REBOOT
;
8740 /* Compatibility nops */
8747 assert_not_reached("Unhandled option");
8750 if (arg_action
== ACTION_REBOOT
&& (argc
== optind
|| argc
== optind
+ 1)) {
8751 r
= update_reboot_parameter_and_warn(argc
== optind
+ 1 ? argv
[optind
] : NULL
, false);
8754 } else if (optind
< argc
)
8755 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8756 "Too many arguments.");
8761 static int shutdown_parse_argv(int argc
, char *argv
[]) {
8767 static const struct option options
[] = {
8768 { "help", no_argument
, NULL
, ARG_HELP
},
8769 { "halt", no_argument
, NULL
, 'H' },
8770 { "poweroff", no_argument
, NULL
, 'P' },
8771 { "reboot", no_argument
, NULL
, 'r' },
8772 { "kexec", no_argument
, NULL
, 'K' }, /* not documented extension */
8773 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8783 while ((c
= getopt_long(argc
, argv
, "HPrhkKat:fFc", options
, NULL
)) >= 0)
8787 return shutdown_help();
8790 arg_action
= ACTION_HALT
;
8794 arg_action
= ACTION_POWEROFF
;
8799 arg_action
= ACTION_KEXEC
;
8801 arg_action
= ACTION_REBOOT
;
8805 arg_action
= ACTION_KEXEC
;
8809 if (arg_action
!= ACTION_HALT
)
8810 arg_action
= ACTION_POWEROFF
;
8822 case 't': /* Note that we also ignore any passed argument to -t, not just the -t itself */
8825 /* Compatibility nops */
8829 arg_action
= ACTION_CANCEL_SHUTDOWN
;
8836 assert_not_reached("Unhandled option");
8839 if (argc
> optind
&& arg_action
!= ACTION_CANCEL_SHUTDOWN
) {
8840 r
= parse_shutdown_time_spec(argv
[optind
], &arg_when
);
8842 log_error("Failed to parse time specification: %s", argv
[optind
]);
8846 arg_when
= now(CLOCK_REALTIME
) + USEC_PER_MINUTE
;
8848 if (argc
> optind
&& arg_action
== ACTION_CANCEL_SHUTDOWN
)
8849 /* No time argument for shutdown cancel */
8850 wall
= argv
+ optind
;
8851 else if (argc
> optind
+ 1)
8852 /* We skip the time argument */
8853 wall
= argv
+ optind
+ 1;
8856 arg_wall
= strv_copy(wall
);
8866 static int telinit_parse_argv(int argc
, char *argv
[]) {
8872 static const struct option options
[] = {
8873 { "help", no_argument
, NULL
, ARG_HELP
},
8874 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8878 static const struct {
8882 { '0', ACTION_POWEROFF
},
8883 { '6', ACTION_REBOOT
},
8884 { '1', ACTION_RESCUE
},
8885 { '2', ACTION_RUNLEVEL2
},
8886 { '3', ACTION_RUNLEVEL3
},
8887 { '4', ACTION_RUNLEVEL4
},
8888 { '5', ACTION_RUNLEVEL5
},
8889 { 's', ACTION_RESCUE
},
8890 { 'S', ACTION_RESCUE
},
8891 { 'q', ACTION_RELOAD
},
8892 { 'Q', ACTION_RELOAD
},
8893 { 'u', ACTION_REEXEC
},
8894 { 'U', ACTION_REEXEC
}
8903 while ((c
= getopt_long(argc
, argv
, "", options
, NULL
)) >= 0)
8907 return telinit_help();
8917 assert_not_reached("Unhandled option");
8921 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8922 "%s: required argument missing.",
8923 program_invocation_short_name
);
8925 if (optind
+ 1 < argc
)
8926 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8927 "Too many arguments.");
8929 if (strlen(argv
[optind
]) != 1)
8930 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8931 "Expected single character argument.");
8933 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
8934 if (table
[i
].from
== argv
[optind
][0])
8937 if (i
>= ELEMENTSOF(table
))
8938 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8939 "Unknown command '%s'.", argv
[optind
]);
8941 arg_action
= table
[i
].to
;
8948 static int runlevel_parse_argv(int argc
, char *argv
[]) {
8953 static const struct option options
[] = {
8954 { "help", no_argument
, NULL
, ARG_HELP
},
8963 while ((c
= getopt_long(argc
, argv
, "", options
, NULL
)) >= 0)
8967 return runlevel_help();
8973 assert_not_reached("Unhandled option");
8977 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8978 "Too many arguments.");
8983 static int parse_argv(int argc
, char *argv
[]) {
8987 if (program_invocation_short_name
) {
8989 if (strstr(program_invocation_short_name
, "halt")) {
8990 arg_action
= ACTION_HALT
;
8991 return halt_parse_argv(argc
, argv
);
8993 } else if (strstr(program_invocation_short_name
, "poweroff")) {
8994 arg_action
= ACTION_POWEROFF
;
8995 return halt_parse_argv(argc
, argv
);
8997 } else if (strstr(program_invocation_short_name
, "reboot")) {
8999 arg_action
= ACTION_KEXEC
;
9001 arg_action
= ACTION_REBOOT
;
9002 return halt_parse_argv(argc
, argv
);
9004 } else if (strstr(program_invocation_short_name
, "shutdown")) {
9005 arg_action
= ACTION_POWEROFF
;
9006 return shutdown_parse_argv(argc
, argv
);
9008 } else if (strstr(program_invocation_short_name
, "init")) {
9010 /* Matches invocations as "init" as well as "telinit", which are synonymous when run as PID !=
9013 * On SysV "telinit" was the official command to communicate with PID 1, but "init" would
9014 * redirect itself to "telinit" if called with PID != 1. We follow the same logic here still,
9015 * though we add one level of indirection, as we implement "telinit" in "systemctl". Hence, for
9016 * us if you invoke "init" you get "systemd", but it will execve() "systemctl" immediately with
9017 * argv[] unmodified if PID is != 1. If you invoke "telinit" you directly get "systemctl". In
9018 * both cases we shall do the same thing, which is why we do strstr(p_i_s_n, "init") here, as a
9019 * quick way to match both.
9021 * Also see redirect_telinit() in src/core/main.c. */
9023 if (sd_booted() > 0) {
9024 arg_action
= _ACTION_INVALID
;
9025 return telinit_parse_argv(argc
, argv
);
9027 /* Hmm, so some other init system is running, we need to forward this request to
9028 * it. For now we simply guess that it is Upstart. */
9030 (void) rlimit_nofile_safe();
9031 execv(TELINIT
, argv
);
9033 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
9034 "Couldn't find an alternative telinit implementation to spawn.");
9037 } else if (strstr(program_invocation_short_name
, "runlevel")) {
9038 arg_action
= ACTION_RUNLEVEL
;
9039 return runlevel_parse_argv(argc
, argv
);
9043 arg_action
= ACTION_SYSTEMCTL
;
9044 return systemctl_parse_argv(argc
, argv
);
9047 #if HAVE_SYSV_COMPAT
9048 _pure_
static int action_to_runlevel(void) {
9049 static const char table
[_ACTION_MAX
] = {
9050 [ACTION_HALT
] = '0',
9051 [ACTION_POWEROFF
] = '0',
9052 [ACTION_REBOOT
] = '6',
9053 [ACTION_RUNLEVEL2
] = '2',
9054 [ACTION_RUNLEVEL3
] = '3',
9055 [ACTION_RUNLEVEL4
] = '4',
9056 [ACTION_RUNLEVEL5
] = '5',
9057 [ACTION_RESCUE
] = '1'
9060 assert(arg_action
>= 0 && arg_action
< _ACTION_MAX
);
9061 return table
[arg_action
];
9065 static int systemctl_main(int argc
, char *argv
[]) {
9066 static const Verb verbs
[] = {
9067 { "list-units", VERB_ANY
, VERB_ANY
, VERB_DEFAULT
|VERB_ONLINE_ONLY
, list_units
},
9068 { "list-unit-files", VERB_ANY
, VERB_ANY
, 0, list_unit_files
},
9069 { "list-sockets", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_sockets
},
9070 { "list-timers", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_timers
},
9071 { "list-jobs", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_jobs
},
9072 { "list-machines", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_machines
},
9073 { "clear-jobs", VERB_ANY
, 1, VERB_ONLINE_ONLY
, trivial_method
},
9074 { "cancel", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, cancel_job
},
9075 { "start", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9076 { "stop", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9077 { "condstop", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with ALTLinux */
9078 { "reload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9079 { "restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9080 { "try-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9081 { "reload-or-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9082 { "reload-or-try-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with old systemctl <= 228 */
9083 { "try-reload-or-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9084 { "force-reload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with SysV */
9085 { "condreload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with ALTLinux */
9086 { "condrestart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with RH */
9087 { "isolate", 2, 2, VERB_ONLINE_ONLY
, start_unit
},
9088 { "kill", 2, VERB_ANY
, VERB_ONLINE_ONLY
, kill_unit
},
9089 { "clean", 2, VERB_ANY
, VERB_ONLINE_ONLY
, clean_unit
},
9090 { "is-active", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_active
},
9091 { "check", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_active
}, /* deprecated alias of is-active */
9092 { "is-failed", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_failed
},
9093 { "show", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
9094 { "cat", 2, VERB_ANY
, VERB_ONLINE_ONLY
, cat
},
9095 { "status", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
9096 { "help", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
9097 { "daemon-reload", VERB_ANY
, 1, VERB_ONLINE_ONLY
, daemon_reload
},
9098 { "daemon-reexec", VERB_ANY
, 1, VERB_ONLINE_ONLY
, daemon_reload
},
9099 { "log-level", VERB_ANY
, 2, 0, log_level
},
9100 { "log-target", VERB_ANY
, 2, 0, log_target
},
9101 { "service-watchdogs", VERB_ANY
, 2, 0, service_watchdogs
},
9102 { "show-environment", VERB_ANY
, 1, VERB_ONLINE_ONLY
, show_environment
},
9103 { "set-environment", 2, VERB_ANY
, VERB_ONLINE_ONLY
, set_environment
},
9104 { "unset-environment", 2, VERB_ANY
, VERB_ONLINE_ONLY
, set_environment
},
9105 { "import-environment", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, import_environment
},
9106 { "halt", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9107 { "poweroff", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9108 { "reboot", VERB_ANY
, 2, VERB_ONLINE_ONLY
, start_system_special
},
9109 { "kexec", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9110 { "suspend", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9111 { "hibernate", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9112 { "hybrid-sleep", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9113 { "suspend-then-hibernate",VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9114 { "default", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_special
},
9115 { "rescue", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9116 { "emergency", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9117 { "exit", VERB_ANY
, 2, VERB_ONLINE_ONLY
, start_special
},
9118 { "reset-failed", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, reset_failed
},
9119 { "enable", 2, VERB_ANY
, 0, enable_unit
},
9120 { "disable", 2, VERB_ANY
, 0, enable_unit
},
9121 { "is-enabled", 2, VERB_ANY
, 0, unit_is_enabled
},
9122 { "reenable", 2, VERB_ANY
, 0, enable_unit
},
9123 { "preset", 2, VERB_ANY
, 0, enable_unit
},
9124 { "preset-all", VERB_ANY
, 1, 0, preset_all
},
9125 { "mask", 2, VERB_ANY
, 0, enable_unit
},
9126 { "unmask", 2, VERB_ANY
, 0, enable_unit
},
9127 { "link", 2, VERB_ANY
, 0, enable_unit
},
9128 { "revert", 2, VERB_ANY
, 0, enable_unit
},
9129 { "switch-root", 2, VERB_ANY
, VERB_ONLINE_ONLY
, switch_root
},
9130 { "list-dependencies", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_dependencies
},
9131 { "set-default", 2, 2, 0, set_default
},
9132 { "get-default", VERB_ANY
, 1, 0, get_default
},
9133 { "set-property", 3, VERB_ANY
, VERB_ONLINE_ONLY
, set_property
},
9134 { "is-system-running", VERB_ANY
, 1, 0, is_system_running
},
9135 { "add-wants", 3, VERB_ANY
, 0, add_dependency
},
9136 { "add-requires", 3, VERB_ANY
, 0, add_dependency
},
9137 { "edit", 2, VERB_ANY
, VERB_ONLINE_ONLY
, edit
},
9141 return dispatch_verb(argc
, argv
, verbs
, NULL
);
9144 static int reload_with_fallback(void) {
9145 /* First, try systemd via D-Bus. */
9146 if (daemon_reload(0, NULL
, NULL
) >= 0)
9149 /* Nothing else worked, so let's try signals */
9150 assert(IN_SET(arg_action
, ACTION_RELOAD
, ACTION_REEXEC
));
9152 if (kill(1, arg_action
== ACTION_RELOAD
? SIGHUP
: SIGTERM
) < 0)
9153 return log_error_errno(errno
, "kill() failed: %m");
9158 static int start_with_fallback(void) {
9159 /* First, try systemd via D-Bus. */
9160 if (start_unit(0, NULL
, NULL
) == 0)
9163 #if HAVE_SYSV_COMPAT
9164 /* Nothing else worked, so let's try /dev/initctl */
9165 if (talk_initctl(action_to_runlevel()) > 0)
9169 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
9170 "Failed to talk to init daemon.");
9173 static int halt_now(enum action a
) {
9174 /* The kernel will automatically flush ATA disks and suchlike on reboot(), but the file systems need to be
9175 * synced explicitly in advance. */
9176 if (!arg_no_sync
&& !arg_dry_run
)
9179 /* Make sure C-A-D is handled by the kernel from this point on... */
9181 (void) reboot(RB_ENABLE_CAD
);
9187 log_info("Halting.");
9190 (void) reboot(RB_HALT_SYSTEM
);
9193 case ACTION_POWEROFF
:
9195 log_info("Powering off.");
9198 (void) reboot(RB_POWER_OFF
);
9203 return reboot_with_parameter(REBOOT_FALLBACK
|
9204 (arg_quiet
? 0 : REBOOT_LOG
) |
9205 (arg_dry_run
? REBOOT_DRY_RUN
: 0));
9208 assert_not_reached("Unknown action.");
9212 static int logind_schedule_shutdown(void) {
9215 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
9216 char date
[FORMAT_TIMESTAMP_MAX
];
9221 r
= acquire_bus(BUS_FULL
, &bus
);
9225 switch (arg_action
) {
9229 case ACTION_POWEROFF
:
9230 action
= "poweroff";
9245 action
= strjoina("dry-", action
);
9247 (void) logind_set_wall_message();
9249 r
= sd_bus_call_method(
9251 "org.freedesktop.login1",
9252 "/org/freedesktop/login1",
9253 "org.freedesktop.login1.Manager",
9261 return log_warning_errno(r
, "Failed to call ScheduleShutdown in logind, proceeding with immediate shutdown: %s", bus_error_message(&error
, r
));
9264 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.", format_timestamp(date
, sizeof(date
), arg_when
));
9267 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
9268 "Cannot schedule shutdown without logind support, proceeding with immediate shutdown.");
9272 static int halt_main(void) {
9275 r
= logind_check_inhibitors(arg_action
);
9279 /* Delayed shutdown requested, and was successful */
9280 if (arg_when
> 0 && logind_schedule_shutdown() == 0)
9282 /* no delay, or logind failed or is not at all available */
9284 if (geteuid() != 0) {
9285 if (arg_dry_run
|| arg_force
> 0) {
9286 (void) must_be_root();
9290 /* Try logind if we are a normal user and no special
9291 * mode applies. Maybe polkit allows us to shutdown
9293 if (IN_SET(arg_action
, ACTION_POWEROFF
, ACTION_REBOOT
, ACTION_HALT
)) {
9294 r
= logind_reboot(arg_action
);
9297 if (IN_SET(r
, -EOPNOTSUPP
, -EINPROGRESS
))
9298 /* requested operation is not
9299 * supported on the local system or
9300 * already in progress */
9302 /* on all other errors, try low-level operation */
9306 /* In order to minimize the difference between operation with and
9307 * without logind, we explicitly enable non-blocking mode for this,
9308 * as logind's shutdown operations are always non-blocking. */
9309 arg_no_block
= true;
9311 if (!arg_dry_run
&& !arg_force
)
9312 return start_with_fallback();
9314 assert(geteuid() == 0);
9317 if (sd_booted() > 0)
9318 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
9320 r
= utmp_put_shutdown();
9322 log_warning_errno(r
, "Failed to write utmp record: %m");
9329 r
= halt_now(arg_action
);
9330 return log_error_errno(r
, "Failed to reboot: %m");
9333 static int runlevel_main(void) {
9334 int r
, runlevel
, previous
;
9336 r
= utmp_get_runlevel(&runlevel
, &previous
);
9343 previous
<= 0 ? 'N' : previous
,
9344 runlevel
<= 0 ? 'N' : runlevel
);
9349 static int logind_cancel_shutdown(void) {
9351 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
9355 r
= acquire_bus(BUS_FULL
, &bus
);
9359 (void) logind_set_wall_message();
9361 r
= sd_bus_call_method(
9363 "org.freedesktop.login1",
9364 "/org/freedesktop/login1",
9365 "org.freedesktop.login1.Manager",
9366 "CancelScheduledShutdown",
9370 return log_warning_errno(r
, "Failed to talk to logind, shutdown hasn't been cancelled: %s", bus_error_message(&error
, r
));
9374 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
9375 "Not compiled with logind support, cannot cancel scheduled shutdowns.");
9379 static int run(int argc
, char *argv
[]) {
9382 setlocale(LC_ALL
, "");
9383 log_parse_environment();
9386 /* The journal merging logic potentially needs a lot of fds. */
9387 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE
);
9391 /* Explicitly not on_tty() to avoid setting cached value.
9392 * This becomes relevant for piping output which might be
9394 original_stdout_is_tty
= isatty(STDOUT_FILENO
);
9396 r
= parse_argv(argc
, argv
);
9400 if (arg_action
!= ACTION_SYSTEMCTL
&& running_in_chroot() > 0) {
9402 log_info("Running in chroot, ignoring request.");
9407 /* systemctl_main() will print an error message for the bus
9408 * connection, but only if it needs to */
9410 switch (arg_action
) {
9412 case ACTION_SYSTEMCTL
:
9413 r
= systemctl_main(argc
, argv
);
9416 /* Legacy command aliases set arg_action. They provide some fallbacks,
9417 * e.g. to tell sysvinit to reboot after you have installed systemd
9421 case ACTION_POWEROFF
:
9427 case ACTION_RUNLEVEL2
:
9428 case ACTION_RUNLEVEL3
:
9429 case ACTION_RUNLEVEL4
:
9430 case ACTION_RUNLEVEL5
:
9432 r
= start_with_fallback();
9437 r
= reload_with_fallback();
9440 case ACTION_CANCEL_SHUTDOWN
:
9441 r
= logind_cancel_shutdown();
9444 case ACTION_RUNLEVEL
:
9445 r
= runlevel_main();
9449 case ACTION_SUSPEND
:
9450 case ACTION_HIBERNATE
:
9451 case ACTION_HYBRID_SLEEP
:
9452 case ACTION_SUSPEND_THEN_HIBERNATE
:
9453 case ACTION_EMERGENCY
:
9454 case ACTION_DEFAULT
:
9455 /* systemctl verbs with no equivalent in the legacy commands.
9456 * These cannot appear in arg_action. Fall through. */
9458 case _ACTION_INVALID
:
9460 assert_not_reached("Unknown action");
9466 /* Note that we return r here, not 0, so that we can implement the LSB-like return codes */
9470 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);