1 /* SPDX-License-Identifier: LGPL-2.1+ */
10 #include <sys/prctl.h>
11 #include <sys/reboot.h>
15 #include "sd-daemon.h"
19 #include "alloc-util.h"
21 #include "bus-common-errors.h"
22 #include "bus-error.h"
23 #include "bus-message.h"
24 #include "bus-unit-procs.h"
25 #include "bus-unit-util.h"
27 #include "bus-wait-for-jobs.h"
28 #include "bus-wait-for-units.h"
29 #include "cgroup-show.h"
30 #include "cgroup-util.h"
32 #include "cpu-set-util.h"
33 #include "dirent-util.h"
35 #include "efi-loader.h"
39 #include "exec-util.h"
40 #include "exit-status.h"
42 #include "format-table.h"
43 #include "format-util.h"
45 #include "glob-util.h"
46 #include "hexdecoct.h"
47 #include "hostname-util.h"
48 #include "in-addr-util.h"
52 #include "journal-util.h"
54 #include "locale-util.h"
56 #include "logs-show.h"
58 #include "main-func.h"
59 #include "memory-util.h"
61 #include "numa-util.h"
63 #include "parse-util.h"
64 #include "path-lookup.h"
65 #include "path-util.h"
66 #include "pretty-print.h"
67 #include "proc-cmdline.h"
68 #include "process-util.h"
69 #include "reboot-util.h"
70 #include "rlimit-util.h"
73 #include "signal-util.h"
74 #include "socket-util.h"
75 #include "sort-util.h"
76 #include "spawn-ask-password-agent.h"
77 #include "spawn-polkit-agent.h"
79 #include "stat-util.h"
80 #include "string-table.h"
82 #include "sysv-compat.h"
83 #include "terminal-util.h"
84 #include "tmpfile-util.h"
86 #include "unit-file.h"
87 #include "unit-name.h"
88 #include "user-util.h"
90 #include "utmp-wtmp.h"
94 static char **arg_types
= NULL
;
95 static char **arg_states
= NULL
;
96 static char **arg_properties
= NULL
;
97 static bool arg_all
= false;
98 static enum dependency
{
104 } arg_dependency
= DEPENDENCY_FORWARD
;
105 static const char *arg_job_mode
= "replace";
106 static UnitFileScope arg_scope
= UNIT_FILE_SYSTEM
;
107 static bool arg_wait
= false;
108 static bool arg_no_block
= false;
109 static bool arg_no_legend
= false;
110 static PagerFlags arg_pager_flags
= 0;
111 static bool arg_no_wtmp
= false;
112 static bool arg_no_sync
= false;
113 static bool arg_no_wall
= false;
114 static bool arg_no_reload
= false;
115 static bool arg_value
= false;
116 static bool arg_show_types
= false;
117 static bool arg_ignore_inhibitors
= false;
118 static bool arg_dry_run
= false;
119 static bool arg_quiet
= false;
120 static bool arg_full
= false;
121 static bool arg_recursive
= false;
122 static bool arg_with_dependencies
= false;
123 static bool arg_show_transaction
= false;
124 static int arg_force
= 0;
125 static bool arg_ask_password
= false;
126 static bool arg_runtime
= false;
127 static UnitFilePresetMode arg_preset_mode
= UNIT_FILE_PRESET_FULL
;
128 static char **arg_wall
= NULL
;
129 static const char *arg_kill_who
= NULL
;
130 static int arg_signal
= SIGTERM
;
131 static char *arg_root
= NULL
;
132 static usec_t arg_when
= 0;
143 ACTION_SUSPEND_THEN_HIBERNATE
,
154 ACTION_CANCEL_SHUTDOWN
,
157 } arg_action
= ACTION_SYSTEMCTL
;
158 static BusTransport arg_transport
= BUS_TRANSPORT_LOCAL
;
159 static const char *arg_host
= NULL
;
160 static unsigned arg_lines
= 10;
161 static OutputMode arg_output
= OUTPUT_SHORT
;
162 static bool arg_plain
= false;
163 static bool arg_firmware_setup
= false;
164 static usec_t arg_boot_loader_menu
= USEC_INFINITY
;
165 static const char *arg_boot_loader_entry
= NULL
;
166 static bool arg_now
= false;
167 static bool arg_jobs_before
= false;
168 static bool arg_jobs_after
= false;
169 static char **arg_clean_what
= NULL
;
171 /* This is a global cache that will be constructed on first use. */
172 static Hashmap
*cached_id_map
= NULL
;
173 static Hashmap
*cached_name_map
= NULL
;
175 STATIC_DESTRUCTOR_REGISTER(arg_wall
, strv_freep
);
176 STATIC_DESTRUCTOR_REGISTER(arg_root
, freep
);
177 STATIC_DESTRUCTOR_REGISTER(arg_types
, strv_freep
);
178 STATIC_DESTRUCTOR_REGISTER(arg_states
, strv_freep
);
179 STATIC_DESTRUCTOR_REGISTER(arg_properties
, strv_freep
);
180 STATIC_DESTRUCTOR_REGISTER(arg_clean_what
, strv_freep
);
181 STATIC_DESTRUCTOR_REGISTER(cached_id_map
, hashmap_freep
);
182 STATIC_DESTRUCTOR_REGISTER(cached_name_map
, hashmap_freep
);
184 static int daemon_reload(int argc
, char *argv
[], void* userdata
);
185 static int trivial_method(int argc
, char *argv
[], void *userdata
);
186 static int halt_now(enum action a
);
187 static int get_state_one_unit(sd_bus
*bus
, const char *name
, UnitActiveState
*active_state
);
189 static bool original_stdout_is_tty
;
191 typedef enum BusFocus
{
192 BUS_FULL
, /* The full bus indicated via --system or --user */
193 BUS_MANAGER
, /* The manager itself, possibly directly, possibly via the bus */
197 static sd_bus
*buses
[_BUS_FOCUS_MAX
] = {};
199 static UnitFileFlags
args_to_flags(void) {
200 return (arg_runtime
? UNIT_FILE_RUNTIME
: 0) |
201 (arg_force
? UNIT_FILE_FORCE
: 0);
204 static int acquire_bus(BusFocus focus
, sd_bus
**ret
) {
207 assert(focus
< _BUS_FOCUS_MAX
);
210 /* We only go directly to the manager, if we are using a local transport */
211 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
214 if (getenv_bool("SYSTEMCTL_FORCE_BUS") > 0)
220 user
= arg_scope
!= UNIT_FILE_SYSTEM
;
222 if (focus
== BUS_MANAGER
)
223 r
= bus_connect_transport_systemd(arg_transport
, arg_host
, user
, &buses
[focus
]);
225 r
= bus_connect_transport(arg_transport
, arg_host
, user
, &buses
[focus
]);
227 return log_error_errno(r
, "Failed to connect to bus: %m");
229 (void) sd_bus_set_allow_interactive_authorization(buses
[focus
], arg_ask_password
);
236 static void release_busses(void) {
239 for (w
= 0; w
< _BUS_FOCUS_MAX
; w
++)
240 buses
[w
] = sd_bus_flush_close_unref(buses
[w
]);
243 static void ask_password_agent_open_maybe(void) {
244 /* Open the password agent as a child process if necessary */
249 if (arg_scope
!= UNIT_FILE_SYSTEM
)
252 ask_password_agent_open_if_enabled(arg_transport
, arg_ask_password
);
255 static void polkit_agent_open_maybe(void) {
256 /* Open the polkit agent as a child process if necessary */
258 if (arg_scope
!= UNIT_FILE_SYSTEM
)
261 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
264 static OutputFlags
get_output_flags(void) {
266 arg_all
* OUTPUT_SHOW_ALL
|
267 (arg_full
|| !on_tty() || pager_have()) * OUTPUT_FULL_WIDTH
|
268 colors_enabled() * OUTPUT_COLOR
|
269 !arg_quiet
* OUTPUT_WARN_CUTOFF
;
272 static int translate_bus_error_to_exit_status(int r
, const sd_bus_error
*error
) {
275 if (!sd_bus_error_is_set(error
))
278 if (sd_bus_error_has_name(error
, SD_BUS_ERROR_ACCESS_DENIED
) ||
279 sd_bus_error_has_name(error
, BUS_ERROR_ONLY_BY_DEPENDENCY
) ||
280 sd_bus_error_has_name(error
, BUS_ERROR_NO_ISOLATION
) ||
281 sd_bus_error_has_name(error
, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE
))
282 return EXIT_NOPERMISSION
;
284 if (sd_bus_error_has_name(error
, BUS_ERROR_NO_SUCH_UNIT
))
285 return EXIT_NOTINSTALLED
;
287 if (sd_bus_error_has_name(error
, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE
) ||
288 sd_bus_error_has_name(error
, SD_BUS_ERROR_NOT_SUPPORTED
))
289 return EXIT_NOTIMPLEMENTED
;
291 if (sd_bus_error_has_name(error
, BUS_ERROR_LOAD_FAILED
))
292 return EXIT_NOTCONFIGURED
;
300 static bool install_client_side(void) {
301 /* Decides when to execute enable/disable/... operations
302 * client-side rather than server-side. */
304 if (running_in_chroot_or_offline())
307 if (sd_booted() <= 0)
310 if (!isempty(arg_root
))
313 if (arg_scope
== UNIT_FILE_GLOBAL
)
316 /* Unsupported environment variable, mostly for debugging purposes */
317 if (getenv_bool("SYSTEMCTL_INSTALL_CLIENT_SIDE") > 0)
323 static int compare_unit_info(const UnitInfo
*a
, const UnitInfo
*b
) {
327 /* First, order by machine */
328 if (!a
->machine
&& b
->machine
)
330 if (a
->machine
&& !b
->machine
)
332 if (a
->machine
&& b
->machine
) {
333 r
= strcasecmp(a
->machine
, b
->machine
);
338 /* Second, order by unit type */
339 d1
= strrchr(a
->id
, '.');
340 d2
= strrchr(b
->id
, '.');
342 r
= strcasecmp(d1
, d2
);
347 /* Third, order by name */
348 return strcasecmp(a
->id
, b
->id
);
351 static const char* unit_type_suffix(const char *name
) {
354 dot
= strrchr(name
, '.');
361 static bool output_show_unit(const UnitInfo
*u
, char **patterns
) {
364 if (!strv_fnmatch_or_empty(patterns
, u
->id
, FNM_NOESCAPE
))
367 if (arg_types
&& !strv_find(arg_types
, unit_type_suffix(u
->id
)))
373 /* Note that '--all' is not purely a state filter, but also a
374 * filter that hides units that "follow" other units (which is
375 * used for device units that appear under different names). */
376 if (!isempty(u
->following
))
379 if (!strv_isempty(arg_states
))
382 /* By default show all units except the ones in inactive
383 * state and with no pending job */
387 if (streq(u
->active_state
, "inactive"))
393 static int output_units_list(const UnitInfo
*unit_infos
, unsigned c
) {
394 _cleanup_(table_unrefp
) Table
*table
= NULL
;
399 table
= table_new("", "unit", "load", "active", "sub", "job", "description");
403 table_set_header(table
, !arg_no_legend
);
405 /* Hide the 'glyph' column when --no-legend is requested */
406 r
= table_hide_column_from_display(table
, 0);
408 return log_error_errno(r
, "Failed to hide column: %m");
411 table_set_width(table
, 0);
413 for (u
= unit_infos
; unit_infos
&& u
< unit_infos
+ c
; u
++) {
414 _cleanup_free_
char *j
= NULL
;
415 const char *on_underline
= "", *on_loaded
= "", *on_active
= "";
416 const char *on_circle
= "", *id
;
417 bool circle
= false, underline
= false;
419 if (u
+ 1 < unit_infos
+ c
&&
420 !streq(unit_type_suffix(u
->id
), unit_type_suffix((u
+ 1)->id
))) {
421 on_underline
= ansi_underline();
425 if (STR_IN_SET(u
->load_state
, "error", "not-found", "bad-setting", "masked") && !arg_plain
) {
426 on_circle
= ansi_highlight_yellow();
428 on_loaded
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
429 } else if (streq(u
->active_state
, "failed") && !arg_plain
) {
430 on_circle
= ansi_highlight_red();
432 on_active
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
434 on_active
= on_underline
;
435 on_loaded
= on_underline
;
439 j
= strjoin(u
->machine
, ":", u
->id
);
447 r
= table_add_many(table
,
448 TABLE_STRING
, circle
? special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
) : " ",
449 TABLE_SET_COLOR
, on_circle
,
451 TABLE_SET_COLOR
, on_active
,
452 TABLE_STRING
, u
->load_state
,
453 TABLE_SET_COLOR
, on_loaded
,
454 TABLE_STRING
, u
->active_state
,
455 TABLE_SET_COLOR
, on_active
,
456 TABLE_STRING
, u
->sub_state
,
457 TABLE_SET_COLOR
, on_active
,
458 TABLE_STRING
, u
->job_id
? u
->job_type
: "",
459 TABLE_SET_COLOR
, u
->job_id
? on_underline
: "",
460 TABLE_STRING
, u
->description
,
461 TABLE_SET_COLOR
, on_underline
);
463 return table_log_add_error(r
);
469 if (job_count
== 0) {
470 /* There's no data in the JOB column, so let's hide it */
471 r
= table_hide_column_from_display(table
, 5);
473 return log_error_errno(r
, "Failed to hide column: %m");
476 r
= table_print(table
, NULL
);
478 return log_error_errno(r
, "Failed to print the table: %m");
480 if (!arg_no_legend
) {
481 const char *on
, *off
;
482 size_t records
= table_get_rows(table
) - 1;
486 "LOAD = Reflects whether the unit definition was properly loaded.\n"
487 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
488 "SUB = The low-level unit activation state, values depend on unit type.");
489 puts(job_count
? "JOB = Pending job for the unit.\n" : "");
490 on
= ansi_highlight();
493 on
= ansi_highlight_red();
497 if (arg_all
|| strv_contains(arg_states
, "inactive"))
498 printf("%s%zu loaded units listed.%s\n"
499 "To show all installed unit files use 'systemctl list-unit-files'.\n",
501 else if (!arg_states
)
502 printf("%s%zu loaded units listed.%s Pass --all to see loaded but inactive units, too.\n"
503 "To show all installed unit files use 'systemctl list-unit-files'.\n",
506 printf("%zu loaded units listed.\n", records
);
512 static int get_unit_list(
516 UnitInfo
**unit_infos
,
518 sd_bus_message
**_reply
) {
520 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
521 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
522 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
526 bool fallback
= false;
532 r
= sd_bus_message_new_method_call(
535 "org.freedesktop.systemd1",
536 "/org/freedesktop/systemd1",
537 "org.freedesktop.systemd1.Manager",
538 "ListUnitsByPatterns");
540 return bus_log_create_error(r
);
542 r
= sd_bus_message_append_strv(m
, arg_states
);
544 return bus_log_create_error(r
);
546 r
= sd_bus_message_append_strv(m
, patterns
);
548 return bus_log_create_error(r
);
550 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
551 if (r
< 0 && (sd_bus_error_has_name(&error
, SD_BUS_ERROR_UNKNOWN_METHOD
) ||
552 sd_bus_error_has_name(&error
, SD_BUS_ERROR_ACCESS_DENIED
))) {
553 /* Fallback to legacy ListUnitsFiltered method */
555 log_debug_errno(r
, "Failed to list units: %s Falling back to ListUnitsFiltered method.", bus_error_message(&error
, r
));
556 m
= sd_bus_message_unref(m
);
557 sd_bus_error_free(&error
);
559 r
= sd_bus_message_new_method_call(
562 "org.freedesktop.systemd1",
563 "/org/freedesktop/systemd1",
564 "org.freedesktop.systemd1.Manager",
565 "ListUnitsFiltered");
567 return bus_log_create_error(r
);
569 r
= sd_bus_message_append_strv(m
, arg_states
);
571 return bus_log_create_error(r
);
573 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
576 return log_error_errno(r
, "Failed to list units: %s", bus_error_message(&error
, r
));
578 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssssouso)");
580 return bus_log_parse_error(r
);
582 while ((r
= bus_parse_unit_info(reply
, &u
)) > 0) {
585 if (!output_show_unit(&u
, fallback
? patterns
: NULL
))
588 if (!GREEDY_REALLOC(*unit_infos
, size
, c
+1))
591 (*unit_infos
)[c
++] = u
;
594 return bus_log_parse_error(r
);
596 r
= sd_bus_message_exit_container(reply
);
598 return bus_log_parse_error(r
);
600 *_reply
= TAKE_PTR(reply
);
605 static void message_set_freep(Set
**set
) {
606 set_free_with_destructor(*set
, sd_bus_message_unref
);
609 static int get_unit_list_recursive(
612 UnitInfo
**_unit_infos
,
616 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
617 _cleanup_(message_set_freep
) Set
*replies
;
618 sd_bus_message
*reply
;
626 replies
= set_new(NULL
);
630 c
= get_unit_list(bus
, NULL
, patterns
, &unit_infos
, 0, &reply
);
634 r
= set_put(replies
, reply
);
636 sd_bus_message_unref(reply
);
641 _cleanup_strv_free_
char **machines
= NULL
;
644 r
= sd_get_machine_names(&machines
);
646 return log_error_errno(r
, "Failed to get machine names: %m");
648 STRV_FOREACH(i
, machines
) {
649 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*container
= NULL
;
652 r
= sd_bus_open_system_machine(&container
, *i
);
654 log_warning_errno(r
, "Failed to connect to container %s, ignoring: %m", *i
);
658 k
= get_unit_list(container
, *i
, patterns
, &unit_infos
, c
, &reply
);
664 r
= set_put(replies
, reply
);
666 sd_bus_message_unref(reply
);
671 *_machines
= TAKE_PTR(machines
);
675 *_unit_infos
= TAKE_PTR(unit_infos
);
676 *_replies
= TAKE_PTR(replies
);
681 static int expand_names(sd_bus
*bus
, char **names
, const char* suffix
, char ***ret
, bool *ret_expanded
) {
682 _cleanup_strv_free_
char **mangled
= NULL
, **globs
= NULL
;
689 STRV_FOREACH(name
, names
) {
691 UnitNameMangle options
= UNIT_NAME_MANGLE_GLOB
| (arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
);
693 r
= unit_name_mangle_with_suffix(*name
, NULL
, options
, suffix
?: ".service", &t
);
695 return log_error_errno(r
, "Failed to mangle name: %m");
697 if (string_is_glob(t
))
698 r
= strv_consume(&globs
, t
);
700 r
= strv_consume(&mangled
, t
);
705 /* Query the manager only if any of the names are a glob, since
706 * this is fairly expensive */
707 bool expanded
= !strv_isempty(globs
);
709 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
710 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
713 r
= get_unit_list(bus
, NULL
, globs
, &unit_infos
, 0, &reply
);
717 n
= strv_length(mangled
);
720 for (i
= 0; i
< r
; i
++) {
721 if (!GREEDY_REALLOC(mangled
, allocated
, n
+2))
724 mangled
[n
] = strdup(unit_infos
[i
].id
);
733 *ret_expanded
= expanded
;
735 *ret
= TAKE_PTR(mangled
);
739 static int list_dependencies_get_dependencies(sd_bus
*bus
, const char *name
, char ***ret
) {
740 _cleanup_strv_free_
char **deps
= NULL
;
742 static const struct bus_properties_map map
[_DEPENDENCY_MAX
][6] = {
743 [DEPENDENCY_FORWARD
] = {
744 { "Requires", "as", NULL
, 0 },
745 { "Requisite", "as", NULL
, 0 },
746 { "Wants", "as", NULL
, 0 },
747 { "ConsistsOf", "as", NULL
, 0 },
748 { "BindsTo", "as", NULL
, 0 },
751 [DEPENDENCY_REVERSE
] = {
752 { "RequiredBy", "as", NULL
, 0 },
753 { "RequisiteOf", "as", NULL
, 0 },
754 { "WantedBy", "as", NULL
, 0 },
755 { "PartOf", "as", NULL
, 0 },
756 { "BoundBy", "as", NULL
, 0 },
759 [DEPENDENCY_AFTER
] = {
760 { "After", "as", NULL
, 0 },
763 [DEPENDENCY_BEFORE
] = {
764 { "Before", "as", NULL
, 0 },
769 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
770 _cleanup_free_
char *dbus_path
= NULL
;
777 dbus_path
= unit_dbus_path_from_name(name
);
781 r
= bus_map_all_properties(bus
,
782 "org.freedesktop.systemd1",
790 return log_error_errno(r
, "Failed to get properties of %s: %s", name
, bus_error_message(&error
, r
));
792 strv_uniq(deps
); /* Sometimes a unit might have multiple deps on the other unit,
793 * but we still want to show it just once. */
794 *ret
= TAKE_PTR(deps
);
799 static int append_unit_dependencies(sd_bus
*bus
, char **names
, char ***ret
) {
800 _cleanup_strv_free_
char **with_deps
= NULL
;
806 STRV_FOREACH(name
, names
) {
807 _cleanup_strv_free_
char **deps
= NULL
;
809 if (strv_extend(&with_deps
, *name
) < 0)
812 (void) list_dependencies_get_dependencies(bus
, *name
, &deps
);
814 if (strv_extend_strv(&with_deps
, deps
, true) < 0)
818 *ret
= TAKE_PTR(with_deps
);
823 static int maybe_extend_with_unit_dependencies(sd_bus
*bus
, char ***list
) {
827 if (arg_with_dependencies
) {
829 _cleanup_strv_free_
char **list_with_deps
= NULL
;
831 r
= append_unit_dependencies(bus
, *list
, &list_with_deps
);
833 return log_error_errno(r
, "Failed to append unit dependencies: %m");
836 *list
= TAKE_PTR(list_with_deps
);
842 static int list_units(int argc
, char *argv
[], void *userdata
) {
843 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
844 _cleanup_(message_set_freep
) Set
*replies
= NULL
;
845 _cleanup_strv_free_
char **machines
= NULL
;
849 r
= acquire_bus(BUS_MANAGER
, &bus
);
853 (void) pager_open(arg_pager_flags
);
855 if (arg_with_dependencies
) {
856 _cleanup_strv_free_
char **names
= NULL
;
858 r
= append_unit_dependencies(bus
, strv_skip(argv
, 1), &names
);
862 r
= get_unit_list_recursive(bus
, names
, &unit_infos
, &replies
, &machines
);
866 r
= get_unit_list_recursive(bus
, strv_skip(argv
, 1), &unit_infos
, &replies
, &machines
);
871 typesafe_qsort(unit_infos
, r
, compare_unit_info
);
872 return output_units_list(unit_infos
, r
);
875 static int get_triggered_units(
880 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
887 r
= sd_bus_get_property_strv(
889 "org.freedesktop.systemd1",
891 "org.freedesktop.systemd1.Unit",
896 return log_error_errno(r
, "Failed to determine triggers: %s", bus_error_message(&error
, r
));
901 static int get_listening(
903 const char* unit_path
,
906 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
907 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
908 const char *type
, *path
;
911 r
= sd_bus_get_property(
913 "org.freedesktop.systemd1",
915 "org.freedesktop.systemd1.Socket",
921 return log_error_errno(r
, "Failed to get list of listening sockets: %s", bus_error_message(&error
, r
));
923 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ss)");
925 return bus_log_parse_error(r
);
927 while ((r
= sd_bus_message_read(reply
, "(ss)", &type
, &path
)) > 0) {
929 r
= strv_extend(listening
, type
);
933 r
= strv_extend(listening
, path
);
940 return bus_log_parse_error(r
);
942 r
= sd_bus_message_exit_container(reply
);
944 return bus_log_parse_error(r
);
956 /* Note: triggered is a list here, although it almost certainly
957 * will always be one unit. Nevertheless, dbus API allows for multiple
958 * values, so let's follow that. */
961 /* The strv above is shared. free is set only in the first one. */
965 static int socket_info_compare(const struct socket_info
*a
, const struct socket_info
*b
) {
971 if (!a
->machine
&& b
->machine
)
973 if (a
->machine
&& !b
->machine
)
975 if (a
->machine
&& b
->machine
) {
976 r
= strcasecmp(a
->machine
, b
->machine
);
981 r
= strcmp(a
->path
, b
->path
);
983 r
= strcmp(a
->type
, b
->type
);
988 static int output_sockets_list(struct socket_info
*socket_infos
, unsigned cs
) {
989 _cleanup_(table_unrefp
) Table
*table
= NULL
;
990 struct socket_info
*s
;
991 const char *on
, *off
;
994 table
= table_new("listen", "type", "units", "activates");
998 if (!arg_show_types
) {
999 /* Hide the second (TYPE) column */
1000 r
= table_set_display(table
, (size_t) 0, (size_t) 2, (size_t) 3, (size_t) -1);
1002 return log_error_errno(r
, "Failed to set columns to display: %m");
1005 table_set_header(table
, !arg_no_legend
);
1007 table_set_width(table
, 0);
1010 for (s
= socket_infos
; s
< socket_infos
+ cs
; s
++) {
1011 _cleanup_free_
char *j
= NULL
, *activates
= NULL
;
1015 j
= strjoin(s
->machine
, ":", s
->path
);
1022 activates
= strv_join(s
->triggered
, ", ");
1026 r
= table_add_many(table
,
1028 TABLE_STRING
, s
->type
,
1029 TABLE_STRING
, s
->id
,
1030 TABLE_STRING
, activates
);
1032 return table_log_add_error(r
);
1035 on
= ansi_highlight();
1036 off
= ansi_normal();
1038 on
= ansi_highlight_red();
1039 off
= ansi_normal();
1042 r
= table_print(table
, NULL
);
1044 return log_error_errno(r
, "Failed to print the table: %m");
1046 if (!arg_no_legend
) {
1047 printf("\n%s%u sockets listed.%s\n", on
, cs
, off
);
1049 printf("Pass --all to see loaded but inactive sockets, too.\n");
1055 static int list_sockets(int argc
, char *argv
[], void *userdata
) {
1056 _cleanup_(message_set_freep
) Set
*replies
= NULL
;
1057 _cleanup_strv_free_
char **machines
= NULL
;
1058 _cleanup_strv_free_
char **sockets_with_suffix
= NULL
;
1059 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
1060 _cleanup_free_
struct socket_info
*socket_infos
= NULL
;
1062 struct socket_info
*s
;
1068 r
= acquire_bus(BUS_MANAGER
, &bus
);
1072 (void) pager_open(arg_pager_flags
);
1074 r
= expand_names(bus
, strv_skip(argv
, 1), ".socket", &sockets_with_suffix
, NULL
);
1078 if (argc
== 1 || sockets_with_suffix
) {
1079 n
= get_unit_list_recursive(bus
, sockets_with_suffix
, &unit_infos
, &replies
, &machines
);
1083 for (u
= unit_infos
; u
< unit_infos
+ n
; u
++) {
1084 _cleanup_strv_free_
char **listening
= NULL
, **triggered
= NULL
;
1087 if (!endswith(u
->id
, ".socket"))
1090 r
= get_triggered_units(bus
, u
->unit_path
, &triggered
);
1094 c
= get_listening(bus
, u
->unit_path
, &listening
);
1100 if (!GREEDY_REALLOC(socket_infos
, size
, cs
+ c
)) {
1105 for (i
= 0; i
< c
; i
++)
1106 socket_infos
[cs
+ i
] = (struct socket_info
) {
1107 .machine
= u
->machine
,
1109 .type
= listening
[i
*2],
1110 .path
= listening
[i
*2 + 1],
1111 .triggered
= triggered
,
1112 .own_triggered
= i
==0,
1115 /* from this point on we will cleanup those socket_infos */
1118 listening
= triggered
= NULL
; /* avoid cleanup */
1121 typesafe_qsort(socket_infos
, cs
, socket_info_compare
);
1124 output_sockets_list(socket_infos
, cs
);
1127 assert(cs
== 0 || socket_infos
);
1128 for (s
= socket_infos
; s
< socket_infos
+ cs
; s
++) {
1131 if (s
->own_triggered
)
1132 strv_free(s
->triggered
);
1138 static int get_next_elapse(
1141 dual_timestamp
*next
) {
1143 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1151 r
= sd_bus_get_property_trivial(
1153 "org.freedesktop.systemd1",
1155 "org.freedesktop.systemd1.Timer",
1156 "NextElapseUSecMonotonic",
1161 return log_error_errno(r
, "Failed to get next elapse time: %s", bus_error_message(&error
, r
));
1163 r
= sd_bus_get_property_trivial(
1165 "org.freedesktop.systemd1",
1167 "org.freedesktop.systemd1.Timer",
1168 "NextElapseUSecRealtime",
1173 return log_error_errno(r
, "Failed to get next elapse time: %s", bus_error_message(&error
, r
));
1179 static int get_last_trigger(
1184 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1191 r
= sd_bus_get_property_trivial(
1193 "org.freedesktop.systemd1",
1195 "org.freedesktop.systemd1.Timer",
1201 return log_error_errno(r
, "Failed to get last trigger time: %s", bus_error_message(&error
, r
));
1207 const char* machine
;
1210 usec_t last_trigger
;
1214 static int timer_info_compare(const struct timer_info
*a
, const struct timer_info
*b
) {
1220 if (!a
->machine
&& b
->machine
)
1222 if (a
->machine
&& !b
->machine
)
1224 if (a
->machine
&& b
->machine
) {
1225 r
= strcasecmp(a
->machine
, b
->machine
);
1230 r
= CMP(a
->next_elapse
, b
->next_elapse
);
1234 return strcmp(a
->id
, b
->id
);
1237 static int output_timers_list(struct timer_info
*timer_infos
, unsigned n
) {
1238 _cleanup_(table_unrefp
) Table
*table
= NULL
;
1239 struct timer_info
*t
;
1240 const char *on
, *off
;
1243 assert(timer_infos
|| n
== 0);
1245 table
= table_new("next", "left", "last", "passed", "unit", "activates");
1249 table_set_header(table
, !arg_no_legend
);
1251 table_set_width(table
, 0);
1254 for (t
= timer_infos
; t
< timer_infos
+ n
; t
++) {
1255 _cleanup_free_
char *j
= NULL
, *activates
= NULL
;
1259 j
= strjoin(t
->machine
, ":", t
->id
);
1266 activates
= strv_join(t
->triggered
, ", ");
1270 r
= table_add_many(table
,
1271 TABLE_TIMESTAMP
, t
->next_elapse
,
1272 TABLE_TIMESTAMP_RELATIVE
, t
->next_elapse
,
1273 TABLE_TIMESTAMP
, t
->last_trigger
,
1274 TABLE_TIMESTAMP_RELATIVE
, t
->last_trigger
,
1276 TABLE_STRING
, activates
);
1278 return table_log_add_error(r
);
1281 on
= ansi_highlight();
1282 off
= ansi_normal();
1284 on
= ansi_highlight_red();
1285 off
= ansi_normal();
1288 r
= table_print(table
, NULL
);
1290 return log_error_errno(r
, "Failed to print the table: %m");
1292 if (!arg_no_legend
) {
1293 printf("\n%s%u timers listed.%s\n", on
, n
, off
);
1295 printf("Pass --all to see loaded but inactive timers, too.\n");
1301 static usec_t
calc_next_elapse(dual_timestamp
*nw
, dual_timestamp
*next
) {
1307 if (timestamp_is_set(next
->monotonic
)) {
1310 if (next
->monotonic
> nw
->monotonic
)
1311 converted
= nw
->realtime
+ (next
->monotonic
- nw
->monotonic
);
1313 converted
= nw
->realtime
- (nw
->monotonic
- next
->monotonic
);
1315 if (timestamp_is_set(next
->realtime
))
1316 next_elapse
= MIN(converted
, next
->realtime
);
1318 next_elapse
= converted
;
1321 next_elapse
= next
->realtime
;
1326 static int list_timers(int argc
, char *argv
[], void *userdata
) {
1327 _cleanup_(message_set_freep
) Set
*replies
= NULL
;
1328 _cleanup_strv_free_
char **machines
= NULL
;
1329 _cleanup_strv_free_
char **timers_with_suffix
= NULL
;
1330 _cleanup_free_
struct timer_info
*timer_infos
= NULL
;
1331 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
1332 struct timer_info
*t
;
1340 r
= acquire_bus(BUS_MANAGER
, &bus
);
1344 (void) pager_open(arg_pager_flags
);
1346 r
= expand_names(bus
, strv_skip(argv
, 1), ".timer", &timers_with_suffix
, NULL
);
1350 if (argc
== 1 || timers_with_suffix
) {
1351 n
= get_unit_list_recursive(bus
, timers_with_suffix
, &unit_infos
, &replies
, &machines
);
1355 dual_timestamp_get(&nw
);
1357 for (u
= unit_infos
; u
< unit_infos
+ n
; u
++) {
1358 _cleanup_strv_free_
char **triggered
= NULL
;
1359 dual_timestamp next
= DUAL_TIMESTAMP_NULL
;
1362 if (!endswith(u
->id
, ".timer"))
1365 r
= get_triggered_units(bus
, u
->unit_path
, &triggered
);
1369 r
= get_next_elapse(bus
, u
->unit_path
, &next
);
1373 get_last_trigger(bus
, u
->unit_path
, &last
);
1375 if (!GREEDY_REALLOC(timer_infos
, size
, c
+1)) {
1380 m
= calc_next_elapse(&nw
, &next
);
1382 timer_infos
[c
++] = (struct timer_info
) {
1383 .machine
= u
->machine
,
1386 .last_trigger
= last
,
1387 .triggered
= TAKE_PTR(triggered
),
1391 typesafe_qsort(timer_infos
, c
, timer_info_compare
);
1394 output_timers_list(timer_infos
, c
);
1397 for (t
= timer_infos
; t
< timer_infos
+ c
; t
++)
1398 strv_free(t
->triggered
);
1403 static int compare_unit_file_list(const UnitFileList
*a
, const UnitFileList
*b
) {
1404 const char *d1
, *d2
;
1406 d1
= strrchr(a
->path
, '.');
1407 d2
= strrchr(b
->path
, '.');
1412 r
= strcasecmp(d1
, d2
);
1417 return strcasecmp(basename(a
->path
), basename(b
->path
));
1420 static bool output_show_unit_file(const UnitFileList
*u
, char **states
, char **patterns
) {
1423 if (!strv_fnmatch_or_empty(patterns
, basename(u
->path
), FNM_NOESCAPE
))
1426 if (!strv_isempty(arg_types
)) {
1429 dot
= strrchr(u
->path
, '.');
1433 if (!strv_find(arg_types
, dot
+1))
1437 if (!strv_isempty(states
) &&
1438 !strv_find(states
, unit_file_state_to_string(u
->state
)))
1444 static int output_unit_file_list(const UnitFileList
*units
, unsigned c
) {
1445 _cleanup_(table_unrefp
) Table
*table
= NULL
;
1446 const UnitFileList
*u
;
1449 table
= table_new("unit file", "state", "vendor preset");
1453 table_set_header(table
, !arg_no_legend
);
1455 table_set_width(table
, 0);
1457 for (u
= units
; u
< units
+ c
; u
++) {
1458 const char *on_underline
= NULL
, *on_unit_color
= NULL
, *id
;
1459 const char *on_preset_color
= NULL
, *unit_preset_str
;
1462 underline
= u
+ 1 < units
+ c
&&
1463 !streq(unit_type_suffix(u
->path
), unit_type_suffix((u
+ 1)->path
));
1466 on_underline
= ansi_underline();
1468 if (IN_SET(u
->state
,
1470 UNIT_FILE_MASKED_RUNTIME
,
1473 on_unit_color
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
1474 else if (u
->state
== UNIT_FILE_ENABLED
)
1475 on_unit_color
= underline
? ansi_highlight_green_underline() : ansi_highlight_green();
1477 on_unit_color
= on_underline
;
1479 id
= basename(u
->path
);
1481 r
= unit_file_query_preset(arg_scope
, arg_root
, id
);
1483 unit_preset_str
= "n/a";
1484 on_preset_color
= underline
? on_underline
: ansi_normal();
1485 } else if (r
== 0) {
1486 unit_preset_str
= "disabled";
1487 on_preset_color
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
1489 unit_preset_str
= "enabled";
1490 on_preset_color
= underline
? ansi_highlight_green_underline() : ansi_highlight_green();
1493 r
= table_add_many(table
,
1495 TABLE_SET_COLOR
, strempty(on_underline
),
1496 TABLE_STRING
, unit_file_state_to_string(u
->state
),
1497 TABLE_SET_COLOR
, strempty(on_unit_color
),
1498 TABLE_STRING
, unit_preset_str
,
1499 TABLE_SET_COLOR
, strempty(on_preset_color
));
1501 return table_log_add_error(r
);
1504 r
= table_print(table
, NULL
);
1506 return log_error_errno(r
, "Failed to print the table: %m");
1509 printf("\n%u unit files listed.\n", c
);
1514 static int list_unit_files(int argc
, char *argv
[], void *userdata
) {
1515 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1516 _cleanup_free_ UnitFileList
*units
= NULL
;
1523 bool fallback
= false;
1525 if (install_client_side()) {
1531 h
= hashmap_new(&string_hash_ops
);
1535 r
= unit_file_get_list(arg_scope
, arg_root
, h
, arg_states
, strv_skip(argv
, 1));
1537 unit_file_list_free(h
);
1538 return log_error_errno(r
, "Failed to get unit file list: %m");
1541 n_units
= hashmap_size(h
);
1543 units
= new(UnitFileList
, n_units
?: 1); /* avoid malloc(0) */
1545 unit_file_list_free(h
);
1549 HASHMAP_FOREACH(u
, h
, i
) {
1550 if (!output_show_unit_file(u
, NULL
, NULL
))
1557 assert(c
<= n_units
);
1562 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
1563 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1566 r
= acquire_bus(BUS_MANAGER
, &bus
);
1570 r
= sd_bus_message_new_method_call(
1573 "org.freedesktop.systemd1",
1574 "/org/freedesktop/systemd1",
1575 "org.freedesktop.systemd1.Manager",
1576 "ListUnitFilesByPatterns");
1578 return bus_log_create_error(r
);
1580 r
= sd_bus_message_append_strv(m
, arg_states
);
1582 return bus_log_create_error(r
);
1584 if (arg_with_dependencies
) {
1585 _cleanup_strv_free_
char **names_with_deps
= NULL
;
1587 r
= append_unit_dependencies(bus
, strv_skip(argv
, 1), &names_with_deps
);
1589 return log_error_errno(r
, "Failed to append unit dependencies: %m");
1591 r
= sd_bus_message_append_strv(m
, names_with_deps
);
1593 return bus_log_create_error(r
);
1595 r
= sd_bus_message_append_strv(m
, strv_skip(argv
, 1));
1597 return bus_log_create_error(r
);
1600 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1601 if (r
< 0 && sd_bus_error_has_name(&error
, SD_BUS_ERROR_UNKNOWN_METHOD
)) {
1602 /* Fallback to legacy ListUnitFiles method */
1604 log_debug_errno(r
, "Failed to list unit files: %s Falling back to ListUnitsFiles method.", bus_error_message(&error
, r
));
1605 m
= sd_bus_message_unref(m
);
1606 sd_bus_error_free(&error
);
1608 r
= sd_bus_message_new_method_call(
1611 "org.freedesktop.systemd1",
1612 "/org/freedesktop/systemd1",
1613 "org.freedesktop.systemd1.Manager",
1616 return bus_log_create_error(r
);
1618 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1621 return log_error_errno(r
, "Failed to list unit files: %s", bus_error_message(&error
, r
));
1623 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ss)");
1625 return bus_log_parse_error(r
);
1627 while ((r
= sd_bus_message_read(reply
, "(ss)", &path
, &state
)) > 0) {
1629 if (!GREEDY_REALLOC(units
, size
, c
+ 1))
1632 units
[c
] = (struct UnitFileList
) {
1634 unit_file_state_from_string(state
)
1637 if (output_show_unit_file(&units
[c
],
1638 fallback
? arg_states
: NULL
,
1639 fallback
? strv_skip(argv
, 1) : NULL
))
1644 return bus_log_parse_error(r
);
1646 r
= sd_bus_message_exit_container(reply
);
1648 return bus_log_parse_error(r
);
1651 (void) pager_open(arg_pager_flags
);
1653 typesafe_qsort(units
, c
, compare_unit_file_list
);
1654 r
= output_unit_file_list(units
, c
);
1658 if (install_client_side())
1659 for (unit
= units
; unit
< units
+ c
; unit
++)
1665 static int list_dependencies_print(const char *name
, int level
, unsigned branches
, bool last
) {
1666 _cleanup_free_
char *n
= NULL
;
1667 size_t max_len
= MAX(columns(),20u);
1673 for (i
= level
- 1; i
>= 0; i
--) {
1675 if (len
> max_len
- 3 && !arg_full
) {
1676 printf("%s...\n",max_len
% 2 ? "" : " ");
1679 printf("%s", special_glyph(branches
& (1 << i
) ? SPECIAL_GLYPH_TREE_VERTICAL
: SPECIAL_GLYPH_TREE_SPACE
));
1683 if (len
> max_len
- 3 && !arg_full
) {
1684 printf("%s...\n",max_len
% 2 ? "" : " ");
1688 printf("%s", special_glyph(last
? SPECIAL_GLYPH_TREE_RIGHT
: SPECIAL_GLYPH_TREE_BRANCH
));
1692 printf("%s\n", name
);
1696 n
= ellipsize(name
, max_len
-len
, 100);
1704 static int list_dependencies_compare(char * const *a
, char * const *b
) {
1705 if (unit_name_to_type(*a
) == UNIT_TARGET
&& unit_name_to_type(*b
) != UNIT_TARGET
)
1707 if (unit_name_to_type(*a
) != UNIT_TARGET
&& unit_name_to_type(*b
) == UNIT_TARGET
)
1710 return strcasecmp(*a
, *b
);
1713 static int list_dependencies_one(
1718 unsigned branches
) {
1720 _cleanup_strv_free_
char **deps
= NULL
;
1728 r
= strv_extend(units
, name
);
1732 r
= list_dependencies_get_dependencies(bus
, name
, &deps
);
1736 typesafe_qsort(deps
, strv_length(deps
), list_dependencies_compare
);
1738 STRV_FOREACH(c
, deps
) {
1739 if (strv_contains(*units
, *c
)) {
1742 r
= list_dependencies_print("...", level
+ 1, (branches
<< 1) | (c
[1] == NULL
? 0 : 1), 1);
1752 UnitActiveState active_state
= _UNIT_ACTIVE_STATE_INVALID
;
1755 (void) get_state_one_unit(bus
, *c
, &active_state
);
1757 switch (active_state
) {
1759 case UNIT_RELOADING
:
1760 case UNIT_ACTIVATING
:
1761 on
= ansi_highlight_green();
1765 case UNIT_DEACTIVATING
:
1770 on
= ansi_highlight_red();
1774 printf("%s%s%s ", on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), ansi_normal());
1777 r
= list_dependencies_print(*c
, level
, branches
, c
[1] == NULL
);
1781 if (arg_all
|| unit_name_to_type(*c
) == UNIT_TARGET
) {
1782 r
= list_dependencies_one(bus
, *c
, level
+ 1, units
, (branches
<< 1) | (c
[1] == NULL
? 0 : 1));
1789 strv_remove(*units
, name
);
1794 static int list_dependencies(int argc
, char *argv
[], void *userdata
) {
1795 _cleanup_strv_free_
char **units
= NULL
, **done
= NULL
;
1796 char **u
, **patterns
;
1800 r
= acquire_bus(BUS_MANAGER
, &bus
);
1804 patterns
= strv_skip(argv
, 1);
1805 if (strv_isempty(patterns
)) {
1806 units
= strv_new(SPECIAL_DEFAULT_TARGET
);
1810 r
= expand_names(bus
, patterns
, NULL
, &units
, NULL
);
1812 return log_error_errno(r
, "Failed to expand names: %m");
1815 (void) pager_open(arg_pager_flags
);
1817 STRV_FOREACH(u
, units
) {
1822 r
= list_dependencies_one(bus
, *u
, 0, &done
, 0);
1830 struct machine_info
{
1834 char *control_group
;
1835 uint32_t n_failed_units
;
1840 static const struct bus_properties_map machine_info_property_map
[] = {
1841 { "SystemState", "s", NULL
, offsetof(struct machine_info
, state
) },
1842 { "NJobs", "u", NULL
, offsetof(struct machine_info
, n_jobs
) },
1843 { "NFailedUnits", "u", NULL
, offsetof(struct machine_info
, n_failed_units
) },
1844 { "ControlGroup", "s", NULL
, offsetof(struct machine_info
, control_group
) },
1845 { "UserspaceTimestamp", "t", NULL
, offsetof(struct machine_info
, timestamp
) },
1849 static void machine_info_clear(struct machine_info
*info
) {
1854 free(info
->control_group
);
1858 static void free_machines_list(struct machine_info
*machine_infos
, int n
) {
1864 for (i
= 0; i
< n
; i
++)
1865 machine_info_clear(&machine_infos
[i
]);
1867 free(machine_infos
);
1870 static int compare_machine_info(const struct machine_info
*a
, const struct machine_info
*b
) {
1873 r
= CMP(b
->is_host
, a
->is_host
);
1877 return strcasecmp(a
->name
, b
->name
);
1880 static int get_machine_properties(sd_bus
*bus
, struct machine_info
*mi
) {
1881 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*container
= NULL
;
1887 r
= sd_bus_open_system_machine(&container
, mi
->name
);
1894 r
= bus_map_all_properties(
1896 "org.freedesktop.systemd1",
1897 "/org/freedesktop/systemd1",
1898 machine_info_property_map
,
1909 static bool output_show_machine(const char *name
, char **patterns
) {
1910 return strv_fnmatch_or_empty(patterns
, name
, FNM_NOESCAPE
);
1913 static int get_machine_list(
1915 struct machine_info
**_machine_infos
,
1918 struct machine_info
*machine_infos
= NULL
;
1919 _cleanup_strv_free_
char **m
= NULL
;
1920 _cleanup_free_
char *hn
= NULL
;
1925 hn
= gethostname_malloc();
1929 if (output_show_machine(hn
, patterns
)) {
1930 if (!GREEDY_REALLOC0(machine_infos
, sz
, c
+1))
1933 machine_infos
[c
].is_host
= true;
1934 machine_infos
[c
].name
= TAKE_PTR(hn
);
1936 (void) get_machine_properties(bus
, &machine_infos
[c
]);
1940 r
= sd_get_machine_names(&m
);
1942 return log_error_errno(r
, "Failed to get machine list: %m");
1944 STRV_FOREACH(i
, m
) {
1945 _cleanup_free_
char *class = NULL
;
1947 if (!output_show_machine(*i
, patterns
))
1950 sd_machine_get_class(*i
, &class);
1951 if (!streq_ptr(class, "container"))
1954 if (!GREEDY_REALLOC0(machine_infos
, sz
, c
+1)) {
1955 free_machines_list(machine_infos
, c
);
1959 machine_infos
[c
].is_host
= false;
1960 machine_infos
[c
].name
= strdup(*i
);
1961 if (!machine_infos
[c
].name
) {
1962 free_machines_list(machine_infos
, c
);
1966 (void) get_machine_properties(NULL
, &machine_infos
[c
]);
1970 *_machine_infos
= machine_infos
;
1974 static int output_machines_list(struct machine_info
*machine_infos
, unsigned n
) {
1975 _cleanup_(table_unrefp
) Table
*table
= NULL
;
1976 struct machine_info
*m
;
1977 bool state_missing
= false;
1980 assert(machine_infos
|| n
== 0);
1982 table
= table_new("", "name", "state", "failed", "jobs");
1986 table_set_header(table
, !arg_no_legend
);
1987 if (arg_no_legend
) {
1988 /* Hide the 'glyph' column when --no-legend is requested */
1989 r
= table_hide_column_from_display(table
, 0);
1991 return log_error_errno(r
, "Failed to hide column: %m");
1994 table_set_width(table
, 0);
1996 for (m
= machine_infos
; m
< machine_infos
+ n
; m
++) {
1997 _cleanup_free_
char *mname
= NULL
;
1998 const char *on_state
= "", *on_failed
= "";
1999 bool circle
= false;
2001 if (streq_ptr(m
->state
, "degraded")) {
2002 on_state
= ansi_highlight_red();
2004 } else if (!streq_ptr(m
->state
, "running")) {
2005 on_state
= ansi_highlight_yellow();
2009 if (m
->n_failed_units
> 0)
2010 on_failed
= ansi_highlight_red();
2015 state_missing
= true;
2018 mname
= strjoin(strna(m
->name
), " (host)");
2020 r
= table_add_many(table
,
2021 TABLE_STRING
, circle
? special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
) : " ",
2022 TABLE_SET_COLOR
, on_state
,
2023 TABLE_STRING
, m
->is_host
? mname
: strna(m
->name
),
2024 TABLE_STRING
, strna(m
->state
),
2025 TABLE_SET_COLOR
, on_state
,
2026 TABLE_UINT32
, m
->n_failed_units
,
2027 TABLE_SET_COLOR
, on_failed
,
2028 TABLE_UINT32
, m
->n_jobs
);
2030 return table_log_add_error(r
);
2033 r
= table_print(table
, NULL
);
2035 return log_error_errno(r
, "Failed to print the table: %m");
2037 if (!arg_no_legend
) {
2039 if (state_missing
&& geteuid() != 0)
2040 printf("Notice: some information only available to privileged users was not shown.\n");
2041 printf("%u machines listed.\n", n
);
2047 static int list_machines(int argc
, char *argv
[], void *userdata
) {
2048 struct machine_info
*machine_infos
= NULL
;
2052 r
= acquire_bus(BUS_MANAGER
, &bus
);
2056 r
= get_machine_list(bus
, &machine_infos
, strv_skip(argv
, 1));
2060 (void) pager_open(arg_pager_flags
);
2062 typesafe_qsort(machine_infos
, r
, compare_machine_info
);
2063 rc
= output_machines_list(machine_infos
, r
);
2064 free_machines_list(machine_infos
, r
);
2069 static int get_default(int argc
, char *argv
[], void *userdata
) {
2070 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2071 _cleanup_free_
char *_path
= NULL
;
2075 if (install_client_side()) {
2076 r
= unit_file_get_default(arg_scope
, arg_root
, &_path
);
2078 return log_error_errno(r
, "Failed to get default target: %m");
2083 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2086 r
= acquire_bus(BUS_MANAGER
, &bus
);
2090 r
= sd_bus_call_method(
2092 "org.freedesktop.systemd1",
2093 "/org/freedesktop/systemd1",
2094 "org.freedesktop.systemd1.Manager",
2100 return log_error_errno(r
, "Failed to get default target: %s", bus_error_message(&error
, r
));
2102 r
= sd_bus_message_read(reply
, "s", &path
);
2104 return bus_log_parse_error(r
);
2108 printf("%s\n", path
);
2113 static int set_default(int argc
, char *argv
[], void *userdata
) {
2114 _cleanup_free_
char *unit
= NULL
;
2115 UnitFileChange
*changes
= NULL
;
2116 size_t n_changes
= 0;
2122 r
= unit_name_mangle_with_suffix(argv
[1], "set-default",
2123 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
2126 return log_error_errno(r
, "Failed to mangle unit name: %m");
2128 if (install_client_side()) {
2129 r
= unit_file_set_default(arg_scope
, UNIT_FILE_FORCE
, arg_root
, unit
, &changes
, &n_changes
);
2130 unit_file_dump_changes(r
, "set default", changes
, n_changes
, arg_quiet
);
2135 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2136 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2139 polkit_agent_open_maybe();
2141 r
= acquire_bus(BUS_MANAGER
, &bus
);
2145 r
= sd_bus_call_method(
2147 "org.freedesktop.systemd1",
2148 "/org/freedesktop/systemd1",
2149 "org.freedesktop.systemd1.Manager",
2155 return log_error_errno(r
, "Failed to set default target: %s", bus_error_message(&error
, r
));
2157 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
2161 /* Try to reload if enabled */
2163 r
= daemon_reload(argc
, argv
, userdata
);
2169 unit_file_changes_free(changes
, n_changes
);
2174 static int output_waiting_jobs(sd_bus
*bus
, Table
*table
, uint32_t id
, const char *method
, const char *prefix
) {
2175 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2176 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2177 const char *name
, *type
;
2183 r
= sd_bus_call_method(
2185 "org.freedesktop.systemd1",
2186 "/org/freedesktop/systemd1",
2187 "org.freedesktop.systemd1.Manager",
2193 return log_debug_errno(r
, "Failed to get waiting jobs for job %" PRIu32
, id
);
2195 r
= sd_bus_message_enter_container(reply
, 'a', "(usssoo)");
2197 return bus_log_parse_error(r
);
2199 while ((r
= sd_bus_message_read(reply
, "(usssoo)", &other_id
, &name
, &type
, NULL
, NULL
, NULL
)) > 0) {
2200 _cleanup_free_
char *row
= NULL
;
2203 if (asprintf(&row
, "%s %u (%s/%s)", prefix
, other_id
, name
, type
) < 0)
2206 rc
= table_add_many(table
,
2207 TABLE_STRING
, special_glyph(SPECIAL_GLYPH_TREE_RIGHT
),
2212 return table_log_add_error(r
);
2216 return bus_log_parse_error(r
);
2218 r
= sd_bus_message_exit_container(reply
);
2220 return bus_log_parse_error(r
);
2227 const char *name
, *type
, *state
;
2230 static int output_jobs_list(sd_bus
*bus
, const struct job_info
* jobs
, unsigned n
, bool skipped
) {
2231 _cleanup_(table_unrefp
) Table
*table
= NULL
;
2232 const struct job_info
*j
;
2233 const char *on
, *off
;
2236 assert(n
== 0 || jobs
);
2239 if (!arg_no_legend
) {
2240 on
= ansi_highlight_green();
2241 off
= ansi_normal();
2243 printf("%sNo jobs %s.%s\n", on
, skipped
? "listed" : "running", off
);
2248 (void) pager_open(arg_pager_flags
);
2250 table
= table_new("job", "unit", "type", "state");
2254 table_set_header(table
, !arg_no_legend
);
2256 table_set_width(table
, 0);
2258 for (j
= jobs
; j
< jobs
+ n
; j
++) {
2259 if (streq(j
->state
, "running"))
2260 on
= ansi_highlight();
2265 r
= table_add_many(table
,
2267 TABLE_STRING
, j
->name
,
2268 TABLE_SET_COLOR
, on
,
2269 TABLE_STRING
, j
->type
,
2270 TABLE_STRING
, j
->state
,
2271 TABLE_SET_COLOR
, on
);
2273 return table_log_add_error(r
);
2276 output_waiting_jobs(bus
, table
, j
->id
, "GetJobAfter", "\twaiting for job");
2277 if (arg_jobs_before
)
2278 output_waiting_jobs(bus
, table
, j
->id
, "GetJobBefore", "\tblocking job");
2281 r
= table_print(table
, NULL
);
2283 return log_error_errno(r
, "Failed to print the table: %m");
2285 if (!arg_no_legend
) {
2286 on
= ansi_highlight();
2287 off
= ansi_normal();
2289 printf("\n%s%u jobs listed%s.\n", on
, n
, off
);
2295 static bool output_show_job(struct job_info
*job
, char **patterns
) {
2296 return strv_fnmatch_or_empty(patterns
, job
->name
, FNM_NOESCAPE
);
2299 static int list_jobs(int argc
, char *argv
[], void *userdata
) {
2300 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2301 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2302 _cleanup_free_
struct job_info
*jobs
= NULL
;
2303 const char *name
, *type
, *state
;
2304 bool skipped
= false;
2311 r
= acquire_bus(BUS_MANAGER
, &bus
);
2315 r
= sd_bus_call_method(
2317 "org.freedesktop.systemd1",
2318 "/org/freedesktop/systemd1",
2319 "org.freedesktop.systemd1.Manager",
2325 return log_error_errno(r
, "Failed to list jobs: %s", bus_error_message(&error
, r
));
2327 r
= sd_bus_message_enter_container(reply
, 'a', "(usssoo)");
2329 return bus_log_parse_error(r
);
2331 while ((r
= sd_bus_message_read(reply
, "(usssoo)", &id
, &name
, &type
, &state
, NULL
, NULL
)) > 0) {
2332 struct job_info job
= { id
, name
, type
, state
};
2334 if (!output_show_job(&job
, strv_skip(argv
, 1))) {
2339 if (!GREEDY_REALLOC(jobs
, size
, c
+ 1))
2345 return bus_log_parse_error(r
);
2347 r
= sd_bus_message_exit_container(reply
);
2349 return bus_log_parse_error(r
);
2351 (void) pager_open(arg_pager_flags
);
2353 return output_jobs_list(bus
, jobs
, c
, skipped
);
2356 static int cancel_job(int argc
, char *argv
[], void *userdata
) {
2362 return trivial_method(argc
, argv
, userdata
);
2364 r
= acquire_bus(BUS_MANAGER
, &bus
);
2368 polkit_agent_open_maybe();
2370 STRV_FOREACH(name
, strv_skip(argv
, 1)) {
2371 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2375 q
= safe_atou32(*name
, &id
);
2377 return log_error_errno(q
, "Failed to parse job id \"%s\": %m", *name
);
2379 q
= sd_bus_call_method(
2381 "org.freedesktop.systemd1",
2382 "/org/freedesktop/systemd1",
2383 "org.freedesktop.systemd1.Manager",
2389 log_error_errno(q
, "Failed to cancel job %"PRIu32
": %s", id
, bus_error_message(&error
, q
));
2398 static int need_daemon_reload(sd_bus
*bus
, const char *unit
) {
2399 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2403 /* We ignore all errors here, since this is used to show a
2406 /* We don't use unit_dbus_path_from_name() directly since we
2407 * don't want to load the unit if it isn't loaded. */
2409 r
= sd_bus_call_method(
2411 "org.freedesktop.systemd1",
2412 "/org/freedesktop/systemd1",
2413 "org.freedesktop.systemd1.Manager",
2421 r
= sd_bus_message_read(reply
, "o", &path
);
2425 r
= sd_bus_get_property_trivial(
2427 "org.freedesktop.systemd1",
2429 "org.freedesktop.systemd1.Unit",
2439 static void warn_unit_file_changed(const char *name
) {
2442 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.",
2443 ansi_highlight_red(),
2446 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user");
2449 static int unit_file_find_path(LookupPaths
*lp
, const char *unit_name
, char **ret_unit_path
) {
2455 STRV_FOREACH(p
, lp
->search_path
) {
2456 _cleanup_free_
char *path
= NULL
, *lpath
= NULL
;
2459 path
= path_join(*p
, unit_name
);
2463 r
= chase_symlinks(path
, arg_root
, 0, &lpath
, NULL
);
2469 return log_error_errno(r
, "Failed to access path \"%s\": %m", path
);
2472 *ret_unit_path
= TAKE_PTR(lpath
);
2478 *ret_unit_path
= NULL
;
2483 static int unit_find_template_path(
2484 const char *unit_name
,
2486 char **ret_fragment_path
,
2487 char **ret_template
) {
2489 _cleanup_free_
char *t
= NULL
, *f
= NULL
;
2492 /* Returns 1 if a fragment was found, 0 if not found, negative on error. */
2494 r
= unit_file_find_path(lp
, unit_name
, &f
);
2498 if (ret_fragment_path
)
2499 *ret_fragment_path
= TAKE_PTR(f
);
2501 *ret_template
= NULL
;
2502 return r
; /* found a real unit */
2505 r
= unit_name_template(unit_name
, &t
);
2507 if (ret_fragment_path
)
2508 *ret_fragment_path
= NULL
;
2510 *ret_template
= NULL
;
2512 return 0; /* not a template, does not exist */
2515 return log_error_errno(r
, "Failed to determine template name: %m");
2517 r
= unit_file_find_path(lp
, t
, ret_fragment_path
);
2522 *ret_template
= r
> 0 ? TAKE_PTR(t
) : NULL
;
2527 static int unit_find_paths(
2529 const char *unit_name
,
2531 bool force_client_side
,
2532 char **ret_fragment_path
,
2533 char ***ret_dropin_paths
) {
2535 _cleanup_strv_free_
char **dropins
= NULL
;
2536 _cleanup_free_
char *path
= NULL
;
2540 * Finds where the unit is defined on disk. Returns 0 if the unit is not found. Returns 1 if it is
2542 * - the path to the unit in *ret_frament_path, if it exists on disk,
2543 * - and a strv of existing drop-ins in *ret_dropin_paths, if the arg is not NULL and any dropins
2546 * Returns -ERFKILL if the unit is masked, and -EKEYREJECTED if the unit file could not be loaded for
2547 * some reason (the latter only applies if we are going through the service manager).
2551 assert(ret_fragment_path
);
2554 /* Go via the bus to acquire the path, unless we are explicitly told not to, or when the unit name is a template */
2555 if (!force_client_side
&&
2556 !install_client_side() &&
2557 !unit_name_is_valid(unit_name
, UNIT_NAME_TEMPLATE
)) {
2558 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2559 _cleanup_free_
char *load_state
= NULL
, *dbus_path
= NULL
;
2561 dbus_path
= unit_dbus_path_from_name(unit_name
);
2565 r
= sd_bus_get_property_string(
2567 "org.freedesktop.systemd1",
2569 "org.freedesktop.systemd1.Unit",
2574 return log_error_errno(r
, "Failed to get LoadState: %s", bus_error_message(&error
, r
));
2576 if (streq(load_state
, "masked"))
2578 if (streq(load_state
, "not-found")) {
2582 if (!STR_IN_SET(load_state
, "loaded", "bad-setting"))
2583 return -EKEYREJECTED
;
2585 r
= sd_bus_get_property_string(
2587 "org.freedesktop.systemd1",
2589 "org.freedesktop.systemd1.Unit",
2594 return log_error_errno(r
, "Failed to get FragmentPath: %s", bus_error_message(&error
, r
));
2596 if (ret_dropin_paths
) {
2597 r
= sd_bus_get_property_strv(
2599 "org.freedesktop.systemd1",
2601 "org.freedesktop.systemd1.Unit",
2606 return log_error_errno(r
, "Failed to get DropInPaths: %s", bus_error_message(&error
, r
));
2610 _cleanup_set_free_free_ Set
*names
= NULL
;
2612 if (!cached_name_map
) {
2613 r
= unit_file_build_name_map(lp
, NULL
, &cached_id_map
, &cached_name_map
, NULL
);
2618 r
= unit_file_find_fragment(cached_id_map
, cached_name_map
, unit_name
, &_path
, &names
);
2623 path
= strdup(_path
);
2628 if (ret_dropin_paths
) {
2629 r
= unit_file_find_dropin_paths(arg_root
, lp
->search_path
, NULL
,
2637 if (isempty(path
)) {
2638 *ret_fragment_path
= NULL
;
2641 *ret_fragment_path
= TAKE_PTR(path
);
2645 if (ret_dropin_paths
) {
2646 if (!strv_isempty(dropins
)) {
2647 *ret_dropin_paths
= TAKE_PTR(dropins
);
2650 *ret_dropin_paths
= NULL
;
2654 if (r
== 0 && !arg_force
)
2655 log_error("No files found for %s.", unit_name
);
2660 static int get_state_one_unit(sd_bus
*bus
, const char *name
, UnitActiveState
*active_state
) {
2661 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2662 _cleanup_free_
char *buf
= NULL
, *dbus_path
= NULL
;
2663 UnitActiveState state
;
2667 assert(active_state
);
2669 dbus_path
= unit_dbus_path_from_name(name
);
2673 r
= sd_bus_get_property_string(
2675 "org.freedesktop.systemd1",
2677 "org.freedesktop.systemd1.Unit",
2682 return log_error_errno(r
, "Failed to retrieve unit state: %s", bus_error_message(&error
, r
));
2684 state
= unit_active_state_from_string(buf
);
2686 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid unit state '%s' for: %s", buf
, name
);
2688 *active_state
= state
;
2692 static int unit_is_masked(sd_bus
*bus
, LookupPaths
*lp
, const char *name
) {
2693 _cleanup_free_
char *load_state
= NULL
;
2696 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
2697 _cleanup_free_
char *path
= NULL
;
2699 /* A template cannot be loaded, but it can be still masked, so
2700 * we need to use a different method. */
2702 r
= unit_file_find_path(lp
, name
, &path
);
2707 return null_or_empty_path(path
);
2710 r
= unit_load_state(bus
, name
, &load_state
);
2714 return streq(load_state
, "masked");
2717 static int check_triggering_units(sd_bus
*bus
, const char *name
) {
2718 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2719 _cleanup_free_
char *n
= NULL
, *dbus_path
= NULL
, *load_state
= NULL
;
2720 _cleanup_strv_free_
char **triggered_by
= NULL
;
2721 bool print_warning_label
= true;
2722 UnitActiveState active_state
;
2726 r
= unit_name_mangle(name
, 0, &n
);
2728 return log_error_errno(r
, "Failed to mangle unit name: %m");
2730 r
= unit_load_state(bus
, name
, &load_state
);
2734 if (streq(load_state
, "masked"))
2737 dbus_path
= unit_dbus_path_from_name(n
);
2741 r
= sd_bus_get_property_strv(
2743 "org.freedesktop.systemd1",
2745 "org.freedesktop.systemd1.Unit",
2750 return log_error_errno(r
, "Failed to get triggered by array of %s: %s", n
, bus_error_message(&error
, r
));
2752 STRV_FOREACH(i
, triggered_by
) {
2753 r
= get_state_one_unit(bus
, *i
, &active_state
);
2757 if (!IN_SET(active_state
, UNIT_ACTIVE
, UNIT_RELOADING
))
2760 if (print_warning_label
) {
2761 log_warning("Warning: Stopping %s, but it can still be activated by:", n
);
2762 print_warning_label
= false;
2765 log_warning(" %s", *i
);
2771 static const struct {
2772 const char *verb
; /* systemctl verb */
2773 const char *method
; /* Name of the specific D-Bus method */
2774 const char *job_type
; /* Job type when passing to the generic EnqueueUnitJob() method */
2775 } unit_actions
[] = {
2776 { "start", "StartUnit", "start" },
2777 { "stop", "StopUnit", "stop" },
2778 { "condstop", "StopUnit", "stop" }, /* legacy alias */
2779 { "reload", "ReloadUnit", "reload" },
2780 { "restart", "RestartUnit", "restart" },
2781 { "try-restart", "TryRestartUnit", "try-restart" },
2782 { "condrestart", "TryRestartUnit", "try-restart" }, /* legacy alias */
2783 { "reload-or-restart", "ReloadOrRestartUnit", "reload-or-restart" },
2784 { "try-reload-or-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" },
2785 { "reload-or-try-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2786 { "condreload", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2787 { "force-reload", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2790 static const char *verb_to_method(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
].method
;
2800 static const char *verb_to_job_type(const char *verb
) {
2803 for (i
= 0; i
< ELEMENTSOF(unit_actions
); i
++)
2804 if (streq_ptr(unit_actions
[i
].verb
, verb
))
2805 return unit_actions
[i
].job_type
;
2810 static int start_unit_one(
2812 const char *method
, /* When using classic per-job bus methods */
2813 const char *job_type
, /* When using new-style EnqueueUnitJob() */
2816 sd_bus_error
*error
,
2818 BusWaitForUnits
*wu
) {
2820 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2830 log_debug("%s dbus call org.freedesktop.systemd1.Manager %s(%s, %s)",
2831 arg_dry_run
? "Would execute" : "Executing",
2832 method
, name
, mode
);
2837 if (arg_show_transaction
) {
2838 _cleanup_(sd_bus_error_free
) sd_bus_error enqueue_error
= SD_BUS_ERROR_NULL
;
2840 /* Use the new, fancy EnqueueUnitJob() API if the user wants us to print the transaction */
2841 r
= sd_bus_call_method(
2843 "org.freedesktop.systemd1",
2844 "/org/freedesktop/systemd1",
2845 "org.freedesktop.systemd1.Manager",
2850 name
, job_type
, mode
);
2852 if (!sd_bus_error_has_name(&enqueue_error
, SD_BUS_ERROR_UNKNOWN_METHOD
)) {
2853 (void) sd_bus_error_move(error
, &enqueue_error
);
2857 /* Hmm, the API is not yet available. Let's use the classic API instead (see below). */
2858 log_notice("--show-transaction not supported by this service manager, proceeding without.");
2863 r
= sd_bus_message_read(reply
, "uosos", &id
, &path
, &u
, NULL
, &jt
);
2865 return bus_log_parse_error(r
);
2867 log_info("Enqueued anchor job %" PRIu32
" %s/%s.", id
, u
, jt
);
2869 r
= sd_bus_message_enter_container(reply
, 'a', "(uosos)");
2871 return bus_log_parse_error(r
);
2873 r
= sd_bus_message_read(reply
, "(uosos)", &id
, NULL
, &u
, NULL
, &jt
);
2875 return bus_log_parse_error(r
);
2879 log_info("Enqueued auxiliary job %" PRIu32
" %s/%s.", id
, u
, jt
);
2882 r
= sd_bus_message_exit_container(reply
);
2884 return bus_log_parse_error(r
);
2891 r
= sd_bus_call_method(
2893 "org.freedesktop.systemd1",
2894 "/org/freedesktop/systemd1",
2895 "org.freedesktop.systemd1.Manager",
2903 r
= sd_bus_message_read(reply
, "o", &path
);
2905 return bus_log_parse_error(r
);
2908 if (need_daemon_reload(bus
, name
) > 0)
2909 warn_unit_file_changed(name
);
2912 log_debug("Adding %s to the set", path
);
2913 r
= bus_wait_for_jobs_add(w
, path
);
2915 return log_error_errno(r
, "Failed to watch job for %s: %m", name
);
2919 r
= bus_wait_for_units_add_unit(wu
, name
, BUS_WAIT_FOR_INACTIVE
|BUS_WAIT_NO_JOB
, NULL
, NULL
);
2921 return log_error_errno(r
, "Failed to watch unit %s: %m", name
);
2927 /* There's always a fallback possible for legacy actions. */
2928 if (arg_action
!= ACTION_SYSTEMCTL
)
2931 log_error_errno(r
, "Failed to %s %s: %s", job_type
, name
, bus_error_message(error
, r
));
2933 if (!sd_bus_error_has_name(error
, BUS_ERROR_NO_SUCH_UNIT
) &&
2934 !sd_bus_error_has_name(error
, BUS_ERROR_UNIT_MASKED
) &&
2935 !sd_bus_error_has_name(error
, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE
))
2936 log_error("See %s logs and 'systemctl%s status%s %s' for details.",
2937 arg_scope
== UNIT_FILE_SYSTEM
? "system" : "user",
2938 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user",
2939 name
[0] == '-' ? " --" : "",
2945 static const struct {
2949 } action_table
[_ACTION_MAX
] = {
2950 [ACTION_HALT
] = { SPECIAL_HALT_TARGET
, "halt", "replace-irreversibly" },
2951 [ACTION_POWEROFF
] = { SPECIAL_POWEROFF_TARGET
, "poweroff", "replace-irreversibly" },
2952 [ACTION_REBOOT
] = { SPECIAL_REBOOT_TARGET
, "reboot", "replace-irreversibly" },
2953 [ACTION_KEXEC
] = { SPECIAL_KEXEC_TARGET
, "kexec", "replace-irreversibly" },
2954 [ACTION_RUNLEVEL2
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
2955 [ACTION_RUNLEVEL3
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
2956 [ACTION_RUNLEVEL4
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
2957 [ACTION_RUNLEVEL5
] = { SPECIAL_GRAPHICAL_TARGET
, NULL
, "isolate" },
2958 [ACTION_RESCUE
] = { SPECIAL_RESCUE_TARGET
, "rescue", "isolate" },
2959 [ACTION_EMERGENCY
] = { SPECIAL_EMERGENCY_TARGET
, "emergency", "isolate" },
2960 [ACTION_DEFAULT
] = { SPECIAL_DEFAULT_TARGET
, "default", "isolate" },
2961 [ACTION_EXIT
] = { SPECIAL_EXIT_TARGET
, "exit", "replace-irreversibly" },
2962 [ACTION_SUSPEND
] = { SPECIAL_SUSPEND_TARGET
, "suspend", "replace-irreversibly" },
2963 [ACTION_HIBERNATE
] = { SPECIAL_HIBERNATE_TARGET
, "hibernate", "replace-irreversibly" },
2964 [ACTION_HYBRID_SLEEP
] = { SPECIAL_HYBRID_SLEEP_TARGET
, "hybrid-sleep", "replace-irreversibly" },
2965 [ACTION_SUSPEND_THEN_HIBERNATE
] = { SPECIAL_SUSPEND_THEN_HIBERNATE_TARGET
, "suspend-then-hibernate", "replace-irreversibly" },
2968 static enum action
verb_to_action(const char *verb
) {
2971 for (i
= 0; i
< _ACTION_MAX
; i
++)
2972 if (streq_ptr(action_table
[i
].verb
, verb
))
2975 return _ACTION_INVALID
;
2978 static const char** make_extra_args(const char *extra_args
[static 4]) {
2983 if (arg_scope
!= UNIT_FILE_SYSTEM
)
2984 extra_args
[n
++] = "--user";
2986 if (arg_transport
== BUS_TRANSPORT_REMOTE
) {
2987 extra_args
[n
++] = "-H";
2988 extra_args
[n
++] = arg_host
;
2989 } else if (arg_transport
== BUS_TRANSPORT_MACHINE
) {
2990 extra_args
[n
++] = "-M";
2991 extra_args
[n
++] = arg_host
;
2993 assert(arg_transport
== BUS_TRANSPORT_LOCAL
);
2995 extra_args
[n
] = NULL
;
2999 static int start_unit(int argc
, char *argv
[], void *userdata
) {
3000 _cleanup_(bus_wait_for_units_freep
) BusWaitForUnits
*wu
= NULL
;
3001 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
3002 const char *method
, *job_type
, *mode
, *one_name
, *suffix
= NULL
;
3003 _cleanup_free_
char **stopped_units
= NULL
; /* Do not use _cleanup_strv_free_ */
3004 _cleanup_strv_free_
char **names
= NULL
;
3005 int r
, ret
= EXIT_SUCCESS
;
3009 if (arg_wait
&& !STR_IN_SET(argv
[0], "start", "restart"))
3010 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3011 "--wait may only be used with the 'start' or 'restart' commands.");
3013 /* we cannot do sender tracking on the private bus, so we need the full
3014 * one for RefUnit to implement --wait */
3015 r
= acquire_bus(arg_wait
? BUS_FULL
: BUS_MANAGER
, &bus
);
3019 ask_password_agent_open_maybe();
3020 polkit_agent_open_maybe();
3022 if (arg_action
== ACTION_SYSTEMCTL
) {
3025 action
= verb_to_action(argv
[0]);
3027 if (action
!= _ACTION_INVALID
) {
3028 /* A command in style "systemctl reboot", "systemctl poweroff", … */
3029 method
= "StartUnit";
3031 mode
= action_table
[action
].mode
;
3032 one_name
= action_table
[action
].target
;
3034 if (streq(argv
[0], "isolate")) {
3035 /* A "systemctl isolate <unit1> <unit2> …" command */
3036 method
= "StartUnit";
3041 /* A command in style of "systemctl start <unit1> <unit2> …", "sysemctl stop <unit1> <unit2> …" and so on */
3042 method
= verb_to_method(argv
[0]);
3043 job_type
= verb_to_job_type(argv
[0]);
3044 mode
= arg_job_mode
;
3049 /* A SysV legacy command such as "halt", "reboot", "poweroff", … */
3050 assert(arg_action
>= 0 && arg_action
< _ACTION_MAX
);
3051 assert(action_table
[arg_action
].target
);
3052 assert(action_table
[arg_action
].mode
);
3054 method
= "StartUnit";
3056 mode
= action_table
[arg_action
].mode
;
3057 one_name
= action_table
[arg_action
].target
;
3061 names
= strv_new(one_name
);
3067 r
= expand_names(bus
, strv_skip(argv
, 1), suffix
, &names
, &expanded
);
3069 return log_error_errno(r
, "Failed to expand names: %m");
3071 if (!arg_all
&& expanded
&& streq(job_type
, "start") && !arg_quiet
) {
3072 log_warning("Warning: %ssystemctl start called with a glob pattern.%s",
3073 ansi_highlight_red(),
3075 log_notice("Hint: unit globs expand to loaded units, so start will usually have no effect.\n"
3076 " Passing --all will also load units which are pulled in by other units.\n"
3077 " See systemctl(1) for more details.");
3081 if (!arg_no_block
) {
3082 r
= bus_wait_for_jobs_new(bus
, &w
);
3084 return log_error_errno(r
, "Could not watch jobs: %m");
3088 r
= sd_bus_call_method_async(
3091 "org.freedesktop.systemd1",
3092 "/org/freedesktop/systemd1",
3093 "org.freedesktop.systemd1.Manager",
3098 return log_error_errno(r
, "Failed to enable subscription: %m");
3100 r
= bus_wait_for_units_new(bus
, &wu
);
3102 return log_error_errno(r
, "Failed to allocate unit watch context: %m");
3105 STRV_FOREACH(name
, names
) {
3106 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3108 r
= start_unit_one(bus
, method
, job_type
, *name
, mode
, &error
, w
, wu
);
3109 if (ret
== EXIT_SUCCESS
&& r
< 0)
3110 ret
= translate_bus_error_to_exit_status(r
, &error
);
3112 if (r
>= 0 && streq(method
, "StopUnit")) {
3113 r
= strv_push(&stopped_units
, *name
);
3119 if (!arg_no_block
) {
3120 const char* extra_args
[4];
3122 r
= bus_wait_for_jobs(w
, arg_quiet
, make_extra_args(extra_args
));
3126 /* When stopping units, warn if they can still be triggered by
3127 * another active unit (socket, path, timer) */
3129 STRV_FOREACH(name
, stopped_units
)
3130 (void) check_triggering_units(bus
, *name
);
3134 r
= bus_wait_for_units_run(wu
);
3136 return log_error_errno(r
, "Failed to wait for units: %m");
3137 if (r
== BUS_WAIT_FAILURE
&& ret
== EXIT_SUCCESS
)
3145 static int logind_set_wall_message(void) {
3146 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3148 _cleanup_free_
char *m
= NULL
;
3151 r
= acquire_bus(BUS_FULL
, &bus
);
3155 m
= strv_join(arg_wall
, " ");
3159 log_debug("%s wall message \"%s\".", arg_dry_run
? "Would set" : "Setting", m
);
3163 r
= sd_bus_call_method(
3165 "org.freedesktop.login1",
3166 "/org/freedesktop/login1",
3167 "org.freedesktop.login1.Manager",
3176 return log_warning_errno(r
, "Failed to set wall message, ignoring: %s", bus_error_message(&error
, r
));
3181 /* Ask systemd-logind, which might grant access to unprivileged users through polkit */
3182 static int logind_reboot(enum action a
) {
3184 static const struct {
3186 const char *description
;
3187 } actions
[_ACTION_MAX
] = {
3188 [ACTION_POWEROFF
] = { "PowerOff", "power off system" },
3189 [ACTION_REBOOT
] = { "Reboot", "reboot system" },
3190 [ACTION_HALT
] = { "Halt", "halt system" },
3191 [ACTION_SUSPEND
] = { "Suspend", "suspend system" },
3192 [ACTION_HIBERNATE
] = { "Hibernate", "hibernate system" },
3193 [ACTION_HYBRID_SLEEP
] = { "HybridSleep", "put system into hybrid sleep" },
3194 [ACTION_SUSPEND_THEN_HIBERNATE
] = { "SuspendThenHibernate", "suspend system, hibernate later" },
3197 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3201 if (a
< 0 || a
>= _ACTION_MAX
|| !actions
[a
].method
)
3204 r
= acquire_bus(BUS_FULL
, &bus
);
3208 polkit_agent_open_maybe();
3209 (void) logind_set_wall_message();
3211 log_debug("%s org.freedesktop.login1.Manager %s dbus call.", arg_dry_run
? "Would execute" : "Executing", actions
[a
].method
);
3216 r
= sd_bus_call_method(
3218 "org.freedesktop.login1",
3219 "/org/freedesktop/login1",
3220 "org.freedesktop.login1.Manager",
3224 "b", arg_ask_password
);
3226 return log_error_errno(r
, "Failed to %s via logind: %s", actions
[a
].description
, bus_error_message(&error
, r
));
3234 static int logind_check_inhibitors(enum action a
) {
3236 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
3237 _cleanup_strv_free_
char **sessions
= NULL
;
3238 const char *what
, *who
, *why
, *mode
;
3245 if (arg_ignore_inhibitors
|| arg_force
> 0)
3257 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
3260 r
= acquire_bus(BUS_FULL
, &bus
);
3264 r
= sd_bus_call_method(
3266 "org.freedesktop.login1",
3267 "/org/freedesktop/login1",
3268 "org.freedesktop.login1.Manager",
3274 /* If logind is not around, then there are no inhibitors... */
3277 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssuu)");
3279 return bus_log_parse_error(r
);
3281 while ((r
= sd_bus_message_read(reply
, "(ssssuu)", &what
, &who
, &why
, &mode
, &uid
, &pid
)) > 0) {
3282 _cleanup_free_
char *comm
= NULL
, *user
= NULL
;
3283 _cleanup_strv_free_
char **sv
= NULL
;
3285 if (!streq(mode
, "block"))
3288 sv
= strv_split(what
, ":");
3292 if (!pid_is_valid((pid_t
) pid
))
3293 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Invalid PID "PID_FMT
".", (pid_t
) pid
);
3295 if (!strv_contains(sv
,
3300 ACTION_KEXEC
) ? "shutdown" : "sleep"))
3303 get_process_comm(pid
, &comm
);
3304 user
= uid_to_name(uid
);
3306 log_warning("Operation inhibited by \"%s\" (PID "PID_FMT
" \"%s\", user %s), reason is \"%s\".",
3307 who
, (pid_t
) pid
, strna(comm
), strna(user
), why
);
3312 return bus_log_parse_error(r
);
3314 r
= sd_bus_message_exit_container(reply
);
3316 return bus_log_parse_error(r
);
3318 /* Check for current sessions */
3319 sd_get_sessions(&sessions
);
3320 STRV_FOREACH(s
, sessions
) {
3321 _cleanup_free_
char *type
= NULL
, *tty
= NULL
, *seat
= NULL
, *user
= NULL
, *service
= NULL
, *class = NULL
;
3323 if (sd_session_get_uid(*s
, &uid
) < 0 || uid
== getuid())
3326 if (sd_session_get_class(*s
, &class) < 0 || !streq(class, "user"))
3329 if (sd_session_get_type(*s
, &type
) < 0 || !STR_IN_SET(type
, "x11", "wayland", "tty", "mir"))
3332 sd_session_get_tty(*s
, &tty
);
3333 sd_session_get_seat(*s
, &seat
);
3334 sd_session_get_service(*s
, &service
);
3335 user
= uid_to_name(uid
);
3337 log_warning("User %s is logged in on %s.", strna(user
), isempty(tty
) ? (isempty(seat
) ? strna(service
) : seat
) : tty
);
3344 log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'systemctl %s -i'.",
3345 action_table
[a
].verb
);
3353 static int prepare_firmware_setup(void) {
3355 if (!arg_firmware_setup
)
3359 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3363 r
= acquire_bus(BUS_FULL
, &bus
);
3367 r
= sd_bus_call_method(
3369 "org.freedesktop.login1",
3370 "/org/freedesktop/login1",
3371 "org.freedesktop.login1.Manager",
3372 "SetRebootToFirmwareSetup",
3377 return log_error_errno(r
, "Cannot indicate to EFI to boot into setup mode: %s", bus_error_message(&error
, r
));
3381 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3382 "Booting into firmware setup not supported.");
3386 static int prepare_boot_loader_menu(void) {
3388 if (arg_boot_loader_menu
== USEC_INFINITY
)
3392 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3396 r
= acquire_bus(BUS_FULL
, &bus
);
3400 r
= sd_bus_call_method(
3402 "org.freedesktop.login1",
3403 "/org/freedesktop/login1",
3404 "org.freedesktop.login1.Manager",
3405 "SetRebootToBootLoaderMenu",
3408 "t", arg_boot_loader_menu
);
3410 return log_error_errno(r
, "Cannot indicate to boot loader to enter boot loader entry menu: %s", bus_error_message(&error
, r
));
3414 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3415 "Booting into boot loader menu not supported.");
3419 static int prepare_boot_loader_entry(void) {
3421 if (!arg_boot_loader_entry
)
3425 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3429 r
= acquire_bus(BUS_FULL
, &bus
);
3433 r
= sd_bus_call_method(
3435 "org.freedesktop.login1",
3436 "/org/freedesktop/login1",
3437 "org.freedesktop.login1.Manager",
3438 "SetRebootToBootLoaderEntry",
3441 "s", arg_boot_loader_entry
);
3443 return log_error_errno(r
, "Cannot set boot into loader entry '%s': %s", arg_boot_loader_entry
, bus_error_message(&error
, r
));
3447 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3448 "Booting into boot loader entry not supported.");
3452 static int load_kexec_kernel(void) {
3453 _cleanup_(boot_config_free
) BootConfig config
= {};
3454 _cleanup_free_
char *kernel
= NULL
, *initrd
= NULL
, *options
= NULL
;
3459 if (kexec_loaded()) {
3460 log_debug("Kexec kernel already loaded.");
3464 if (access(KEXEC
, X_OK
) < 0)
3465 return log_error_errno(errno
, KEXEC
" is not available: %m");
3467 r
= boot_entries_load_config_auto(NULL
, NULL
, &config
);
3469 /* The call doesn't log about ENOKEY, let's do so here. */
3470 return log_error_errno(r
,
3471 "No kexec kernel loaded and autodetection failed.\n%s",
3473 ? "Cannot automatically load kernel: ESP partition mount point not found."
3474 : "Automatic loading works only on systems booted with EFI.");
3478 e
= boot_config_default_entry(&config
);
3480 return log_error_errno(SYNTHETIC_ERRNO(ENOENT
),
3481 "No boot loader entry suitable as default, refusing to guess.");
3483 log_debug("Found default boot loader entry in file \"%s\"", e
->path
);
3486 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3487 "Boot entry does not refer to Linux kernel, which is not supported currently.");
3488 if (strv_length(e
->initrd
) > 1)
3489 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3490 "Boot entry specifies multiple initrds, which is not supported currently.");
3492 kernel
= path_join(e
->root
, e
->kernel
);
3496 if (!strv_isempty(e
->initrd
)) {
3497 initrd
= path_join(e
->root
, e
->initrd
[0]);
3502 options
= strv_join(e
->options
, " ");
3506 log_full(arg_quiet
? LOG_DEBUG
: LOG_INFO
,
3507 "%s "KEXEC
" --load \"%s\" --append \"%s\"%s%s%s",
3508 arg_dry_run
? "Would run" : "Running",
3511 initrd
? " --initrd \"" : NULL
, strempty(initrd
), initrd
? "\"" : "");
3515 r
= safe_fork("(kexec)", FORK_WAIT
|FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
, &pid
);
3519 const char* const args
[] = {
3522 "--append", options
,
3523 initrd
? "--initrd" : NULL
, initrd
,
3528 execv(args
[0], (char * const *) args
);
3529 _exit(EXIT_FAILURE
);
3535 static int set_exit_code(uint8_t code
) {
3536 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3540 r
= acquire_bus(BUS_MANAGER
, &bus
);
3544 r
= sd_bus_call_method(
3546 "org.freedesktop.systemd1",
3547 "/org/freedesktop/systemd1",
3548 "org.freedesktop.systemd1.Manager",
3554 return log_error_errno(r
, "Failed to set exit code: %s", bus_error_message(&error
, r
));
3559 static int start_special(int argc
, char *argv
[], void *userdata
) {
3562 bool termination_action
; /* an action that terminates the manager,
3563 * can be performed also by signal. */
3567 a
= verb_to_action(argv
[0]);
3569 r
= logind_check_inhibitors(a
);
3573 if (arg_force
>= 2) {
3579 r
= prepare_firmware_setup();
3583 r
= prepare_boot_loader_menu();
3587 r
= prepare_boot_loader_entry();
3591 if (a
== ACTION_REBOOT
&& argc
> 1) {
3592 r
= update_reboot_parameter_and_warn(argv
[1], false);
3596 } else if (a
== ACTION_KEXEC
) {
3597 r
= load_kexec_kernel();
3598 if (r
< 0 && arg_force
>= 1)
3599 log_notice("Failed to load kexec kernel, continuing without.");
3603 } else if (a
== ACTION_EXIT
&& argc
> 1) {
3606 /* If the exit code is not given on the command line,
3607 * don't reset it to zero: just keep it as it might
3608 * have been set previously. */
3610 r
= safe_atou8(argv
[1], &code
);
3612 return log_error_errno(r
, "Invalid exit code.");
3614 r
= set_exit_code(code
);
3619 termination_action
= IN_SET(a
,
3623 if (termination_action
&& arg_force
>= 2)
3626 if (arg_force
>= 1 &&
3627 (termination_action
|| IN_SET(a
, ACTION_KEXEC
, ACTION_EXIT
)))
3628 r
= trivial_method(argc
, argv
, userdata
);
3630 /* First try logind, to allow authentication with polkit */
3637 ACTION_HYBRID_SLEEP
,
3638 ACTION_SUSPEND_THEN_HIBERNATE
)) {
3640 r
= logind_reboot(a
);
3643 if (IN_SET(r
, -EOPNOTSUPP
, -EINPROGRESS
))
3644 /* requested operation is not supported or already in progress */
3647 /* On all other errors, try low-level operation. In order to minimize the difference between
3648 * operation with and without logind, we explicitly enable non-blocking mode for this, as
3649 * logind's shutdown operations are always non-blocking. */
3651 arg_no_block
= true;
3653 } else if (IN_SET(a
, ACTION_EXIT
, ACTION_KEXEC
))
3654 /* Since exit/kexec are so close in behaviour to power-off/reboot, let's also make them
3655 * asynchronous, in order to not confuse the user needlessly with unexpected behaviour. */
3656 arg_no_block
= true;
3658 r
= start_unit(argc
, argv
, userdata
);
3661 if (termination_action
&& arg_force
< 2 &&
3662 IN_SET(r
, -ENOENT
, -ETIMEDOUT
))
3663 log_notice("It is possible to perform action directly, see discussion of --force --force in man:systemctl(1).");
3668 static int start_system_special(int argc
, char *argv
[], void *userdata
) {
3669 /* Like start_special above, but raises an error when running in user mode */
3671 if (arg_scope
!= UNIT_FILE_SYSTEM
)
3672 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3673 "Bad action for %s mode.",
3674 arg_scope
== UNIT_FILE_GLOBAL
? "--global" : "--user");
3676 return start_special(argc
, argv
, userdata
);
3679 static int check_unit_generic(int code
, const UnitActiveState good_states
[], int nb_states
, char **args
) {
3680 _cleanup_strv_free_
char **names
= NULL
;
3681 UnitActiveState active_state
;
3687 r
= acquire_bus(BUS_MANAGER
, &bus
);
3691 r
= expand_names(bus
, args
, NULL
, &names
, NULL
);
3693 return log_error_errno(r
, "Failed to expand names: %m");
3695 STRV_FOREACH(name
, names
) {
3696 r
= get_state_one_unit(bus
, *name
, &active_state
);
3701 puts(unit_active_state_to_string(active_state
));
3703 for (i
= 0; i
< nb_states
; ++i
)
3704 if (good_states
[i
] == active_state
)
3708 /* use the given return code for the case that we won't find
3709 * any unit which matches the list */
3710 return found
? 0 : code
;
3713 static int check_unit_active(int argc
, char *argv
[], void *userdata
) {
3714 static const UnitActiveState states
[] = {
3719 /* According to LSB: 3, "program is not running" */
3720 return check_unit_generic(EXIT_PROGRAM_NOT_RUNNING
, states
, ELEMENTSOF(states
), strv_skip(argv
, 1));
3723 static int check_unit_failed(int argc
, char *argv
[], void *userdata
) {
3724 static const UnitActiveState states
[] = {
3728 return check_unit_generic(EXIT_PROGRAM_DEAD_AND_PID_EXISTS
, states
, ELEMENTSOF(states
), strv_skip(argv
, 1));
3731 static int kill_unit(int argc
, char *argv
[], void *userdata
) {
3732 _cleanup_strv_free_
char **names
= NULL
;
3733 char *kill_who
= NULL
, **name
;
3737 r
= acquire_bus(BUS_MANAGER
, &bus
);
3741 polkit_agent_open_maybe();
3744 arg_kill_who
= "all";
3746 /* --fail was specified */
3747 if (streq(arg_job_mode
, "fail"))
3748 kill_who
= strjoina(arg_kill_who
, "-fail");
3750 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
3752 return log_error_errno(r
, "Failed to expand names: %m");
3754 STRV_FOREACH(name
, names
) {
3755 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3757 q
= sd_bus_call_method(
3759 "org.freedesktop.systemd1",
3760 "/org/freedesktop/systemd1",
3761 "org.freedesktop.systemd1.Manager",
3765 "ssi", *name
, kill_who
? kill_who
: arg_kill_who
, arg_signal
);
3767 log_error_errno(q
, "Failed to kill unit %s: %s", *name
, bus_error_message(&error
, q
));
3776 static int clean_unit(int argc
, char *argv
[], void *userdata
) {
3777 _cleanup_(bus_wait_for_units_freep
) BusWaitForUnits
*w
= NULL
;
3778 _cleanup_strv_free_
char **names
= NULL
;
3779 int r
, ret
= EXIT_SUCCESS
;
3783 r
= acquire_bus(BUS_FULL
, &bus
);
3787 polkit_agent_open_maybe();
3789 if (!arg_clean_what
) {
3790 arg_clean_what
= strv_new("cache", "runtime");
3791 if (!arg_clean_what
)
3795 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
3797 return log_error_errno(r
, "Failed to expand names: %m");
3799 if (!arg_no_block
) {
3800 r
= bus_wait_for_units_new(bus
, &w
);
3802 return log_error_errno(r
, "Failed to allocate unit waiter: %m");
3805 STRV_FOREACH(name
, names
) {
3806 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3807 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
3810 /* If we shall wait for the cleaning to complete, let's add a ref on the unit first */
3811 r
= sd_bus_call_method(
3813 "org.freedesktop.systemd1",
3814 "/org/freedesktop/systemd1",
3815 "org.freedesktop.systemd1.Manager",
3821 log_error_errno(r
, "Failed to add reference to unit %s: %s", *name
, bus_error_message(&error
, r
));
3822 if (ret
== EXIT_SUCCESS
)
3828 r
= sd_bus_message_new_method_call(
3831 "org.freedesktop.systemd1",
3832 "/org/freedesktop/systemd1",
3833 "org.freedesktop.systemd1.Manager",
3836 return bus_log_create_error(r
);
3838 r
= sd_bus_message_append(m
, "s", *name
);
3840 return bus_log_create_error(r
);
3842 r
= sd_bus_message_append_strv(m
, arg_clean_what
);
3844 return bus_log_create_error(r
);
3846 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
3848 log_error_errno(r
, "Failed to clean unit %s: %s", *name
, bus_error_message(&error
, r
));
3849 if (ret
== EXIT_SUCCESS
) {
3856 r
= bus_wait_for_units_add_unit(w
, *name
, BUS_WAIT_REFFED
|BUS_WAIT_FOR_MAINTENANCE_END
, NULL
, NULL
);
3858 return log_error_errno(r
, "Failed to watch unit %s: %m", *name
);
3862 r
= bus_wait_for_units_run(w
);
3864 return log_error_errno(r
, "Failed to wait for units: %m");
3865 if (r
== BUS_WAIT_FAILURE
)
3871 typedef struct ExecStatusInfo
{
3879 usec_t start_timestamp
;
3880 usec_t exit_timestamp
;
3885 ExecCommandFlags flags
;
3887 LIST_FIELDS(struct ExecStatusInfo
, exec
);
3890 static void exec_status_info_free(ExecStatusInfo
*i
) {
3899 static int exec_status_info_deserialize(sd_bus_message
*m
, ExecStatusInfo
*i
, bool is_ex_prop
) {
3900 _cleanup_strv_free_
char **ex_opts
= NULL
;
3901 uint64_t start_timestamp
, exit_timestamp
, start_timestamp_monotonic
, exit_timestamp_monotonic
;
3904 int32_t code
, status
;
3910 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_STRUCT
, is_ex_prop
? "sasasttttuii" : "sasbttttuii");
3912 return bus_log_parse_error(r
);
3916 r
= sd_bus_message_read(m
, "s", &path
);
3918 return bus_log_parse_error(r
);
3920 i
->path
= strdup(path
);
3924 r
= sd_bus_message_read_strv(m
, &i
->argv
);
3926 return bus_log_parse_error(r
);
3928 r
= is_ex_prop
? sd_bus_message_read_strv(m
, &ex_opts
) : sd_bus_message_read(m
, "b", &ignore
);
3930 return bus_log_parse_error(r
);
3932 r
= sd_bus_message_read(m
,
3934 &start_timestamp
, &start_timestamp_monotonic
,
3935 &exit_timestamp
, &exit_timestamp_monotonic
,
3939 return bus_log_parse_error(r
);
3942 r
= exec_command_flags_from_strv(ex_opts
, &i
->flags
);
3944 return log_error_errno(r
, "Failed to convert strv to ExecCommandFlags: %m");
3946 i
->ignore
= FLAGS_SET(i
->flags
, EXEC_COMMAND_IGNORE_FAILURE
);
3950 i
->start_timestamp
= (usec_t
) start_timestamp
;
3951 i
->exit_timestamp
= (usec_t
) exit_timestamp
;
3952 i
->pid
= (pid_t
) pid
;
3956 r
= sd_bus_message_exit_container(m
);
3958 return bus_log_parse_error(r
);
3963 typedef struct UnitCondition
{
3970 LIST_FIELDS(struct UnitCondition
, conditions
);
3973 static void unit_condition_free(UnitCondition
*c
) {
3982 DEFINE_TRIVIAL_CLEANUP_FUNC(UnitCondition
*, unit_condition_free
);
3984 typedef struct UnitStatusInfo
{
3986 const char *load_state
;
3987 const char *active_state
;
3988 const char *sub_state
;
3989 const char *unit_file_state
;
3990 const char *unit_file_preset
;
3992 const char *description
;
3993 const char *following
;
3995 char **documentation
;
3997 const char *fragment_path
;
3998 const char *source_path
;
3999 const char *control_group
;
4001 char **dropin_paths
;
4003 char **triggered_by
;
4006 const char *load_error
;
4009 usec_t inactive_exit_timestamp
;
4010 usec_t inactive_exit_timestamp_monotonic
;
4011 usec_t active_enter_timestamp
;
4012 usec_t active_exit_timestamp
;
4013 usec_t inactive_enter_timestamp
;
4015 bool need_daemon_reload
;
4021 const char *status_text
;
4022 const char *pid_file
;
4026 usec_t start_timestamp
;
4027 usec_t exit_timestamp
;
4029 int exit_code
, exit_status
;
4031 const char *log_namespace
;
4033 usec_t condition_timestamp
;
4034 bool condition_result
;
4035 LIST_HEAD(UnitCondition
, conditions
);
4037 usec_t assert_timestamp
;
4039 bool failed_assert_trigger
;
4040 bool failed_assert_negate
;
4041 const char *failed_assert
;
4042 const char *failed_assert_parameter
;
4043 usec_t next_elapse_real
;
4044 usec_t next_elapse_monotonic
;
4047 unsigned n_accepted
;
4048 unsigned n_connections
;
4052 /* Pairs of type, path */
4056 const char *sysfs_path
;
4058 /* Mount, Automount */
4065 uint64_t memory_current
;
4066 uint64_t memory_min
;
4067 uint64_t memory_low
;
4068 uint64_t memory_high
;
4069 uint64_t memory_max
;
4070 uint64_t memory_swap_max
;
4071 uint64_t memory_limit
;
4072 uint64_t cpu_usage_nsec
;
4073 uint64_t tasks_current
;
4075 uint64_t ip_ingress_bytes
;
4076 uint64_t ip_egress_bytes
;
4077 uint64_t io_read_bytes
;
4078 uint64_t io_write_bytes
;
4080 uint64_t default_memory_min
;
4081 uint64_t default_memory_low
;
4083 LIST_HEAD(ExecStatusInfo
, exec
);
4086 static void unit_status_info_free(UnitStatusInfo
*info
) {
4090 strv_free(info
->documentation
);
4091 strv_free(info
->dropin_paths
);
4092 strv_free(info
->triggered_by
);
4093 strv_free(info
->triggers
);
4094 strv_free(info
->listen
);
4096 while ((c
= info
->conditions
)) {
4097 LIST_REMOVE(conditions
, info
->conditions
, c
);
4098 unit_condition_free(c
);
4101 while ((p
= info
->exec
)) {
4102 LIST_REMOVE(exec
, info
->exec
, p
);
4103 exec_status_info_free(p
);
4107 static void format_active_state(const char *active_state
, const char **active_on
, const char **active_off
) {
4108 if (streq_ptr(active_state
, "failed")) {
4109 *active_on
= ansi_highlight_red();
4110 *active_off
= ansi_normal();
4111 } else if (STRPTR_IN_SET(active_state
, "active", "reloading")) {
4112 *active_on
= ansi_highlight_green();
4113 *active_off
= ansi_normal();
4115 *active_on
= *active_off
= "";
4118 static void print_status_info(
4123 char since1
[FORMAT_TIMESTAMP_RELATIVE_MAX
], since2
[FORMAT_TIMESTAMP_MAX
];
4124 const char *s1
, *s2
, *active_on
, *active_off
, *on
, *off
, *ss
;
4125 _cleanup_free_
char *formatted_path
= NULL
;
4134 /* This shows pretty information about a unit. See
4135 * print_property() for a low-level property printer */
4137 format_active_state(i
->active_state
, &active_on
, &active_off
);
4139 printf("%s%s%s %s", active_on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), active_off
, strna(i
->id
));
4141 if (i
->description
&& !streq_ptr(i
->id
, i
->description
))
4142 printf(" - %s", i
->description
);
4147 printf(" Follow: unit currently follows state of %s\n", i
->following
);
4149 if (STRPTR_IN_SET(i
->load_state
, "error", "not-found", "bad-setting")) {
4150 on
= ansi_highlight_red();
4151 off
= ansi_normal();
4155 path
= i
->source_path
?: i
->fragment_path
;
4156 if (path
&& terminal_urlify_path(path
, NULL
, &formatted_path
) >= 0)
4157 path
= formatted_path
;
4159 if (!isempty(i
->load_error
))
4160 printf(" Loaded: %s%s%s (Reason: %s)\n",
4161 on
, strna(i
->load_state
), off
, i
->load_error
);
4162 else if (path
&& !isempty(i
->unit_file_state
) && !isempty(i
->unit_file_preset
) &&
4163 !STR_IN_SET(i
->unit_file_state
, "generated", "transient"))
4164 printf(" Loaded: %s%s%s (%s; %s; vendor preset: %s)\n",
4165 on
, strna(i
->load_state
), off
, path
, i
->unit_file_state
, i
->unit_file_preset
);
4166 else if (path
&& !isempty(i
->unit_file_state
))
4167 printf(" Loaded: %s%s%s (%s; %s)\n",
4168 on
, strna(i
->load_state
), off
, path
, i
->unit_file_state
);
4170 printf(" Loaded: %s%s%s (%s)\n",
4171 on
, strna(i
->load_state
), off
, path
);
4173 printf(" Loaded: %s%s%s\n",
4174 on
, strna(i
->load_state
), off
);
4177 printf(" Transient: yes\n");
4179 if (!strv_isempty(i
->dropin_paths
)) {
4180 _cleanup_free_
char *dir
= NULL
;
4184 STRV_FOREACH(dropin
, i
->dropin_paths
) {
4185 _cleanup_free_
char *dropin_formatted
= NULL
;
4194 dir
= dirname_malloc(*dropin
);
4202 special_glyph(SPECIAL_GLYPH_TREE_RIGHT
));
4205 last
= ! (*(dropin
+ 1) && startswith(*(dropin
+ 1), dir
));
4207 if (terminal_urlify_path(*dropin
, basename(*dropin
), &dropin_formatted
) >= 0)
4208 df
= dropin_formatted
;
4212 printf("%s%s", df
, last
? "\n" : ", ");
4216 ss
= streq_ptr(i
->active_state
, i
->sub_state
) ? NULL
: i
->sub_state
;
4218 printf(" Active: %s%s (%s)%s",
4219 active_on
, strna(i
->active_state
), ss
, active_off
);
4221 printf(" Active: %s%s%s",
4222 active_on
, strna(i
->active_state
), active_off
);
4224 if (!isempty(i
->result
) && !streq(i
->result
, "success"))
4225 printf(" (Result: %s)", i
->result
);
4227 timestamp
= STRPTR_IN_SET(i
->active_state
, "active", "reloading") ? i
->active_enter_timestamp
:
4228 STRPTR_IN_SET(i
->active_state
, "inactive", "failed") ? i
->inactive_enter_timestamp
:
4229 STRPTR_IN_SET(i
->active_state
, "activating") ? i
->inactive_exit_timestamp
:
4230 i
->active_exit_timestamp
;
4232 s1
= format_timestamp_relative(since1
, sizeof(since1
), timestamp
);
4233 s2
= format_timestamp(since2
, sizeof(since2
), timestamp
);
4236 printf(" since %s; %s\n", s2
, s1
);
4238 printf(" since %s\n", s2
);
4242 STRV_FOREACH(t
, i
->triggered_by
) {
4243 UnitActiveState state
= _UNIT_ACTIVE_STATE_INVALID
;
4245 (void) get_state_one_unit(bus
, *t
, &state
);
4246 format_active_state(unit_active_state_to_string(state
), &on
, &off
);
4248 printf("%s %s%s%s %s\n",
4249 t
== i
->triggered_by
? "TriggeredBy:" : " ",
4250 on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
,
4254 if (endswith(i
->id
, ".timer")) {
4255 char tstamp1
[FORMAT_TIMESTAMP_RELATIVE_MAX
],
4256 tstamp2
[FORMAT_TIMESTAMP_MAX
];
4257 const char *next_rel_time
, *next_time
;
4258 dual_timestamp nw
, next
= {i
->next_elapse_real
,
4259 i
->next_elapse_monotonic
};
4262 printf(" Trigger: ");
4264 dual_timestamp_get(&nw
);
4265 next_elapse
= calc_next_elapse(&nw
, &next
);
4266 next_rel_time
= format_timestamp_relative(tstamp1
, sizeof tstamp1
, next_elapse
);
4267 next_time
= format_timestamp(tstamp2
, sizeof tstamp2
, next_elapse
);
4269 if (next_time
&& next_rel_time
)
4270 printf("%s; %s\n", next_time
, next_rel_time
);
4275 STRV_FOREACH(t
, i
->triggers
) {
4276 UnitActiveState state
= _UNIT_ACTIVE_STATE_INVALID
;
4278 (void) get_state_one_unit(bus
, *t
, &state
);
4279 format_active_state(unit_active_state_to_string(state
), &on
, &off
);
4281 printf("%s %s%s%s %s\n",
4282 t
== i
->triggers
? " Triggers:" : " ",
4283 on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
,
4287 if (!i
->condition_result
&& i
->condition_timestamp
> 0) {
4291 s1
= format_timestamp_relative(since1
, sizeof(since1
), i
->condition_timestamp
);
4292 s2
= format_timestamp(since2
, sizeof(since2
), i
->condition_timestamp
);
4294 printf(" Condition: start %scondition failed%s at %s%s%s\n",
4295 ansi_highlight_yellow(), ansi_normal(),
4296 s2
, s1
? "; " : "", strempty(s1
));
4298 LIST_FOREACH(conditions
, c
, i
->conditions
)
4299 if (c
->tristate
< 0)
4302 LIST_FOREACH(conditions
, c
, i
->conditions
)
4303 if (c
->tristate
< 0)
4304 printf(" %s %s=%s%s%s was not met\n",
4305 --n
? special_glyph(SPECIAL_GLYPH_TREE_BRANCH
) : special_glyph(SPECIAL_GLYPH_TREE_RIGHT
),
4307 c
->trigger
? "|" : "",
4308 c
->negate
? "!" : "",
4312 if (!i
->assert_result
&& i
->assert_timestamp
> 0) {
4313 s1
= format_timestamp_relative(since1
, sizeof(since1
), i
->assert_timestamp
);
4314 s2
= format_timestamp(since2
, sizeof(since2
), i
->assert_timestamp
);
4316 printf(" Assert: start %sassertion failed%s at %s%s%s\n",
4317 ansi_highlight_red(), ansi_normal(),
4318 s2
, s1
? "; " : "", strempty(s1
));
4319 if (i
->failed_assert_trigger
)
4320 printf(" none of the trigger assertions were met\n");
4321 else if (i
->failed_assert
)
4322 printf(" %s=%s%s was not met\n",
4324 i
->failed_assert_negate
? "!" : "",
4325 i
->failed_assert_parameter
);
4329 printf(" Device: %s\n", i
->sysfs_path
);
4331 printf(" Where: %s\n", i
->where
);
4333 printf(" What: %s\n", i
->what
);
4335 STRV_FOREACH(t
, i
->documentation
) {
4336 _cleanup_free_
char *formatted
= NULL
;
4339 if (terminal_urlify(*t
, NULL
, &formatted
) >= 0)
4344 printf(" %*s %s\n", 9, t
== i
->documentation
? "Docs:" : "", q
);
4347 STRV_FOREACH_PAIR(t
, t2
, i
->listen
)
4348 printf(" %*s %s (%s)\n", 9, t
== i
->listen
? "Listen:" : "", *t2
, *t
);
4351 printf(" Accepted: %u; Connected: %u;", i
->n_accepted
, i
->n_connections
);
4353 printf(" Refused: %u", i
->n_refused
);
4357 LIST_FOREACH(exec
, p
, i
->exec
) {
4358 _cleanup_free_
char *argv
= NULL
;
4361 /* Only show exited processes here */
4365 /* Don't print ExecXYZEx= properties here since it will appear as a
4366 * duplicate of the non-Ex= variant. */
4367 if (endswith(p
->name
, "Ex"))
4370 argv
= strv_join(p
->argv
, " ");
4371 printf(" Process: "PID_FMT
" %s=%s ", p
->pid
, p
->name
, strna(argv
));
4373 good
= is_clean_exit(p
->code
, p
->status
, EXIT_CLEAN_DAEMON
, NULL
);
4375 on
= ansi_highlight_red();
4376 off
= ansi_normal();
4380 printf("%s(code=%s, ", on
, sigchld_code_to_string(p
->code
));
4382 if (p
->code
== CLD_EXITED
) {
4385 printf("status=%i", p
->status
);
4387 c
= exit_status_to_string(p
->status
, EXIT_STATUS_LIBC
| EXIT_STATUS_SYSTEMD
);
4392 printf("signal=%s", signal_to_string(p
->status
));
4394 printf(")%s\n", off
);
4396 if (i
->main_pid
== p
->pid
&&
4397 i
->start_timestamp
== p
->start_timestamp
&&
4398 i
->exit_timestamp
== p
->start_timestamp
)
4399 /* Let's not show this twice */
4402 if (p
->pid
== i
->control_pid
)
4406 if (i
->main_pid
> 0 || i
->control_pid
> 0) {
4407 if (i
->main_pid
> 0) {
4408 printf(" Main PID: "PID_FMT
, i
->main_pid
);
4412 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
4413 _cleanup_free_
char *comm
= NULL
;
4415 (void) get_process_comm(i
->main_pid
, &comm
);
4417 printf(" (%s)", comm
);
4420 } else if (i
->exit_code
> 0) {
4421 printf(" (code=%s, ", sigchld_code_to_string(i
->exit_code
));
4423 if (i
->exit_code
== CLD_EXITED
) {
4426 printf("status=%i", i
->exit_status
);
4428 c
= exit_status_to_string(i
->exit_status
,
4429 EXIT_STATUS_LIBC
| EXIT_STATUS_SYSTEMD
);
4434 printf("signal=%s", signal_to_string(i
->exit_status
));
4439 if (i
->control_pid
> 0) {
4440 _cleanup_free_
char *c
= NULL
;
4442 if (i
->main_pid
> 0)
4443 fputs("; Control PID: ", stdout
);
4445 fputs("Cntrl PID: ", stdout
); /* if first in column, abbreviated so it fits alignment */
4447 printf(PID_FMT
, i
->control_pid
);
4449 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
4450 (void) get_process_comm(i
->control_pid
, &c
);
4460 printf(" Status: \"%s\"\n", i
->status_text
);
4461 if (i
->status_errno
> 0)
4462 printf(" Error: %i (%s)\n", i
->status_errno
, strerror_safe(i
->status_errno
));
4464 if (i
->ip_ingress_bytes
!= (uint64_t) -1 && i
->ip_egress_bytes
!= (uint64_t) -1) {
4465 char buf_in
[FORMAT_BYTES_MAX
], buf_out
[FORMAT_BYTES_MAX
];
4467 printf(" IP: %s in, %s out\n",
4468 format_bytes(buf_in
, sizeof(buf_in
), i
->ip_ingress_bytes
),
4469 format_bytes(buf_out
, sizeof(buf_out
), i
->ip_egress_bytes
));
4472 if (i
->io_read_bytes
!= UINT64_MAX
&& i
->io_write_bytes
!= UINT64_MAX
) {
4473 char buf_in
[FORMAT_BYTES_MAX
], buf_out
[FORMAT_BYTES_MAX
];
4475 printf(" IO: %s read, %s written\n",
4476 format_bytes(buf_in
, sizeof(buf_in
), i
->io_read_bytes
),
4477 format_bytes(buf_out
, sizeof(buf_out
), i
->io_write_bytes
));
4480 if (i
->tasks_current
!= (uint64_t) -1) {
4481 printf(" Tasks: %" PRIu64
, i
->tasks_current
);
4483 if (i
->tasks_max
!= (uint64_t) -1)
4484 printf(" (limit: %" PRIu64
")\n", i
->tasks_max
);
4489 if (i
->memory_current
!= (uint64_t) -1) {
4490 char buf
[FORMAT_BYTES_MAX
];
4492 printf(" Memory: %s", format_bytes(buf
, sizeof(buf
), i
->memory_current
));
4494 if (i
->memory_min
> 0 || i
->memory_low
> 0 ||
4495 i
->memory_high
!= CGROUP_LIMIT_MAX
|| i
->memory_max
!= CGROUP_LIMIT_MAX
||
4496 i
->memory_swap_max
!= CGROUP_LIMIT_MAX
||
4497 i
->memory_limit
!= CGROUP_LIMIT_MAX
) {
4498 const char *prefix
= "";
4501 if (i
->memory_min
> 0) {
4502 printf("%smin: %s", prefix
, format_bytes_cgroup_protection(buf
, sizeof(buf
), i
->memory_min
));
4505 if (i
->memory_low
> 0) {
4506 printf("%slow: %s", prefix
, format_bytes_cgroup_protection(buf
, sizeof(buf
), i
->memory_low
));
4509 if (i
->memory_high
!= CGROUP_LIMIT_MAX
) {
4510 printf("%shigh: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_high
));
4513 if (i
->memory_max
!= CGROUP_LIMIT_MAX
) {
4514 printf("%smax: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_max
));
4517 if (i
->memory_swap_max
!= CGROUP_LIMIT_MAX
) {
4518 printf("%sswap max: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_swap_max
));
4521 if (i
->memory_limit
!= CGROUP_LIMIT_MAX
) {
4522 printf("%slimit: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_limit
));
4530 if (i
->cpu_usage_nsec
!= (uint64_t) -1) {
4531 char buf
[FORMAT_TIMESPAN_MAX
];
4532 printf(" CPU: %s\n", format_timespan(buf
, sizeof(buf
), i
->cpu_usage_nsec
/ NSEC_PER_USEC
, USEC_PER_MSEC
));
4535 if (i
->control_group
) {
4536 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
4537 static const char prefix
[] = " ";
4540 printf(" CGroup: %s\n", i
->control_group
);
4543 if (c
> sizeof(prefix
) - 1)
4544 c
-= sizeof(prefix
) - 1;
4548 r
= unit_show_processes(bus
, i
->id
, i
->control_group
, prefix
, c
, get_output_flags(), &error
);
4553 /* Fallback for older systemd versions where the GetUnitProcesses() call is not yet available */
4555 if (i
->main_pid
> 0)
4556 extra
[k
++] = i
->main_pid
;
4558 if (i
->control_pid
> 0)
4559 extra
[k
++] = i
->control_pid
;
4561 show_cgroup_and_extra(SYSTEMD_CGROUP_CONTROLLER
, i
->control_group
, prefix
, c
, extra
, k
, get_output_flags());
4563 log_warning_errno(r
, "Failed to dump process list for '%s', ignoring: %s",
4564 i
->id
, bus_error_message(&error
, r
));
4567 if (i
->id
&& arg_transport
== BUS_TRANSPORT_LOCAL
)
4568 show_journal_by_unit(
4574 i
->inactive_exit_timestamp_monotonic
,
4577 get_output_flags() | OUTPUT_BEGIN_NEWLINE
,
4578 SD_JOURNAL_LOCAL_ONLY
,
4579 arg_scope
== UNIT_FILE_SYSTEM
,
4582 if (i
->need_daemon_reload
)
4583 warn_unit_file_changed(i
->id
);
4586 static void show_unit_help(UnitStatusInfo
*i
) {
4591 if (!i
->documentation
) {
4592 log_info("Documentation for %s not known.", i
->id
);
4596 STRV_FOREACH(p
, i
->documentation
)
4597 if (startswith(*p
, "man:"))
4598 show_man_page(*p
+ 4, false);
4600 log_info("Can't show: %s", *p
);
4603 static int map_main_pid(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4604 UnitStatusInfo
*i
= userdata
;
4608 r
= sd_bus_message_read(m
, "u", &u
);
4612 i
->main_pid
= (pid_t
) u
;
4618 static int map_load_error(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4619 const char *message
, **p
= userdata
;
4622 r
= sd_bus_message_read(m
, "(ss)", NULL
, &message
);
4626 if (!isempty(message
))
4632 static int map_listen(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4633 const char *type
, *path
;
4634 char ***p
= userdata
;
4637 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
4641 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0) {
4643 r
= strv_extend(p
, type
);
4647 r
= strv_extend(p
, path
);
4654 r
= sd_bus_message_exit_container(m
);
4661 static int map_conditions(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4662 UnitStatusInfo
*i
= userdata
;
4663 const char *cond
, *param
;
4664 int trigger
, negate
;
4668 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sbbsi)");
4672 while ((r
= sd_bus_message_read(m
, "(sbbsi)", &cond
, &trigger
, &negate
, ¶m
, &state
)) > 0) {
4673 _cleanup_(unit_condition_freep
) UnitCondition
*c
= NULL
;
4675 c
= new(UnitCondition
, 1);
4679 *c
= (UnitCondition
) {
4680 .name
= strdup(cond
),
4681 .param
= strdup(param
),
4687 if (!c
->name
|| !c
->param
)
4690 LIST_PREPEND(conditions
, i
->conditions
, TAKE_PTR(c
));
4695 r
= sd_bus_message_exit_container(m
);
4702 static int map_asserts(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4703 UnitStatusInfo
*i
= userdata
;
4704 const char *cond
, *param
;
4705 int trigger
, negate
;
4709 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sbbsi)");
4713 while ((r
= sd_bus_message_read(m
, "(sbbsi)", &cond
, &trigger
, &negate
, ¶m
, &state
)) > 0) {
4714 if (state
< 0 && (!trigger
|| !i
->failed_assert
)) {
4715 i
->failed_assert
= cond
;
4716 i
->failed_assert_trigger
= trigger
;
4717 i
->failed_assert_negate
= negate
;
4718 i
->failed_assert_parameter
= param
;
4724 r
= sd_bus_message_exit_container(m
);
4731 static int map_exec(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4732 _cleanup_free_ ExecStatusInfo
*info
= NULL
;
4733 ExecStatusInfo
*last
;
4734 UnitStatusInfo
*i
= userdata
;
4735 bool is_ex_prop
= endswith(member
, "Ex");
4738 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, is_ex_prop
? "(sasasttttuii)" : "(sasbttttuii)");
4742 info
= new0(ExecStatusInfo
, 1);
4746 LIST_FIND_TAIL(exec
, i
->exec
, last
);
4748 while ((r
= exec_status_info_deserialize(m
, info
, is_ex_prop
)) > 0) {
4750 info
->name
= strdup(member
);
4754 LIST_INSERT_AFTER(exec
, i
->exec
, last
, info
);
4757 info
= new0(ExecStatusInfo
, 1);
4764 r
= sd_bus_message_exit_container(m
);
4771 static int print_property(const char *name
, const char *expected_value
, sd_bus_message
*m
, bool value
, bool all
) {
4773 const char *contents
;
4779 /* This is a low-level property printer, see
4780 * print_status_info() for the nicer output */
4782 r
= sd_bus_message_peek_type(m
, &bus_type
, &contents
);
4788 case SD_BUS_TYPE_INT32
:
4789 if (endswith(name
, "ActionExitStatus")) {
4792 r
= sd_bus_message_read_basic(m
, bus_type
, &i
);
4796 if (i
>= 0 && i
<= 255)
4797 bus_print_property_valuef(name
, expected_value
, value
, "%"PRIi32
, i
);
4799 bus_print_property_value(name
, expected_value
, value
, "[not set]");
4802 } else if (streq(name
, "NUMAPolicy")) {
4805 r
= sd_bus_message_read_basic(m
, bus_type
, &i
);
4809 bus_print_property_valuef(name
, expected_value
, value
, "%s", strna(mpol_to_string(i
)));
4815 case SD_BUS_TYPE_STRUCT
:
4817 if (contents
[0] == SD_BUS_TYPE_UINT32
&& streq(name
, "Job")) {
4820 r
= sd_bus_message_read(m
, "(uo)", &u
, NULL
);
4822 return bus_log_parse_error(r
);
4825 bus_print_property_valuef(name
, expected_value
, value
, "%"PRIu32
, u
);
4827 bus_print_property_value(name
, expected_value
, value
, "");
4831 } else if (contents
[0] == SD_BUS_TYPE_STRING
&& streq(name
, "Unit")) {
4834 r
= sd_bus_message_read(m
, "(so)", &s
, NULL
);
4836 return bus_log_parse_error(r
);
4838 if (all
|| !isempty(s
))
4839 bus_print_property_value(name
, expected_value
, value
, s
);
4843 } else if (contents
[0] == SD_BUS_TYPE_STRING
&& streq(name
, "LoadError")) {
4844 const char *a
= NULL
, *b
= NULL
;
4846 r
= sd_bus_message_read(m
, "(ss)", &a
, &b
);
4848 return bus_log_parse_error(r
);
4850 if (!isempty(a
) || !isempty(b
))
4851 bus_print_property_valuef(name
, expected_value
, value
, "%s \"%s\"", strempty(a
), strempty(b
));
4853 bus_print_property_value(name
, expected_value
, value
, "");
4857 } else if (STR_IN_SET(name
, "SystemCallFilter", "RestrictAddressFamilies")) {
4858 _cleanup_strv_free_
char **l
= NULL
;
4861 r
= sd_bus_message_enter_container(m
, 'r', "bas");
4863 return bus_log_parse_error(r
);
4865 r
= sd_bus_message_read(m
, "b", &whitelist
);
4867 return bus_log_parse_error(r
);
4869 r
= sd_bus_message_read_strv(m
, &l
);
4871 return bus_log_parse_error(r
);
4873 r
= sd_bus_message_exit_container(m
);
4875 return bus_log_parse_error(r
);
4877 if (all
|| whitelist
|| !strv_isempty(l
)) {
4882 fputs(name
, stdout
);
4889 STRV_FOREACH(i
, l
) {
4897 fputc('\n', stdout
);
4902 } else if (STR_IN_SET(name
, "SELinuxContext", "AppArmorProfile", "SmackProcessLabel")) {
4906 r
= sd_bus_message_read(m
, "(bs)", &ignore
, &s
);
4908 return bus_log_parse_error(r
);
4911 bus_print_property_valuef(name
, expected_value
, value
, "%s%s", ignore
? "-" : "", s
);
4913 bus_print_property_value(name
, expected_value
, value
, "");
4917 } else if (endswith(name
, "ExitStatus") && streq(contents
, "aiai")) {
4918 const int32_t *status
, *signal
;
4919 size_t n_status
, n_signal
, i
;
4921 r
= sd_bus_message_enter_container(m
, 'r', "aiai");
4923 return bus_log_parse_error(r
);
4925 r
= sd_bus_message_read_array(m
, 'i', (const void **) &status
, &n_status
);
4927 return bus_log_parse_error(r
);
4929 r
= sd_bus_message_read_array(m
, 'i', (const void **) &signal
, &n_signal
);
4931 return bus_log_parse_error(r
);
4933 r
= sd_bus_message_exit_container(m
);
4935 return bus_log_parse_error(r
);
4937 n_status
/= sizeof(int32_t);
4938 n_signal
/= sizeof(int32_t);
4940 if (all
|| n_status
> 0 || n_signal
> 0) {
4944 fputs(name
, stdout
);
4948 for (i
= 0; i
< n_status
; i
++) {
4954 printf("%"PRIi32
, status
[i
]);
4957 for (i
= 0; i
< n_signal
; i
++) {
4960 str
= signal_to_string((int) signal
[i
]);
4970 printf("%"PRIi32
, status
[i
]);
4973 fputc('\n', stdout
);
4980 case SD_BUS_TYPE_ARRAY
:
4982 if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "EnvironmentFiles")) {
4986 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sb)");
4988 return bus_log_parse_error(r
);
4990 while ((r
= sd_bus_message_read(m
, "(sb)", &path
, &ignore
)) > 0)
4991 bus_print_property_valuef(name
, expected_value
, value
, "%s (ignore_errors=%s)", path
, yes_no(ignore
));
4994 return bus_log_parse_error(r
);
4996 r
= sd_bus_message_exit_container(m
);
4998 return bus_log_parse_error(r
);
5002 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "Paths")) {
5003 const char *type
, *path
;
5005 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5007 return bus_log_parse_error(r
);
5009 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0)
5010 bus_print_property_valuef(name
, expected_value
, value
, "%s (%s)", path
, type
);
5012 return bus_log_parse_error(r
);
5014 r
= sd_bus_message_exit_container(m
);
5016 return bus_log_parse_error(r
);
5020 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "Listen")) {
5021 const char *type
, *path
;
5023 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5025 return bus_log_parse_error(r
);
5027 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0)
5028 bus_print_property_valuef(name
, expected_value
, value
, "%s (%s)", path
, type
);
5030 return bus_log_parse_error(r
);
5032 r
= sd_bus_message_exit_container(m
);
5034 return bus_log_parse_error(r
);
5038 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "TimersMonotonic")) {
5040 uint64_t v
, next_elapse
;
5042 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(stt)");
5044 return bus_log_parse_error(r
);
5046 while ((r
= sd_bus_message_read(m
, "(stt)", &base
, &v
, &next_elapse
)) > 0) {
5047 char timespan1
[FORMAT_TIMESPAN_MAX
] = "n/a", timespan2
[FORMAT_TIMESPAN_MAX
] = "n/a";
5049 (void) format_timespan(timespan1
, sizeof timespan1
, v
, 0);
5050 (void) format_timespan(timespan2
, sizeof timespan2
, next_elapse
, 0);
5052 bus_print_property_valuef(name
, expected_value
, value
,
5053 "{ %s=%s ; next_elapse=%s }", base
, timespan1
, timespan2
);
5056 return bus_log_parse_error(r
);
5058 r
= sd_bus_message_exit_container(m
);
5060 return bus_log_parse_error(r
);
5064 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "TimersCalendar")) {
5065 const char *base
, *spec
;
5066 uint64_t next_elapse
;
5068 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sst)");
5070 return bus_log_parse_error(r
);
5072 while ((r
= sd_bus_message_read(m
, "(sst)", &base
, &spec
, &next_elapse
)) > 0) {
5073 char timestamp
[FORMAT_TIMESTAMP_MAX
] = "n/a";
5075 (void) format_timestamp(timestamp
, sizeof(timestamp
), next_elapse
);
5076 bus_print_property_valuef(name
, expected_value
, value
,
5077 "{ %s=%s ; next_elapse=%s }", base
, spec
, timestamp
);
5080 return bus_log_parse_error(r
);
5082 r
= sd_bus_message_exit_container(m
);
5084 return bus_log_parse_error(r
);
5088 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& startswith(name
, "Exec")) {
5089 ExecStatusInfo info
= {};
5090 bool is_ex_prop
= endswith(name
, "Ex");
5092 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, is_ex_prop
? "(sasasttttuii)" : "(sasbttttuii)");
5094 return bus_log_parse_error(r
);
5096 while ((r
= exec_status_info_deserialize(m
, &info
, is_ex_prop
)) > 0) {
5097 char timestamp1
[FORMAT_TIMESTAMP_MAX
], timestamp2
[FORMAT_TIMESTAMP_MAX
];
5098 _cleanup_strv_free_
char **optv
= NULL
;
5099 _cleanup_free_
char *tt
, *o
= NULL
;
5101 tt
= strv_join(info
.argv
, " ");
5104 r
= exec_command_flags_to_strv(info
.flags
, &optv
);
5106 return log_error_errno(r
, "Failed to convert ExecCommandFlags to strv: %m");
5108 o
= strv_join(optv
, " ");
5110 bus_print_property_valuef(name
, expected_value
, value
,
5111 "{ path=%s ; argv[]=%s ; flags=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT
" ; code=%s ; status=%i%s%s }",
5115 strna(format_timestamp(timestamp1
, sizeof(timestamp1
), info
.start_timestamp
)),
5116 strna(format_timestamp(timestamp2
, sizeof(timestamp2
), info
.exit_timestamp
)),
5118 sigchld_code_to_string(info
.code
),
5120 info
.code
== CLD_EXITED
? "" : "/",
5121 strempty(info
.code
== CLD_EXITED
? NULL
: signal_to_string(info
.status
)));
5123 bus_print_property_valuef(name
, expected_value
, value
,
5124 "{ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT
" ; code=%s ; status=%i%s%s }",
5127 yes_no(info
.ignore
),
5128 strna(format_timestamp(timestamp1
, sizeof(timestamp1
), info
.start_timestamp
)),
5129 strna(format_timestamp(timestamp2
, sizeof(timestamp2
), info
.exit_timestamp
)),
5131 sigchld_code_to_string(info
.code
),
5133 info
.code
== CLD_EXITED
? "" : "/",
5134 strempty(info
.code
== CLD_EXITED
? NULL
: signal_to_string(info
.status
)));
5137 strv_free(info
.argv
);
5141 r
= sd_bus_message_exit_container(m
);
5143 return bus_log_parse_error(r
);
5147 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "DeviceAllow")) {
5148 const char *path
, *rwm
;
5150 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5152 return bus_log_parse_error(r
);
5154 while ((r
= sd_bus_message_read(m
, "(ss)", &path
, &rwm
)) > 0)
5155 bus_print_property_valuef(name
, expected_value
, value
, "%s %s", strna(path
), strna(rwm
));
5157 return bus_log_parse_error(r
);
5159 r
= sd_bus_message_exit_container(m
);
5161 return bus_log_parse_error(r
);
5165 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5166 STR_IN_SET(name
, "IODeviceWeight", "BlockIODeviceWeight")) {
5170 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5172 return bus_log_parse_error(r
);
5174 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &weight
)) > 0)
5175 bus_print_property_valuef(name
, expected_value
, value
, "%s %"PRIu64
, strna(path
), weight
);
5177 return bus_log_parse_error(r
);
5179 r
= sd_bus_message_exit_container(m
);
5181 return bus_log_parse_error(r
);
5185 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5186 (cgroup_io_limit_type_from_string(name
) >= 0 ||
5187 STR_IN_SET(name
, "BlockIOReadBandwidth", "BlockIOWriteBandwidth"))) {
5191 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5193 return bus_log_parse_error(r
);
5195 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &bandwidth
)) > 0)
5196 bus_print_property_valuef(name
, expected_value
, value
, "%s %"PRIu64
, strna(path
), bandwidth
);
5198 return bus_log_parse_error(r
);
5200 r
= sd_bus_message_exit_container(m
);
5202 return bus_log_parse_error(r
);
5206 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5207 streq(name
, "IODeviceLatencyTargetUSec")) {
5208 char ts
[FORMAT_TIMESPAN_MAX
];
5212 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5214 return bus_log_parse_error(r
);
5216 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &target
)) > 0)
5217 bus_print_property_valuef(name
, expected_value
, value
, "%s %s", strna(path
),
5218 format_timespan(ts
, sizeof(ts
), target
, 1));
5220 return bus_log_parse_error(r
);
5222 r
= sd_bus_message_exit_container(m
);
5224 return bus_log_parse_error(r
);
5228 } else if (contents
[0] == SD_BUS_TYPE_BYTE
&& streq(name
, "StandardInputData")) {
5229 _cleanup_free_
char *h
= NULL
;
5234 r
= sd_bus_message_read_array(m
, 'y', &p
, &sz
);
5236 return bus_log_parse_error(r
);
5238 n
= base64mem(p
, sz
, &h
);
5242 bus_print_property_value(name
, expected_value
, value
, h
);
5246 } else if (STR_IN_SET(name
, "IPAddressAllow", "IPAddressDeny")) {
5247 _cleanup_free_
char *addresses
= NULL
;
5249 r
= sd_bus_message_enter_container(m
, 'a', "(iayu)");
5251 return bus_log_parse_error(r
);
5254 _cleanup_free_
char *str
= NULL
;
5260 r
= sd_bus_message_enter_container(m
, 'r', "iayu");
5262 return bus_log_parse_error(r
);
5266 r
= sd_bus_message_read(m
, "i", &family
);
5268 return bus_log_parse_error(r
);
5270 r
= sd_bus_message_read_array(m
, 'y', &ap
, &an
);
5272 return bus_log_parse_error(r
);
5274 r
= sd_bus_message_read(m
, "u", &prefixlen
);
5276 return bus_log_parse_error(r
);
5278 r
= sd_bus_message_exit_container(m
);
5280 return bus_log_parse_error(r
);
5282 if (!IN_SET(family
, AF_INET
, AF_INET6
))
5285 if (an
!= FAMILY_ADDRESS_SIZE(family
))
5288 if (prefixlen
> FAMILY_ADDRESS_SIZE(family
) * 8)
5291 if (in_addr_prefix_to_string(family
, (union in_addr_union
*) ap
, prefixlen
, &str
) < 0)
5294 if (!strextend_with_separator(&addresses
, " ", str
, NULL
))
5298 r
= sd_bus_message_exit_container(m
);
5300 return bus_log_parse_error(r
);
5302 if (all
|| !isempty(addresses
))
5303 bus_print_property_value(name
, expected_value
, value
, strempty(addresses
));
5307 } else if (STR_IN_SET(name
, "BindPaths", "BindReadOnlyPaths")) {
5308 _cleanup_free_
char *paths
= NULL
;
5309 const char *source
, *dest
;
5313 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ssbt)");
5315 return bus_log_parse_error(r
);
5317 while ((r
= sd_bus_message_read(m
, "(ssbt)", &source
, &dest
, &ignore_enoent
, &rbind
)) > 0) {
5318 _cleanup_free_
char *str
= NULL
;
5320 if (isempty(source
))
5323 if (asprintf(&str
, "%s%s%s%s%s",
5324 ignore_enoent
? "-" : "",
5326 isempty(dest
) ? "" : ":",
5328 rbind
== MS_REC
? ":rbind" : "") < 0)
5331 if (!strextend_with_separator(&paths
, " ", str
, NULL
))
5335 return bus_log_parse_error(r
);
5337 r
= sd_bus_message_exit_container(m
);
5339 return bus_log_parse_error(r
);
5341 if (all
|| !isempty(paths
))
5342 bus_print_property_value(name
, expected_value
, value
, strempty(paths
));
5346 } else if (streq(name
, "TemporaryFileSystem")) {
5347 _cleanup_free_
char *paths
= NULL
;
5348 const char *target
, *option
;
5350 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5352 return bus_log_parse_error(r
);
5354 while ((r
= sd_bus_message_read(m
, "(ss)", &target
, &option
)) > 0) {
5355 _cleanup_free_
char *str
= NULL
;
5357 if (isempty(target
))
5360 if (asprintf(&str
, "%s%s%s", target
, isempty(option
) ? "" : ":", strempty(option
)) < 0)
5363 if (!strextend_with_separator(&paths
, " ", str
, NULL
))
5367 return bus_log_parse_error(r
);
5369 r
= sd_bus_message_exit_container(m
);
5371 return bus_log_parse_error(r
);
5373 if (all
|| !isempty(paths
))
5374 bus_print_property_value(name
, expected_value
, value
, strempty(paths
));
5378 } else if (streq(name
, "LogExtraFields")) {
5379 _cleanup_free_
char *fields
= NULL
;
5383 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "ay");
5385 return bus_log_parse_error(r
);
5387 while ((r
= sd_bus_message_read_array(m
, 'y', &p
, &sz
)) > 0) {
5388 _cleanup_free_
char *str
= NULL
;
5391 if (memchr(p
, 0, sz
))
5394 eq
= memchr(p
, '=', sz
);
5398 if (!journal_field_valid(p
, eq
- (const char*) p
, false))
5401 str
= malloc(sz
+ 1);
5408 if (!utf8_is_valid(str
))
5411 if (!strextend_with_separator(&fields
, " ", str
, NULL
))
5415 return bus_log_parse_error(r
);
5417 r
= sd_bus_message_exit_container(m
);
5419 return bus_log_parse_error(r
);
5421 if (all
|| !isempty(fields
))
5422 bus_print_property_value(name
, expected_value
, value
, strempty(fields
));
5425 } else if (contents
[0] == SD_BUS_TYPE_BYTE
&& STR_IN_SET(name
, "CPUAffinity", "NUMAMask", "AllowedCPUs", "AllowedMemoryNodes", "EffectiveCPUs", "EffectiveMemoryNodes")) {
5426 _cleanup_free_
char *affinity
= NULL
;
5427 _cleanup_(cpu_set_reset
) CPUSet set
= {};
5431 r
= sd_bus_message_read_array(m
, 'y', &a
, &n
);
5433 return bus_log_parse_error(r
);
5435 r
= cpu_set_from_dbus(a
, n
, &set
);
5437 return log_error_errno(r
, "Failed to deserialize %s: %m", name
);
5439 affinity
= cpu_set_to_range_string(&set
);
5443 bus_print_property_value(name
, expected_value
, value
, affinity
);
5454 typedef enum SystemctlShowMode
{
5455 SYSTEMCTL_SHOW_PROPERTIES
,
5456 SYSTEMCTL_SHOW_STATUS
,
5457 SYSTEMCTL_SHOW_HELP
,
5458 _SYSTEMCTL_SHOW_MODE_MAX
,
5459 _SYSTEMCTL_SHOW_MODE_INVALID
= -1,
5460 } SystemctlShowMode
;
5462 static const char* const systemctl_show_mode_table
[_SYSTEMCTL_SHOW_MODE_MAX
] = {
5463 [SYSTEMCTL_SHOW_PROPERTIES
] = "show",
5464 [SYSTEMCTL_SHOW_STATUS
] = "status",
5465 [SYSTEMCTL_SHOW_HELP
] = "help",
5468 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(systemctl_show_mode
, SystemctlShowMode
);
5470 static int show_one(
5474 SystemctlShowMode show_mode
,
5478 static const struct bus_properties_map property_map
[] = {
5479 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
5480 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
) },
5481 { "Documentation", "as", NULL
, offsetof(UnitStatusInfo
, documentation
) },
5484 { "Id", "s", NULL
, offsetof(UnitStatusInfo
, id
) },
5485 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
5486 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
) },
5487 { "SubState", "s", NULL
, offsetof(UnitStatusInfo
, sub_state
) },
5488 { "UnitFileState", "s", NULL
, offsetof(UnitStatusInfo
, unit_file_state
) },
5489 { "UnitFilePreset", "s", NULL
, offsetof(UnitStatusInfo
, unit_file_preset
) },
5490 { "Description", "s", NULL
, offsetof(UnitStatusInfo
, description
) },
5491 { "Following", "s", NULL
, offsetof(UnitStatusInfo
, following
) },
5492 { "Documentation", "as", NULL
, offsetof(UnitStatusInfo
, documentation
) },
5493 { "FragmentPath", "s", NULL
, offsetof(UnitStatusInfo
, fragment_path
) },
5494 { "SourcePath", "s", NULL
, offsetof(UnitStatusInfo
, source_path
) },
5495 { "ControlGroup", "s", NULL
, offsetof(UnitStatusInfo
, control_group
) },
5496 { "DropInPaths", "as", NULL
, offsetof(UnitStatusInfo
, dropin_paths
) },
5497 { "LoadError", "(ss)", map_load_error
, offsetof(UnitStatusInfo
, load_error
) },
5498 { "Result", "s", NULL
, offsetof(UnitStatusInfo
, result
) },
5499 { "TriggeredBy", "as", NULL
, offsetof(UnitStatusInfo
, triggered_by
) },
5500 { "Triggers", "as", NULL
, offsetof(UnitStatusInfo
, triggers
) },
5501 { "InactiveExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, inactive_exit_timestamp
) },
5502 { "InactiveExitTimestampMonotonic", "t", NULL
, offsetof(UnitStatusInfo
, inactive_exit_timestamp_monotonic
) },
5503 { "ActiveEnterTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, active_enter_timestamp
) },
5504 { "ActiveExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, active_exit_timestamp
) },
5505 { "InactiveEnterTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, inactive_enter_timestamp
) },
5506 { "NeedDaemonReload", "b", NULL
, offsetof(UnitStatusInfo
, need_daemon_reload
) },
5507 { "Transient", "b", NULL
, offsetof(UnitStatusInfo
, transient
) },
5508 { "ExecMainPID", "u", NULL
, offsetof(UnitStatusInfo
, main_pid
) },
5509 { "MainPID", "u", map_main_pid
, 0 },
5510 { "ControlPID", "u", NULL
, offsetof(UnitStatusInfo
, control_pid
) },
5511 { "StatusText", "s", NULL
, offsetof(UnitStatusInfo
, status_text
) },
5512 { "PIDFile", "s", NULL
, offsetof(UnitStatusInfo
, pid_file
) },
5513 { "StatusErrno", "i", NULL
, offsetof(UnitStatusInfo
, status_errno
) },
5514 { "ExecMainStartTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, start_timestamp
) },
5515 { "ExecMainExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, exit_timestamp
) },
5516 { "ExecMainCode", "i", NULL
, offsetof(UnitStatusInfo
, exit_code
) },
5517 { "ExecMainStatus", "i", NULL
, offsetof(UnitStatusInfo
, exit_status
) },
5518 { "LogNamespace", "s", NULL
, offsetof(UnitStatusInfo
, log_namespace
) },
5519 { "ConditionTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, condition_timestamp
) },
5520 { "ConditionResult", "b", NULL
, offsetof(UnitStatusInfo
, condition_result
) },
5521 { "Conditions", "a(sbbsi)", map_conditions
, 0 },
5522 { "AssertTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, assert_timestamp
) },
5523 { "AssertResult", "b", NULL
, offsetof(UnitStatusInfo
, assert_result
) },
5524 { "Asserts", "a(sbbsi)", map_asserts
, 0 },
5525 { "NextElapseUSecRealtime", "t", NULL
, offsetof(UnitStatusInfo
, next_elapse_real
) },
5526 { "NextElapseUSecMonotonic", "t", NULL
, offsetof(UnitStatusInfo
, next_elapse_monotonic
) },
5527 { "NAccepted", "u", NULL
, offsetof(UnitStatusInfo
, n_accepted
) },
5528 { "NConnections", "u", NULL
, offsetof(UnitStatusInfo
, n_connections
) },
5529 { "NRefused", "u", NULL
, offsetof(UnitStatusInfo
, n_refused
) },
5530 { "Accept", "b", NULL
, offsetof(UnitStatusInfo
, accept
) },
5531 { "Listen", "a(ss)", map_listen
, offsetof(UnitStatusInfo
, listen
) },
5532 { "SysFSPath", "s", NULL
, offsetof(UnitStatusInfo
, sysfs_path
) },
5533 { "Where", "s", NULL
, offsetof(UnitStatusInfo
, where
) },
5534 { "What", "s", NULL
, offsetof(UnitStatusInfo
, what
) },
5535 { "MemoryCurrent", "t", NULL
, offsetof(UnitStatusInfo
, memory_current
) },
5536 { "DefaultMemoryMin", "t", NULL
, offsetof(UnitStatusInfo
, default_memory_min
) },
5537 { "DefaultMemoryLow", "t", NULL
, offsetof(UnitStatusInfo
, default_memory_low
) },
5538 { "MemoryMin", "t", NULL
, offsetof(UnitStatusInfo
, memory_min
) },
5539 { "MemoryLow", "t", NULL
, offsetof(UnitStatusInfo
, memory_low
) },
5540 { "MemoryHigh", "t", NULL
, offsetof(UnitStatusInfo
, memory_high
) },
5541 { "MemoryMax", "t", NULL
, offsetof(UnitStatusInfo
, memory_max
) },
5542 { "MemorySwapMax", "t", NULL
, offsetof(UnitStatusInfo
, memory_swap_max
) },
5543 { "MemoryLimit", "t", NULL
, offsetof(UnitStatusInfo
, memory_limit
) },
5544 { "CPUUsageNSec", "t", NULL
, offsetof(UnitStatusInfo
, cpu_usage_nsec
) },
5545 { "TasksCurrent", "t", NULL
, offsetof(UnitStatusInfo
, tasks_current
) },
5546 { "TasksMax", "t", NULL
, offsetof(UnitStatusInfo
, tasks_max
) },
5547 { "IPIngressBytes", "t", NULL
, offsetof(UnitStatusInfo
, ip_ingress_bytes
) },
5548 { "IPEgressBytes", "t", NULL
, offsetof(UnitStatusInfo
, ip_egress_bytes
) },
5549 { "IOReadBytes", "t", NULL
, offsetof(UnitStatusInfo
, io_read_bytes
) },
5550 { "IOWriteBytes", "t", NULL
, offsetof(UnitStatusInfo
, io_write_bytes
) },
5551 { "ExecCondition", "a(sasbttttuii)", map_exec
, 0 },
5552 { "ExecConditionEx", "a(sasasttttuii)", map_exec
, 0 },
5553 { "ExecStartPre", "a(sasbttttuii)", map_exec
, 0 },
5554 { "ExecStartPreEx", "a(sasasttttuii)", map_exec
, 0 },
5555 { "ExecStart", "a(sasbttttuii)", map_exec
, 0 },
5556 { "ExecStartEx", "a(sasasttttuii)", map_exec
, 0 },
5557 { "ExecStartPost", "a(sasbttttuii)", map_exec
, 0 },
5558 { "ExecStartPostEx", "a(sasasttttuii)", map_exec
, 0 },
5559 { "ExecReload", "a(sasbttttuii)", map_exec
, 0 },
5560 { "ExecReloadEx", "a(sasasttttuii)", map_exec
, 0 },
5561 { "ExecStopPre", "a(sasbttttuii)", map_exec
, 0 },
5562 { "ExecStop", "a(sasbttttuii)", map_exec
, 0 },
5563 { "ExecStopEx", "a(sasasttttuii)", map_exec
, 0 },
5564 { "ExecStopPost", "a(sasbttttuii)", map_exec
, 0 },
5565 { "ExecStopPostEx", "a(sasasttttuii)", map_exec
, 0 },
5569 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5570 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5571 _cleanup_set_free_ Set
*found_properties
= NULL
;
5572 _cleanup_(unit_status_info_free
) UnitStatusInfo info
= {
5573 .memory_current
= (uint64_t) -1,
5574 .memory_high
= CGROUP_LIMIT_MAX
,
5575 .memory_max
= CGROUP_LIMIT_MAX
,
5576 .memory_swap_max
= CGROUP_LIMIT_MAX
,
5577 .memory_limit
= (uint64_t) -1,
5578 .cpu_usage_nsec
= (uint64_t) -1,
5579 .tasks_current
= (uint64_t) -1,
5580 .tasks_max
= (uint64_t) -1,
5581 .ip_ingress_bytes
= (uint64_t) -1,
5582 .ip_egress_bytes
= (uint64_t) -1,
5583 .io_read_bytes
= UINT64_MAX
,
5584 .io_write_bytes
= UINT64_MAX
,
5592 log_debug("Showing one %s", path
);
5594 r
= bus_map_all_properties(
5596 "org.freedesktop.systemd1",
5598 show_mode
== SYSTEMCTL_SHOW_STATUS
? status_map
: property_map
,
5599 BUS_MAP_BOOLEAN_AS_BOOL
,
5604 return log_error_errno(r
, "Failed to get properties: %s", bus_error_message(&error
, r
));
5606 if (unit
&& streq_ptr(info
.load_state
, "not-found") && streq_ptr(info
.active_state
, "inactive")) {
5607 log_full(show_mode
== SYSTEMCTL_SHOW_STATUS
? LOG_ERR
: LOG_DEBUG
,
5608 "Unit %s could not be found.", unit
);
5610 if (show_mode
== SYSTEMCTL_SHOW_STATUS
)
5611 return EXIT_PROGRAM_OR_SERVICES_STATUS_UNKNOWN
;
5612 else if (show_mode
== SYSTEMCTL_SHOW_HELP
)
5621 if (show_mode
== SYSTEMCTL_SHOW_STATUS
) {
5622 print_status_info(bus
, &info
, ellipsized
);
5624 if (info
.active_state
&& !STR_IN_SET(info
.active_state
, "active", "reloading"))
5625 return EXIT_PROGRAM_NOT_RUNNING
;
5627 return EXIT_PROGRAM_RUNNING_OR_SERVICE_OK
;
5629 } else if (show_mode
== SYSTEMCTL_SHOW_HELP
) {
5630 show_unit_help(&info
);
5634 r
= sd_bus_message_rewind(reply
, true);
5636 return log_error_errno(r
, "Failed to rewind: %s", bus_error_message(&error
, r
));
5638 r
= bus_message_print_all_properties(reply
, print_property
, arg_properties
, arg_value
, arg_all
, &found_properties
);
5640 return bus_log_parse_error(r
);
5642 STRV_FOREACH(pp
, arg_properties
)
5643 if (!set_contains(found_properties
, *pp
))
5644 log_debug("Property %s does not exist.", *pp
);
5649 static int get_unit_dbus_path_by_pid(
5654 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5655 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5659 r
= sd_bus_call_method(
5661 "org.freedesktop.systemd1",
5662 "/org/freedesktop/systemd1",
5663 "org.freedesktop.systemd1.Manager",
5669 return log_error_errno(r
, "Failed to get unit for PID %"PRIu32
": %s", pid
, bus_error_message(&error
, r
));
5671 r
= sd_bus_message_read(reply
, "o", &u
);
5673 return bus_log_parse_error(r
);
5683 static int show_all(
5688 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5689 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
5694 r
= get_unit_list(bus
, NULL
, NULL
, &unit_infos
, 0, &reply
);
5698 (void) pager_open(arg_pager_flags
);
5702 typesafe_qsort(unit_infos
, c
, compare_unit_info
);
5704 for (u
= unit_infos
; u
< unit_infos
+ c
; u
++) {
5705 _cleanup_free_
char *p
= NULL
;
5707 p
= unit_dbus_path_from_name(u
->id
);
5711 r
= show_one(bus
, p
, u
->id
, SYSTEMCTL_SHOW_STATUS
, new_line
, ellipsized
);
5714 else if (r
> 0 && ret
== 0)
5721 static int show_system_status(sd_bus
*bus
) {
5722 char since1
[FORMAT_TIMESTAMP_RELATIVE_MAX
], since2
[FORMAT_TIMESTAMP_MAX
];
5723 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5724 _cleanup_(machine_info_clear
) struct machine_info mi
= {};
5725 _cleanup_free_
char *hn
= NULL
;
5726 const char *on
, *off
;
5729 hn
= gethostname_malloc();
5733 r
= bus_map_all_properties(
5735 "org.freedesktop.systemd1",
5736 "/org/freedesktop/systemd1",
5737 machine_info_property_map
,
5743 return log_error_errno(r
, "Failed to read server status: %s", bus_error_message(&error
, r
));
5745 if (streq_ptr(mi
.state
, "degraded")) {
5746 on
= ansi_highlight_red();
5747 off
= ansi_normal();
5748 } else if (streq_ptr(mi
.state
, "running")) {
5749 on
= ansi_highlight_green();
5750 off
= ansi_normal();
5752 on
= ansi_highlight_yellow();
5753 off
= ansi_normal();
5756 printf("%s%s%s %s\n", on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
, arg_host
? arg_host
: hn
);
5758 printf(" State: %s%s%s\n",
5759 on
, strna(mi
.state
), off
);
5761 printf(" Jobs: %" PRIu32
" queued\n", mi
.n_jobs
);
5762 printf(" Failed: %" PRIu32
" units\n", mi
.n_failed_units
);
5764 printf(" Since: %s; %s\n",
5765 format_timestamp(since2
, sizeof(since2
), mi
.timestamp
),
5766 format_timestamp_relative(since1
, sizeof(since1
), mi
.timestamp
));
5768 printf(" CGroup: %s\n", mi
.control_group
?: "/");
5769 if (IN_SET(arg_transport
,
5770 BUS_TRANSPORT_LOCAL
,
5771 BUS_TRANSPORT_MACHINE
)) {
5772 static const char prefix
[] = " ";
5776 if (c
> sizeof(prefix
) - 1)
5777 c
-= sizeof(prefix
) - 1;
5781 show_cgroup(SYSTEMD_CGROUP_CONTROLLER
, strempty(mi
.control_group
), prefix
, c
, get_output_flags());
5787 static int show(int argc
, char *argv
[], void *userdata
) {
5788 bool new_line
= false, ellipsized
= false;
5789 SystemctlShowMode show_mode
;
5795 show_mode
= systemctl_show_mode_from_string(argv
[0]);
5797 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
5798 "Invalid argument.");
5800 if (show_mode
== SYSTEMCTL_SHOW_HELP
&& argc
<= 1)
5801 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
5802 "'help' command expects one or more unit names.\n"
5803 "(Alternatively, help for systemctl itself may be shown with --help)");
5805 r
= acquire_bus(BUS_MANAGER
, &bus
);
5809 (void) pager_open(arg_pager_flags
);
5811 /* If no argument is specified inspect the manager itself */
5812 if (show_mode
== SYSTEMCTL_SHOW_PROPERTIES
&& argc
<= 1)
5813 return show_one(bus
, "/org/freedesktop/systemd1", NULL
, show_mode
, &new_line
, &ellipsized
);
5815 if (show_mode
== SYSTEMCTL_SHOW_STATUS
&& argc
<= 1) {
5817 show_system_status(bus
);
5821 ret
= show_all(bus
, &new_line
, &ellipsized
);
5823 _cleanup_free_
char **patterns
= NULL
;
5826 STRV_FOREACH(name
, strv_skip(argv
, 1)) {
5827 _cleanup_free_
char *path
= NULL
, *unit
= NULL
;
5830 if (safe_atou32(*name
, &id
) < 0) {
5831 if (strv_push(&patterns
, *name
) < 0)
5835 } else if (show_mode
== SYSTEMCTL_SHOW_PROPERTIES
) {
5836 /* Interpret as job id */
5837 if (asprintf(&path
, "/org/freedesktop/systemd1/job/%u", id
) < 0)
5841 /* Interpret as PID */
5842 r
= get_unit_dbus_path_by_pid(bus
, id
, &path
);
5848 r
= unit_name_from_dbus_path(path
, &unit
);
5853 r
= show_one(bus
, path
, unit
, show_mode
, &new_line
, &ellipsized
);
5856 else if (r
> 0 && ret
== 0)
5860 if (!strv_isempty(patterns
)) {
5861 _cleanup_strv_free_
char **names
= NULL
;
5863 r
= expand_names(bus
, patterns
, NULL
, &names
, NULL
);
5865 return log_error_errno(r
, "Failed to expand names: %m");
5867 r
= maybe_extend_with_unit_dependencies(bus
, &names
);
5871 STRV_FOREACH(name
, names
) {
5872 _cleanup_free_
char *path
;
5874 path
= unit_dbus_path_from_name(*name
);
5878 r
= show_one(bus
, path
, *name
, show_mode
, &new_line
, &ellipsized
);
5881 if (r
> 0 && ret
== 0)
5887 if (ellipsized
&& !arg_quiet
)
5888 printf("Hint: Some lines were ellipsized, use -l to show in full.\n");
5893 static int cat(int argc
, char *argv
[], void *userdata
) {
5894 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
5895 _cleanup_strv_free_
char **names
= NULL
;
5901 /* Include all units by default — i.e. continue as if the --all
5902 * option was used */
5903 if (strv_isempty(arg_states
))
5906 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
5907 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot remotely cat units.");
5909 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
5911 return log_error_errno(r
, "Failed to determine unit paths: %m");
5913 r
= acquire_bus(BUS_MANAGER
, &bus
);
5917 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
5919 return log_error_errno(r
, "Failed to expand names: %m");
5921 r
= maybe_extend_with_unit_dependencies(bus
, &names
);
5925 (void) pager_open(arg_pager_flags
);
5927 STRV_FOREACH(name
, names
) {
5928 _cleanup_free_
char *fragment_path
= NULL
;
5929 _cleanup_strv_free_
char **dropin_paths
= NULL
;
5931 r
= unit_find_paths(bus
, *name
, &lp
, false, &fragment_path
, &dropin_paths
);
5932 if (r
== -ERFKILL
) {
5933 printf("%s# Unit %s is masked%s.\n",
5934 ansi_highlight_magenta(),
5939 if (r
== -EKEYREJECTED
) {
5940 printf("%s# Unit %s could not be loaded.%s\n",
5941 ansi_highlight_magenta(),
5949 /* Skip units which have no on-disk counterpart, but
5950 * propagate the error to the user */
5960 if (need_daemon_reload(bus
, *name
) > 0) /* ignore errors (<0), this is informational output */
5962 "%s# Warning: %s changed on disk, the version systemd has loaded is outdated.\n"
5963 "%s# This output shows the current version of the unit's original fragment and drop-in files.\n"
5964 "%s# If fragments or drop-ins were added or removed, they are not properly reflected in this output.\n"
5965 "%s# Run 'systemctl%s daemon-reload' to reload units.%s\n",
5966 ansi_highlight_red(),
5968 ansi_highlight_red(),
5969 ansi_highlight_red(),
5970 ansi_highlight_red(),
5971 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user",
5974 r
= cat_files(fragment_path
, dropin_paths
, 0);
5982 static int set_property(int argc
, char *argv
[], void *userdata
) {
5983 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
5984 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5985 _cleanup_free_
char *n
= NULL
;
5990 r
= acquire_bus(BUS_MANAGER
, &bus
);
5994 polkit_agent_open_maybe();
5996 r
= sd_bus_message_new_method_call(
5999 "org.freedesktop.systemd1",
6000 "/org/freedesktop/systemd1",
6001 "org.freedesktop.systemd1.Manager",
6002 "SetUnitProperties");
6004 return bus_log_create_error(r
);
6006 r
= unit_name_mangle(argv
[1], arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, &n
);
6008 return log_error_errno(r
, "Failed to mangle unit name: %m");
6010 t
= unit_name_to_type(n
);
6012 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid unit type: %s", n
);
6014 r
= sd_bus_message_append(m
, "sb", n
, arg_runtime
);
6016 return bus_log_create_error(r
);
6018 r
= sd_bus_message_open_container(m
, SD_BUS_TYPE_ARRAY
, "(sv)");
6020 return bus_log_create_error(r
);
6022 r
= bus_append_unit_property_assignment_many(m
, t
, strv_skip(argv
, 2));
6026 r
= sd_bus_message_close_container(m
);
6028 return bus_log_create_error(r
);
6030 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6032 return log_error_errno(r
, "Failed to set unit properties on %s: %s", n
, bus_error_message(&error
, r
));
6037 static int daemon_reload(int argc
, char *argv
[], void *userdata
) {
6038 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6039 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6044 r
= acquire_bus(BUS_MANAGER
, &bus
);
6048 polkit_agent_open_maybe();
6050 switch (arg_action
) {
6057 method
= "Reexecute";
6060 case ACTION_SYSTEMCTL
:
6061 method
= streq(argv
[0], "daemon-reexec") ? "Reexecute" :
6062 /* "daemon-reload" */ "Reload";
6066 assert_not_reached("Unexpected action");
6069 r
= sd_bus_message_new_method_call(
6072 "org.freedesktop.systemd1",
6073 "/org/freedesktop/systemd1",
6074 "org.freedesktop.systemd1.Manager",
6077 return bus_log_create_error(r
);
6079 /* Note we use an extra-long timeout here. This is because a reload or reexec means generators are rerun which
6080 * are timed out after DEFAULT_TIMEOUT_USEC. Let's use twice that time here, so that the generators can have
6081 * their timeout, and for everything else there's the same time budget in place. */
6083 r
= sd_bus_call(bus
, m
, DEFAULT_TIMEOUT_USEC
* 2, &error
, NULL
);
6085 /* On reexecution, we expect a disconnect, not a reply */
6086 if (IN_SET(r
, -ETIMEDOUT
, -ECONNRESET
) && streq(method
, "Reexecute"))
6089 if (r
< 0 && arg_action
== ACTION_SYSTEMCTL
)
6090 return log_error_errno(r
, "Failed to reload daemon: %s", bus_error_message(&error
, r
));
6092 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
6093 * old ways of doing things, hence don't log any error in that case here. */
6095 return r
< 0 ? r
: 0;
6098 static int trivial_method(int argc
, char *argv
[], void *userdata
) {
6099 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6107 r
= acquire_bus(BUS_MANAGER
, &bus
);
6111 polkit_agent_open_maybe();
6114 streq(argv
[0], "clear-jobs") ||
6115 streq(argv
[0], "cancel") ? "ClearJobs" :
6116 streq(argv
[0], "reset-failed") ? "ResetFailed" :
6117 streq(argv
[0], "halt") ? "Halt" :
6118 streq(argv
[0], "reboot") ? "Reboot" :
6119 streq(argv
[0], "kexec") ? "KExec" :
6120 streq(argv
[0], "exit") ? "Exit" :
6121 /* poweroff */ "PowerOff";
6123 r
= sd_bus_call_method(
6125 "org.freedesktop.systemd1",
6126 "/org/freedesktop/systemd1",
6127 "org.freedesktop.systemd1.Manager",
6132 if (r
< 0 && arg_action
== ACTION_SYSTEMCTL
)
6133 return log_error_errno(r
, "Failed to execute operation: %s", bus_error_message(&error
, r
));
6135 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
6136 * old ways of doing things, hence don't log any error in that case here. */
6138 return r
< 0 ? r
: 0;
6141 static int reset_failed(int argc
, char *argv
[], void *userdata
) {
6142 _cleanup_strv_free_
char **names
= NULL
;
6148 return trivial_method(argc
, argv
, userdata
);
6150 r
= acquire_bus(BUS_MANAGER
, &bus
);
6154 polkit_agent_open_maybe();
6156 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
6158 return log_error_errno(r
, "Failed to expand names: %m");
6160 STRV_FOREACH(name
, names
) {
6161 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6163 q
= sd_bus_call_method(
6165 "org.freedesktop.systemd1",
6166 "/org/freedesktop/systemd1",
6167 "org.freedesktop.systemd1.Manager",
6173 log_error_errno(q
, "Failed to reset failed state of unit %s: %s", *name
, bus_error_message(&error
, q
));
6182 static int print_variable(const char *s
) {
6184 _cleanup_free_
char *esc
= NULL
;
6186 sep
= strchr(s
, '=');
6188 return log_error_errno(SYNTHETIC_ERRNO(EUCLEAN
),
6189 "Invalid environment block");
6191 esc
= shell_maybe_quote(sep
+ 1, ESCAPE_POSIX
);
6195 printf("%.*s=%s\n", (int)(sep
-s
), s
, esc
);
6199 static int show_environment(int argc
, char *argv
[], void *userdata
) {
6200 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6201 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
6206 r
= acquire_bus(BUS_MANAGER
, &bus
);
6210 (void) pager_open(arg_pager_flags
);
6212 r
= sd_bus_get_property(
6214 "org.freedesktop.systemd1",
6215 "/org/freedesktop/systemd1",
6216 "org.freedesktop.systemd1.Manager",
6222 return log_error_errno(r
, "Failed to get environment: %s", bus_error_message(&error
, r
));
6224 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "s");
6226 return bus_log_parse_error(r
);
6228 while ((r
= sd_bus_message_read_basic(reply
, SD_BUS_TYPE_STRING
, &text
)) > 0) {
6229 r
= print_variable(text
);
6234 return bus_log_parse_error(r
);
6236 r
= sd_bus_message_exit_container(reply
);
6238 return bus_log_parse_error(r
);
6243 static int switch_root(int argc
, char *argv
[], void *userdata
) {
6244 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6245 _cleanup_free_
char *cmdline_init
= NULL
;
6246 const char *root
, *init
;
6250 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
6251 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot switch root remotely.");
6253 if (argc
< 2 || argc
> 3)
6254 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Wrong number of arguments.");
6261 r
= proc_cmdline_get_key("init", 0, &cmdline_init
);
6263 log_debug_errno(r
, "Failed to parse /proc/cmdline: %m");
6265 init
= cmdline_init
;
6268 init
= empty_to_null(init
);
6270 const char *root_systemd_path
= NULL
, *root_init_path
= NULL
;
6272 root_systemd_path
= prefix_roota(root
, "/" SYSTEMD_BINARY_PATH
);
6273 root_init_path
= prefix_roota(root
, init
);
6275 /* If the passed init is actually the same as the
6276 * systemd binary, then let's suppress it. */
6277 if (files_same(root_init_path
, root_systemd_path
, 0) > 0)
6281 /* Instruct PID1 to exclude us from its killing spree applied during the transition. Otherwise we
6282 * would exit with a failure status even though the switch to the new root has succeed. */
6284 assert(saved_argv
[0]);
6285 saved_argv
[0][0] = '@';
6287 r
= acquire_bus(BUS_MANAGER
, &bus
);
6291 /* If we are slow to exit after the root switch, the new systemd instance
6292 * will send us a signal to terminate. Just ignore it and exit normally.
6293 * This way the unit does not end up as failed.
6295 r
= ignore_signals(SIGTERM
, -1);
6297 log_warning_errno(r
, "Failed to change disposition of SIGTERM to ignore: %m");
6299 log_debug("Switching root - root: %s; init: %s", root
, strna(init
));
6301 r
= sd_bus_call_method(
6303 "org.freedesktop.systemd1",
6304 "/org/freedesktop/systemd1",
6305 "org.freedesktop.systemd1.Manager",
6311 (void) default_signals(SIGTERM
, -1);
6313 return log_error_errno(r
, "Failed to switch root: %s", bus_error_message(&error
, r
));
6319 static int log_level(int argc
, char *argv
[], void *userdata
) {
6321 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6324 r
= acquire_bus(BUS_MANAGER
, &bus
);
6329 _cleanup_free_
char *level
= NULL
;
6331 r
= sd_bus_get_property_string(
6333 "org.freedesktop.systemd1",
6334 "/org/freedesktop/systemd1",
6335 "org.freedesktop.systemd1.Manager",
6340 return log_error_errno(r
, "Failed to get log level: %s", bus_error_message(&error
, r
));
6347 r
= sd_bus_set_property(
6349 "org.freedesktop.systemd1",
6350 "/org/freedesktop/systemd1",
6351 "org.freedesktop.systemd1.Manager",
6357 return log_error_errno(r
, "Failed to set log level: %s", bus_error_message(&error
, r
));
6363 static int log_target(int argc
, char *argv
[], void *userdata
) {
6365 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6368 r
= acquire_bus(BUS_MANAGER
, &bus
);
6373 _cleanup_free_
char *target
= NULL
;
6375 r
= sd_bus_get_property_string(
6377 "org.freedesktop.systemd1",
6378 "/org/freedesktop/systemd1",
6379 "org.freedesktop.systemd1.Manager",
6384 return log_error_errno(r
, "Failed to get log target: %s", bus_error_message(&error
, r
));
6391 r
= sd_bus_set_property(
6393 "org.freedesktop.systemd1",
6394 "/org/freedesktop/systemd1",
6395 "org.freedesktop.systemd1.Manager",
6401 return log_error_errno(r
, "Failed to set log target: %s", bus_error_message(&error
, r
));
6407 static int service_watchdogs(int argc
, char *argv
[], void *userdata
) {
6409 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6414 r
= acquire_bus(BUS_MANAGER
, &bus
);
6419 /* get ServiceWatchdogs */
6420 r
= sd_bus_get_property_trivial(
6422 "org.freedesktop.systemd1",
6423 "/org/freedesktop/systemd1",
6424 "org.freedesktop.systemd1.Manager",
6430 return log_error_errno(r
, "Failed to get service-watchdog state: %s", bus_error_message(&error
, r
));
6432 printf("%s\n", yes_no(!!b
));
6435 /* set ServiceWatchdogs */
6438 b
= parse_boolean(argv
[1]);
6440 return log_error_errno(b
, "Failed to parse service-watchdogs argument: %m");
6442 r
= sd_bus_set_property(
6444 "org.freedesktop.systemd1",
6445 "/org/freedesktop/systemd1",
6446 "org.freedesktop.systemd1.Manager",
6452 return log_error_errno(r
, "Failed to set service-watchdog state: %s", bus_error_message(&error
, r
));
6458 static int set_environment(int argc
, char *argv
[], void *userdata
) {
6459 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6460 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6468 r
= acquire_bus(BUS_MANAGER
, &bus
);
6472 polkit_agent_open_maybe();
6474 method
= streq(argv
[0], "set-environment")
6476 : "UnsetEnvironment";
6478 r
= sd_bus_message_new_method_call(
6481 "org.freedesktop.systemd1",
6482 "/org/freedesktop/systemd1",
6483 "org.freedesktop.systemd1.Manager",
6486 return bus_log_create_error(r
);
6488 r
= sd_bus_message_append_strv(m
, strv_skip(argv
, 1));
6490 return bus_log_create_error(r
);
6492 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6494 return log_error_errno(r
, "Failed to set environment: %s", bus_error_message(&error
, r
));
6499 static int import_environment(int argc
, char *argv
[], void *userdata
) {
6500 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6501 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6505 r
= acquire_bus(BUS_MANAGER
, &bus
);
6509 polkit_agent_open_maybe();
6511 r
= sd_bus_message_new_method_call(
6514 "org.freedesktop.systemd1",
6515 "/org/freedesktop/systemd1",
6516 "org.freedesktop.systemd1.Manager",
6519 return bus_log_create_error(r
);
6522 r
= sd_bus_message_append_strv(m
, environ
);
6526 r
= sd_bus_message_open_container(m
, 'a', "s");
6528 return bus_log_create_error(r
);
6530 STRV_FOREACH(a
, strv_skip(argv
, 1)) {
6532 if (!env_name_is_valid(*a
))
6533 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Not a valid environment variable name: %s", *a
);
6535 STRV_FOREACH(b
, environ
) {
6538 eq
= startswith(*b
, *a
);
6539 if (eq
&& *eq
== '=') {
6541 r
= sd_bus_message_append(m
, "s", *b
);
6543 return bus_log_create_error(r
);
6550 r
= sd_bus_message_close_container(m
);
6553 return bus_log_create_error(r
);
6555 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6557 return log_error_errno(r
, "Failed to import environment: %s", bus_error_message(&error
, r
));
6562 static int enable_sysv_units(const char *verb
, char **args
) {
6565 #if HAVE_SYSV_COMPAT
6566 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
6569 /* Processes all SysV units, and reshuffles the array so that afterwards only the native units remain */
6571 if (arg_scope
!= UNIT_FILE_SYSTEM
)
6574 if (getenv_bool("SYSTEMCTL_SKIP_SYSV") > 0)
6577 if (!STR_IN_SET(verb
,
6583 r
= lookup_paths_init(&paths
, arg_scope
, LOOKUP_PATHS_EXCLUDE_GENERATED
, arg_root
);
6590 const char *argv
[] = {
6591 ROOTLIBEXECDIR
"/systemd-sysv-install",
6598 _cleanup_free_
char *p
= NULL
, *q
= NULL
, *l
= NULL
, *v
= NULL
;
6599 bool found_native
= false, found_sysv
;
6607 if (!endswith(name
, ".service"))
6610 if (path_is_absolute(name
))
6613 j
= unit_file_exists(arg_scope
, &paths
, name
);
6614 if (j
< 0 && !IN_SET(j
, -ELOOP
, -ERFKILL
, -EADDRNOTAVAIL
))
6615 return log_error_errno(j
, "Failed to look up unit file state: %m");
6616 found_native
= j
!= 0;
6618 /* If we have both a native unit and a SysV script, enable/disable them both (below); for is-enabled,
6619 * prefer the native unit */
6620 if (found_native
&& streq(verb
, "is-enabled"))
6623 p
= path_join(arg_root
, SYSTEM_SYSVINIT_PATH
, name
);
6627 p
[strlen(p
) - STRLEN(".service")] = 0;
6628 found_sysv
= access(p
, F_OK
) >= 0;
6634 log_info("Synchronizing state of %s with SysV service script with %s.", name
, argv
[0]);
6636 log_info("%s is not a native service, redirecting to systemd-sysv-install.", name
);
6639 if (!isempty(arg_root
)) {
6640 q
= strjoin("--root=", arg_root
);
6647 /* Let's copy the verb, since it's still pointing directly into the original argv[] array we
6648 * got passed, but safe_fork() is likely going to rewrite that for the new child */
6654 argv
[c
++] = basename(p
);
6657 l
= strv_join((char**)argv
, " ");
6662 log_info("Executing: %s", l
);
6664 j
= safe_fork("(sysv-install)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
, &pid
);
6669 execv(argv
[0], (char**) argv
);
6670 log_error_errno(errno
, "Failed to execute %s: %m", argv
[0]);
6671 _exit(EXIT_FAILURE
);
6674 j
= wait_for_terminate_and_check("sysv-install", pid
, WAIT_LOG_ABNORMAL
);
6677 if (streq(verb
, "is-enabled")) {
6678 if (j
== EXIT_SUCCESS
) {
6687 } else if (j
!= EXIT_SUCCESS
)
6688 return -EBADE
; /* We don't warn here, under the assumption the script already showed an explanation */
6693 /* Remove this entry, so that we don't try enabling it as native unit */
6696 assert(args
[f
] == name
);
6697 strv_remove(args
+ f
, name
);
6704 static int mangle_names(const char *operation
, char **original_names
, char ***mangled_names
) {
6705 char **i
, **l
, **name
;
6708 l
= i
= new(char*, strv_length(original_names
) + 1);
6712 STRV_FOREACH(name
, original_names
) {
6714 /* When enabling units qualified path names are OK,
6715 * too, hence allow them explicitly. */
6717 if (is_path(*name
)) {
6724 r
= unit_name_mangle_with_suffix(*name
, operation
,
6725 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
6730 return log_error_errno(r
, "Failed to mangle unit name: %m");
6743 static int normalize_filenames(char **names
) {
6747 STRV_FOREACH(u
, names
)
6748 if (!path_is_absolute(*u
)) {
6749 char* normalized_path
;
6751 if (!isempty(arg_root
))
6752 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6753 "Non-absolute paths are not allowed when --root is used: %s",
6756 if (!strchr(*u
,'/'))
6757 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6758 "Link argument does contain at least one directory separator: %s",
6761 r
= path_make_absolute_cwd(*u
, &normalized_path
);
6765 free_and_replace(*u
, normalized_path
);
6771 static int normalize_names(char **names
, bool warn_if_path
) {
6773 bool was_path
= false;
6775 STRV_FOREACH(u
, names
) {
6781 r
= free_and_strdup(u
, basename(*u
));
6783 return log_error_errno(r
, "Failed to normalize unit file path: %m");
6788 if (warn_if_path
&& was_path
)
6789 log_warning("Warning: Can't execute disable on the unit file path. Proceeding with the unit name.");
6794 static int unit_exists(LookupPaths
*lp
, const char *unit
) {
6795 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6796 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6797 _cleanup_free_
char *path
= NULL
;
6798 static const struct bus_properties_map property_map
[] = {
6799 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
6800 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
)},
6803 UnitStatusInfo info
= {};
6807 if (unit_name_is_valid(unit
, UNIT_NAME_TEMPLATE
))
6808 return unit_find_template_path(unit
, lp
, NULL
, NULL
);
6810 path
= unit_dbus_path_from_name(unit
);
6814 r
= acquire_bus(BUS_MANAGER
, &bus
);
6818 r
= bus_map_all_properties(bus
, "org.freedesktop.systemd1", path
, property_map
, 0, &error
, &m
, &info
);
6820 return log_error_errno(r
, "Failed to get properties: %s", bus_error_message(&error
, r
));
6822 return !streq_ptr(info
.load_state
, "not-found") || !streq_ptr(info
.active_state
, "inactive");
6825 static int enable_unit(int argc
, char *argv
[], void *userdata
) {
6826 _cleanup_strv_free_
char **names
= NULL
;
6827 const char *verb
= argv
[0];
6828 UnitFileChange
*changes
= NULL
;
6829 size_t n_changes
= 0;
6830 int carries_install_info
= -1;
6831 bool ignore_carries_install_info
= arg_quiet
;
6837 r
= mangle_names("to enable", strv_skip(argv
, 1), &names
);
6841 r
= enable_sysv_units(verb
, names
);
6845 /* If the operation was fully executed by the SysV compat, let's finish early */
6846 if (strv_isempty(names
)) {
6847 if (arg_no_reload
|| install_client_side())
6849 return daemon_reload(argc
, argv
, userdata
);
6852 if (streq(verb
, "disable")) {
6853 r
= normalize_names(names
, true);
6858 if (streq(verb
, "link")) {
6859 r
= normalize_filenames(names
);
6864 if (install_client_side()) {
6865 UnitFileFlags flags
;
6867 flags
= args_to_flags();
6868 if (streq(verb
, "enable")) {
6869 r
= unit_file_enable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6870 carries_install_info
= r
;
6871 } else if (streq(verb
, "disable"))
6872 r
= unit_file_disable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6873 else if (streq(verb
, "reenable")) {
6874 r
= unit_file_reenable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6875 carries_install_info
= r
;
6876 } else if (streq(verb
, "link"))
6877 r
= unit_file_link(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6878 else if (streq(verb
, "preset")) {
6879 r
= unit_file_preset(arg_scope
, flags
, arg_root
, names
, arg_preset_mode
, &changes
, &n_changes
);
6880 } else if (streq(verb
, "mask"))
6881 r
= unit_file_mask(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6882 else if (streq(verb
, "unmask"))
6883 r
= unit_file_unmask(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6884 else if (streq(verb
, "revert"))
6885 r
= unit_file_revert(arg_scope
, arg_root
, names
, &changes
, &n_changes
);
6887 assert_not_reached("Unknown verb");
6889 unit_file_dump_changes(r
, verb
, changes
, n_changes
, arg_quiet
);
6894 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
, *m
= NULL
;
6895 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6896 bool expect_carries_install_info
= false;
6897 bool send_runtime
= true, send_force
= true, send_preset_mode
= false;
6901 if (STR_IN_SET(verb
, "mask", "unmask")) {
6903 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
6905 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
6909 STRV_FOREACH(name
, names
) {
6910 r
= unit_exists(&lp
, *name
);
6914 log_notice("Unit %s does not exist, proceeding anyway.", *name
);
6918 r
= acquire_bus(BUS_MANAGER
, &bus
);
6922 polkit_agent_open_maybe();
6924 if (streq(verb
, "enable")) {
6925 method
= "EnableUnitFiles";
6926 expect_carries_install_info
= true;
6927 } else if (streq(verb
, "disable")) {
6928 method
= "DisableUnitFiles";
6930 } else if (streq(verb
, "reenable")) {
6931 method
= "ReenableUnitFiles";
6932 expect_carries_install_info
= true;
6933 } else if (streq(verb
, "link"))
6934 method
= "LinkUnitFiles";
6935 else if (streq(verb
, "preset")) {
6937 if (arg_preset_mode
!= UNIT_FILE_PRESET_FULL
) {
6938 method
= "PresetUnitFilesWithMode";
6939 send_preset_mode
= true;
6941 method
= "PresetUnitFiles";
6943 expect_carries_install_info
= true;
6944 ignore_carries_install_info
= true;
6945 } else if (streq(verb
, "mask"))
6946 method
= "MaskUnitFiles";
6947 else if (streq(verb
, "unmask")) {
6948 method
= "UnmaskUnitFiles";
6950 } else if (streq(verb
, "revert")) {
6951 method
= "RevertUnitFiles";
6952 send_runtime
= send_force
= false;
6954 assert_not_reached("Unknown verb");
6956 r
= sd_bus_message_new_method_call(
6959 "org.freedesktop.systemd1",
6960 "/org/freedesktop/systemd1",
6961 "org.freedesktop.systemd1.Manager",
6964 return bus_log_create_error(r
);
6966 r
= sd_bus_message_append_strv(m
, names
);
6968 return bus_log_create_error(r
);
6970 if (send_preset_mode
) {
6971 r
= sd_bus_message_append(m
, "s", unit_file_preset_mode_to_string(arg_preset_mode
));
6973 return bus_log_create_error(r
);
6977 r
= sd_bus_message_append(m
, "b", arg_runtime
);
6979 return bus_log_create_error(r
);
6983 r
= sd_bus_message_append(m
, "b", arg_force
);
6985 return bus_log_create_error(r
);
6988 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
6990 return log_error_errno(r
, "Failed to %s unit: %s", verb
, bus_error_message(&error
, r
));
6992 if (expect_carries_install_info
) {
6993 r
= sd_bus_message_read(reply
, "b", &carries_install_info
);
6995 return bus_log_parse_error(r
);
6998 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
7002 /* Try to reload if enabled */
7004 r
= daemon_reload(argc
, argv
, userdata
);
7009 if (carries_install_info
== 0 && !ignore_carries_install_info
)
7010 log_notice("The unit files have no installation config (WantedBy=, RequiredBy=, Also=,\n"
7011 "Alias= settings in the [Install] section, and DefaultInstance= for template\n"
7012 "units). This means they are not meant to be enabled using systemctl.\n"
7013 " \n" /* trick: the space is needed so that the line does not get stripped from output */
7014 "Possible reasons for having this kind of units are:\n"
7015 "%1$s A unit may be statically enabled by being symlinked from another unit's\n"
7016 " .wants/ or .requires/ directory.\n"
7017 "%1$s A unit's purpose may be to act as a helper for some other unit which has\n"
7018 " a requirement dependency on it.\n"
7019 "%1$s A unit may be started when needed via activation (socket, path, timer,\n"
7020 " D-Bus, udev, scripted systemctl call, ...).\n"
7021 "%1$s In case of template units, the unit is meant to be enabled with some\n"
7022 " instance name specified.",
7023 special_glyph(SPECIAL_GLYPH_BULLET
));
7025 if (arg_now
&& STR_IN_SET(argv
[0], "enable", "disable", "mask")) {
7029 r
= acquire_bus(BUS_MANAGER
, &bus
);
7033 len
= strv_length(names
);
7035 char *new_args
[len
+ 2];
7037 new_args
[0] = (char*) (streq(argv
[0], "enable") ? "start" : "stop");
7038 for (i
= 0; i
< len
; i
++)
7039 new_args
[i
+ 1] = basename(names
[i
]);
7040 new_args
[i
+ 1] = NULL
;
7042 r
= start_unit(len
+ 1, new_args
, userdata
);
7047 unit_file_changes_free(changes
, n_changes
);
7052 static int add_dependency(int argc
, char *argv
[], void *userdata
) {
7053 _cleanup_strv_free_
char **names
= NULL
;
7054 _cleanup_free_
char *target
= NULL
;
7055 const char *verb
= argv
[0];
7056 UnitFileChange
*changes
= NULL
;
7057 size_t n_changes
= 0;
7064 r
= unit_name_mangle_with_suffix(argv
[1], "as target",
7065 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
7066 ".target", &target
);
7068 return log_error_errno(r
, "Failed to mangle unit name: %m");
7070 r
= mangle_names("as dependency", strv_skip(argv
, 2), &names
);
7074 if (streq(verb
, "add-wants"))
7076 else if (streq(verb
, "add-requires"))
7077 dep
= UNIT_REQUIRES
;
7079 assert_not_reached("Unknown verb");
7081 if (install_client_side()) {
7082 r
= unit_file_add_dependency(arg_scope
, args_to_flags(), arg_root
, names
, target
, dep
, &changes
, &n_changes
);
7083 unit_file_dump_changes(r
, "add dependency on", changes
, n_changes
, arg_quiet
);
7088 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
, *m
= NULL
;
7089 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7092 r
= acquire_bus(BUS_MANAGER
, &bus
);
7096 polkit_agent_open_maybe();
7098 r
= sd_bus_message_new_method_call(
7101 "org.freedesktop.systemd1",
7102 "/org/freedesktop/systemd1",
7103 "org.freedesktop.systemd1.Manager",
7104 "AddDependencyUnitFiles");
7106 return bus_log_create_error(r
);
7108 r
= sd_bus_message_append_strv(m
, names
);
7110 return bus_log_create_error(r
);
7112 r
= sd_bus_message_append(m
, "ssbb", target
, unit_dependency_to_string(dep
), arg_runtime
, arg_force
);
7114 return bus_log_create_error(r
);
7116 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
7118 return log_error_errno(r
, "Failed to add dependency: %s", bus_error_message(&error
, r
));
7120 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
7124 if (arg_no_reload
) {
7129 r
= daemon_reload(argc
, argv
, userdata
);
7133 unit_file_changes_free(changes
, n_changes
);
7138 static int preset_all(int argc
, char *argv
[], void *userdata
) {
7139 UnitFileChange
*changes
= NULL
;
7140 size_t n_changes
= 0;
7143 if (install_client_side()) {
7144 r
= unit_file_preset_all(arg_scope
, args_to_flags(), arg_root
, arg_preset_mode
, &changes
, &n_changes
);
7145 unit_file_dump_changes(r
, "preset", changes
, n_changes
, arg_quiet
);
7150 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7151 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7154 r
= acquire_bus(BUS_MANAGER
, &bus
);
7158 polkit_agent_open_maybe();
7160 r
= sd_bus_call_method(
7162 "org.freedesktop.systemd1",
7163 "/org/freedesktop/systemd1",
7164 "org.freedesktop.systemd1.Manager",
7165 "PresetAllUnitFiles",
7169 unit_file_preset_mode_to_string(arg_preset_mode
),
7173 return log_error_errno(r
, "Failed to preset all units: %s", bus_error_message(&error
, r
));
7175 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
7179 if (arg_no_reload
) {
7184 r
= daemon_reload(argc
, argv
, userdata
);
7188 unit_file_changes_free(changes
, n_changes
);
7193 static int show_installation_targets_client_side(const char *name
) {
7194 UnitFileChange
*changes
= NULL
;
7195 size_t n_changes
= 0, i
;
7196 UnitFileFlags flags
;
7200 p
= STRV_MAKE(name
);
7201 flags
= UNIT_FILE_DRY_RUN
|
7202 (arg_runtime
? UNIT_FILE_RUNTIME
: 0);
7204 r
= unit_file_disable(UNIT_FILE_SYSTEM
, flags
, NULL
, p
, &changes
, &n_changes
);
7206 return log_error_errno(r
, "Failed to get file links for %s: %m", name
);
7208 for (i
= 0; i
< n_changes
; i
++)
7209 if (changes
[i
].type
== UNIT_FILE_UNLINK
)
7210 printf(" %s\n", changes
[i
].path
);
7215 static int show_installation_targets(sd_bus
*bus
, const char *name
) {
7216 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7217 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7221 r
= sd_bus_call_method(
7223 "org.freedesktop.systemd1",
7224 "/org/freedesktop/systemd1",
7225 "org.freedesktop.systemd1.Manager",
7229 "sb", name
, arg_runtime
);
7231 return log_error_errno(r
, "Failed to get unit file links for %s: %s", name
, bus_error_message(&error
, r
));
7233 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "s");
7235 return bus_log_parse_error(r
);
7237 while ((r
= sd_bus_message_read(reply
, "s", &link
)) > 0)
7238 printf(" %s\n", link
);
7241 return bus_log_parse_error(r
);
7243 r
= sd_bus_message_exit_container(reply
);
7245 return bus_log_parse_error(r
);
7250 static int unit_is_enabled(int argc
, char *argv
[], void *userdata
) {
7251 _cleanup_strv_free_
char **names
= NULL
;
7256 r
= mangle_names("to check", strv_skip(argv
, 1), &names
);
7260 r
= enable_sysv_units(argv
[0], names
);
7266 if (install_client_side()) {
7267 STRV_FOREACH(name
, names
) {
7268 UnitFileState state
;
7270 r
= unit_file_get_state(arg_scope
, arg_root
, *name
, &state
);
7272 return log_error_errno(r
, "Failed to get unit file state for %s: %m", *name
);
7276 UNIT_FILE_ENABLED_RUNTIME
,
7279 UNIT_FILE_GENERATED
))
7283 puts(unit_file_state_to_string(state
));
7285 r
= show_installation_targets_client_side(*name
);
7294 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7297 r
= acquire_bus(BUS_MANAGER
, &bus
);
7301 STRV_FOREACH(name
, names
) {
7302 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7305 r
= sd_bus_call_method(
7307 "org.freedesktop.systemd1",
7308 "/org/freedesktop/systemd1",
7309 "org.freedesktop.systemd1.Manager",
7315 return log_error_errno(r
, "Failed to get unit file state for %s: %s", *name
, bus_error_message(&error
, r
));
7317 r
= sd_bus_message_read(reply
, "s", &s
);
7319 return bus_log_parse_error(r
);
7321 if (STR_IN_SET(s
, "enabled", "enabled-runtime", "static", "indirect", "generated"))
7327 r
= show_installation_targets(bus
, *name
);
7335 return enabled
? EXIT_SUCCESS
: EXIT_FAILURE
;
7338 static int match_startup_finished(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
7339 char **state
= userdata
;
7344 r
= sd_bus_get_property_string(
7345 sd_bus_message_get_bus(m
),
7346 "org.freedesktop.systemd1",
7347 "/org/freedesktop/systemd1",
7348 "org.freedesktop.systemd1.Manager",
7353 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m
)), r
);
7357 static int is_system_running(int argc
, char *argv
[], void *userdata
) {
7358 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7359 _cleanup_(sd_bus_slot_unrefp
) sd_bus_slot
*slot_startup_finished
= NULL
;
7360 _cleanup_(sd_event_unrefp
) sd_event
* event
= NULL
;
7361 _cleanup_free_
char *state
= NULL
;
7365 if (running_in_chroot() > 0 || (arg_transport
== BUS_TRANSPORT_LOCAL
&& !sd_booted())) {
7368 return EXIT_FAILURE
;
7371 r
= acquire_bus(BUS_MANAGER
, &bus
);
7376 r
= sd_event_default(&event
);
7378 r
= sd_bus_attach_event(bus
, event
, 0);
7380 r
= sd_bus_match_signal_async(
7382 &slot_startup_finished
,
7383 "org.freedesktop.systemd1",
7384 "/org/freedesktop/systemd1",
7385 "org.freedesktop.systemd1.Manager",
7387 match_startup_finished
, NULL
, &state
);
7389 log_warning_errno(r
, "Failed to request match for StartupFinished: %m");
7394 r
= sd_bus_get_property_string(
7396 "org.freedesktop.systemd1",
7397 "/org/freedesktop/systemd1",
7398 "org.freedesktop.systemd1.Manager",
7403 log_warning_errno(r
, "Failed to query system state: %s", bus_error_message(&error
, r
));
7407 return EXIT_FAILURE
;
7410 if (arg_wait
&& STR_IN_SET(state
, "initializing", "starting")) {
7411 r
= sd_event_loop(event
);
7413 log_warning_errno(r
, "Failed to get property from event loop: %m");
7416 return EXIT_FAILURE
;
7423 return streq(state
, "running") ? EXIT_SUCCESS
: EXIT_FAILURE
;
7426 static int create_edit_temp_file(const char *new_path
, const char *original_path
, char **ret_tmp_fn
) {
7427 _cleanup_free_
char *t
= NULL
;
7431 assert(original_path
);
7434 r
= tempfn_random(new_path
, NULL
, &t
);
7436 return log_error_errno(r
, "Failed to determine temporary filename for \"%s\": %m", new_path
);
7438 r
= mkdir_parents(new_path
, 0755);
7440 return log_error_errno(r
, "Failed to create directories for \"%s\": %m", new_path
);
7442 r
= copy_file(original_path
, t
, 0, 0644, 0, 0, COPY_REFLINK
);
7447 return log_error_errno(r
, "Failed to create temporary file \"%s\": %m", t
);
7450 return log_error_errno(r
, "Failed to create temporary file for \"%s\": %m", new_path
);
7452 *ret_tmp_fn
= TAKE_PTR(t
);
7457 static int get_file_to_edit(
7458 const LookupPaths
*paths
,
7462 _cleanup_free_
char *path
= NULL
, *run
= NULL
;
7467 path
= path_join(paths
->persistent_config
, name
);
7472 run
= path_join(paths
->runtime_config
, name
);
7478 if (access(path
, F_OK
) >= 0)
7479 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
7480 "Refusing to create \"%s\" because it would be overridden by \"%s\" anyway.",
7483 *ret_path
= TAKE_PTR(run
);
7485 *ret_path
= TAKE_PTR(path
);
7490 static int unit_file_create_new(
7491 const LookupPaths
*paths
,
7492 const char *unit_name
,
7494 char **ret_new_path
,
7495 char **ret_tmp_path
) {
7497 _cleanup_free_
char *new_path
= NULL
, *tmp_path
= NULL
;
7502 assert(ret_new_path
);
7503 assert(ret_tmp_path
);
7505 ending
= strjoina(unit_name
, suffix
);
7506 r
= get_file_to_edit(paths
, ending
, &new_path
);
7510 r
= create_edit_temp_file(new_path
, new_path
, &tmp_path
);
7514 *ret_new_path
= TAKE_PTR(new_path
);
7515 *ret_tmp_path
= TAKE_PTR(tmp_path
);
7520 static int unit_file_create_copy(
7521 const LookupPaths
*paths
,
7522 const char *unit_name
,
7523 const char *fragment_path
,
7524 char **ret_new_path
,
7525 char **ret_tmp_path
) {
7527 _cleanup_free_
char *new_path
= NULL
, *tmp_path
= NULL
;
7530 assert(fragment_path
);
7532 assert(ret_new_path
);
7533 assert(ret_tmp_path
);
7535 r
= get_file_to_edit(paths
, unit_name
, &new_path
);
7539 if (!path_equal(fragment_path
, new_path
) && access(new_path
, F_OK
) >= 0) {
7542 r
= ask_char(&response
, "yn", "\"%s\" already exists. Overwrite with \"%s\"? [(y)es, (n)o] ", new_path
, fragment_path
);
7545 if (response
!= 'y')
7546 return log_warning_errno(SYNTHETIC_ERRNO(EKEYREJECTED
), "%s skipped.", unit_name
);
7549 r
= create_edit_temp_file(new_path
, fragment_path
, &tmp_path
);
7553 *ret_new_path
= TAKE_PTR(new_path
);
7554 *ret_tmp_path
= TAKE_PTR(tmp_path
);
7559 static int run_editor(char **paths
) {
7564 r
= safe_fork("(editor)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
|FORK_WAIT
, NULL
);
7568 char **editor_args
= NULL
, **tmp_path
, **original_path
;
7569 size_t n_editor_args
= 0, i
= 1, argc
;
7570 const char **args
, *editor
, *p
;
7572 argc
= strv_length(paths
)/2 + 1;
7574 /* SYSTEMD_EDITOR takes precedence over EDITOR which takes precedence over VISUAL
7575 * If neither SYSTEMD_EDITOR nor EDITOR nor VISUAL are present,
7576 * we try to execute well known editors
7578 editor
= getenv("SYSTEMD_EDITOR");
7580 editor
= getenv("EDITOR");
7582 editor
= getenv("VISUAL");
7584 if (!isempty(editor
)) {
7585 editor_args
= strv_split(editor
, WHITESPACE
);
7588 _exit(EXIT_FAILURE
);
7590 n_editor_args
= strv_length(editor_args
);
7591 argc
+= n_editor_args
- 1;
7594 args
= newa(const char*, argc
+ 1);
7596 if (n_editor_args
> 0) {
7597 args
[0] = editor_args
[0];
7598 for (; i
< n_editor_args
; i
++)
7599 args
[i
] = editor_args
[i
];
7602 STRV_FOREACH_PAIR(original_path
, tmp_path
, paths
)
7603 args
[i
++] = *tmp_path
;
7606 if (n_editor_args
> 0)
7607 execvp(args
[0], (char* const*) args
);
7609 FOREACH_STRING(p
, "editor", "nano", "vim", "vi") {
7611 execvp(p
, (char* const*) args
);
7612 /* We do not fail if the editor doesn't exist
7613 * because we want to try each one of them before
7616 if (errno
!= ENOENT
) {
7617 log_error_errno(errno
, "Failed to execute %s: %m", editor
);
7618 _exit(EXIT_FAILURE
);
7622 log_error("Cannot edit unit(s), no editor available. Please set either $SYSTEMD_EDITOR, $EDITOR or $VISUAL.");
7623 _exit(EXIT_FAILURE
);
7629 static int find_paths_to_edit(sd_bus
*bus
, char **names
, char ***paths
) {
7630 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
7637 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
7641 STRV_FOREACH(name
, names
) {
7642 _cleanup_free_
char *path
= NULL
, *new_path
= NULL
, *tmp_path
= NULL
, *tmp_name
= NULL
;
7643 const char *unit_name
;
7645 r
= unit_find_paths(bus
, *name
, &lp
, false, &path
, NULL
);
7646 if (r
== -EKEYREJECTED
) {
7647 /* If loading of the unit failed server side complete, then the server won't tell us the unit
7648 * file path. In that case, find the file client side. */
7649 log_debug_errno(r
, "Unit '%s' was not loaded correctly, retrying client-side.", *name
);
7650 r
= unit_find_paths(bus
, *name
, &lp
, true, &path
, NULL
);
7653 return log_error_errno(r
, "Unit '%s' masked, cannot edit.", *name
);
7661 log_info("Run 'systemctl edit%s --force --full %s' to create a new unit.",
7662 arg_scope
== UNIT_FILE_GLOBAL
? " --global" :
7663 arg_scope
== UNIT_FILE_USER
? " --user" : "",
7668 /* Create a new unit from scratch */
7670 r
= unit_file_create_new(&lp
, unit_name
,
7671 arg_full
? NULL
: ".d/override.conf",
7672 &new_path
, &tmp_path
);
7676 unit_name
= basename(path
);
7677 /* We follow unit aliases, but we need to propagate the instance */
7678 if (unit_name_is_valid(*name
, UNIT_NAME_INSTANCE
) &&
7679 unit_name_is_valid(unit_name
, UNIT_NAME_TEMPLATE
)) {
7680 _cleanup_free_
char *instance
= NULL
;
7682 r
= unit_name_to_instance(*name
, &instance
);
7686 r
= unit_name_replace_instance(unit_name
, instance
, &tmp_name
);
7690 unit_name
= tmp_name
;
7694 r
= unit_file_create_copy(&lp
, unit_name
, path
, &new_path
, &tmp_path
);
7696 r
= unit_file_create_new(&lp
, unit_name
, ".d/override.conf", &new_path
, &tmp_path
);
7701 r
= strv_push_pair(paths
, new_path
, tmp_path
);
7705 new_path
= tmp_path
= NULL
;
7711 static int edit(int argc
, char *argv
[], void *userdata
) {
7712 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
7713 _cleanup_strv_free_
char **names
= NULL
;
7714 _cleanup_strv_free_
char **paths
= NULL
;
7715 char **original
, **tmp
;
7720 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit units if not on a tty.");
7722 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
7723 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit units remotely.");
7725 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
7727 return log_error_errno(r
, "Failed to determine unit paths: %m");
7729 r
= acquire_bus(BUS_MANAGER
, &bus
);
7733 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
7735 return log_error_errno(r
, "Failed to expand names: %m");
7737 STRV_FOREACH(tmp
, names
) {
7738 r
= unit_is_masked(bus
, &lp
, *tmp
);
7742 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit %s: unit is masked.", *tmp
);
7745 r
= find_paths_to_edit(bus
, names
, &paths
);
7749 if (strv_isempty(paths
))
7752 r
= run_editor(paths
);
7756 STRV_FOREACH_PAIR(original
, tmp
, paths
) {
7757 /* If the temporary file is empty we ignore it.
7758 * This allows the user to cancel the modification.
7760 if (null_or_empty_path(*tmp
)) {
7761 log_warning("Editing \"%s\" canceled: temporary file is empty.", *original
);
7765 r
= rename(*tmp
, *original
);
7767 r
= log_error_errno(errno
, "Failed to rename \"%s\" to \"%s\": %m", *tmp
, *original
);
7774 if (!arg_no_reload
&& !install_client_side())
7775 r
= daemon_reload(argc
, argv
, userdata
);
7778 STRV_FOREACH_PAIR(original
, tmp
, paths
) {
7779 (void) unlink(*tmp
);
7781 /* Removing empty dropin dirs */
7783 _cleanup_free_
char *dir
;
7785 dir
= dirname_malloc(*original
);
7789 /* no need to check if the dir is empty, rmdir
7790 * does nothing if it is not the case.
7799 static int systemctl_help(void) {
7800 _cleanup_free_
char *link
= NULL
;
7803 (void) pager_open(arg_pager_flags
);
7805 r
= terminal_urlify_man("systemctl", "1", &link
);
7809 printf("%1$s [OPTIONS...] COMMAND ...\n\n"
7810 "%5$sQuery or send control commands to the system manager.%6$s\n"
7811 "\n%3$sUnit Commands:%4$s\n"
7812 " list-units [PATTERN...] List units currently in memory\n"
7813 " list-sockets [PATTERN...] List socket units currently in memory,\n"
7814 " ordered by address\n"
7815 " list-timers [PATTERN...] List timer units currently in memory,\n"
7816 " ordered by next elapse\n"
7817 " start UNIT... Start (activate) one or more units\n"
7818 " stop UNIT... Stop (deactivate) one or more units\n"
7819 " reload UNIT... Reload one or more units\n"
7820 " restart UNIT... Start or restart one or more units\n"
7821 " try-restart UNIT... Restart one or more units if active\n"
7822 " reload-or-restart UNIT... Reload one or more units if possible,\n"
7823 " otherwise start or restart\n"
7824 " try-reload-or-restart UNIT... If active, reload one or more units,\n"
7825 " if supported, otherwise restart\n"
7826 " isolate UNIT Start one unit and stop all others\n"
7827 " kill UNIT... Send signal to processes of a unit\n"
7828 " clean UNIT... Clean runtime, cache, state, logs or\n"
7829 " configuration of unit\n"
7830 " is-active PATTERN... Check whether units are active\n"
7831 " is-failed PATTERN... Check whether units are failed\n"
7832 " status [PATTERN...|PID...] Show runtime status of one or more units\n"
7833 " show [PATTERN...|JOB...] Show properties of one or more\n"
7834 " units/jobs or the manager\n"
7835 " cat PATTERN... Show files and drop-ins of specified units\n"
7836 " set-property UNIT PROPERTY=VALUE... Sets one or more properties of a unit\n"
7837 " help PATTERN...|PID... Show manual for one or more units\n"
7838 " reset-failed [PATTERN...] Reset failed state for all, one, or more\n"
7840 " list-dependencies [UNIT...] Recursively show units which are required\n"
7841 " or wanted by the units or by which those\n"
7842 " units are required or wanted"
7843 "\n%3$sUnit File Commands:%4$s\n"
7844 " list-unit-files [PATTERN...] List installed unit files\n"
7845 " enable [UNIT...|PATH...] Enable one or more unit files\n"
7846 " disable UNIT... Disable one or more unit files\n"
7847 " reenable UNIT... Reenable one or more unit files\n"
7848 " preset UNIT... Enable/disable one or more unit files\n"
7849 " based on preset configuration\n"
7850 " preset-all Enable/disable all unit files based on\n"
7851 " preset configuration\n"
7852 " is-enabled UNIT... Check whether unit files are enabled\n"
7853 " mask UNIT... Mask one or more units\n"
7854 " unmask UNIT... Unmask one or more units\n"
7855 " link PATH... Link one or more units files into\n"
7856 " the search path\n"
7857 " revert UNIT... Revert one or more unit files to vendor\n"
7859 " add-wants TARGET UNIT... Add 'Wants' dependency for the target\n"
7860 " on specified one or more units\n"
7861 " add-requires TARGET UNIT... Add 'Requires' dependency for the target\n"
7862 " on specified one or more units\n"
7863 " edit UNIT... Edit one or more unit files\n"
7864 " get-default Get the name of the default target\n"
7865 " set-default TARGET Set the default target\n"
7866 "\n%3$sMachine Commands:%4$s\n"
7867 " list-machines [PATTERN...] List local containers and host\n"
7868 "\n%3$sJob Commands:%4$s\n"
7869 " list-jobs [PATTERN...] List jobs\n"
7870 " cancel [JOB...] Cancel all, one, or more jobs\n"
7871 "\n%3$sEnvironment Commands:%4$s\n"
7872 " show-environment Dump environment\n"
7873 " set-environment VARIABLE=VALUE... Set one or more environment variables\n"
7874 " unset-environment VARIABLE... Unset one or more environment variables\n"
7875 " import-environment [VARIABLE...] Import all or some environment variables\n"
7876 "\n%3$sManager State Commands:%4$s\n"
7877 " daemon-reload Reload systemd manager configuration\n"
7878 " daemon-reexec Reexecute systemd manager\n"
7879 " log-level [LEVEL] Get/set logging threshold for manager\n"
7880 " log-target [TARGET] Get/set logging target for manager\n"
7881 " service-watchdogs [BOOL] Get/set service watchdog state\n"
7882 "\n%3$sSystem Commands:%4$s\n"
7883 " is-system-running Check whether system is fully running\n"
7884 " default Enter system default mode\n"
7885 " rescue Enter system rescue mode\n"
7886 " emergency Enter system emergency mode\n"
7887 " halt Shut down and halt the system\n"
7888 " poweroff Shut down and power-off the system\n"
7889 " reboot [ARG] Shut down and reboot the system\n"
7890 " kexec Shut down and reboot the system with kexec\n"
7891 " exit [EXIT_CODE] Request user instance or container exit\n"
7892 " switch-root ROOT [INIT] Change to a different root file system\n"
7893 " suspend Suspend the system\n"
7894 " hibernate Hibernate the system\n"
7895 " hybrid-sleep Hibernate and suspend the system\n"
7896 " suspend-then-hibernate Suspend the system, wake after a period of\n"
7897 " time, and hibernate"
7898 "\n%3$sOptions:%4$s\n"
7899 " -h --help Show this help\n"
7900 " --version Show package version\n"
7901 " --system Connect to system manager\n"
7902 " --user Connect to user service manager\n"
7903 " -H --host=[USER@]HOST Operate on remote host\n"
7904 " -M --machine=CONTAINER Operate on a local container\n"
7905 " -t --type=TYPE List units of a particular type\n"
7906 " --state=STATE List units with particular LOAD or SUB or ACTIVE state\n"
7907 " --failed Shorcut for --state=failed\n"
7908 " -p --property=NAME Show only properties by this name\n"
7909 " -a --all Show all properties/all units currently in memory,\n"
7910 " including dead/empty ones. To list all units installed\n"
7911 " on the system, use 'list-unit-files' instead.\n"
7912 " -l --full Don't ellipsize unit names on output\n"
7913 " -r --recursive Show unit list of host and local containers\n"
7914 " --reverse Show reverse dependencies with 'list-dependencies'\n"
7915 " --with-dependencies Show unit dependencies with 'status', 'cat',\n"
7916 " 'list-units', and 'list-unit-files'.\n"
7917 " --job-mode=MODE Specify how to deal with already queued jobs, when\n"
7918 " queueing a new job\n"
7919 " -T --show-transaction When enqueuing a unit job, show full transaction\n"
7920 " --show-types When showing sockets, explicitly show their type\n"
7921 " --value When showing properties, only print the value\n"
7922 " -i --ignore-inhibitors When shutting down or sleeping, ignore inhibitors\n"
7923 " --kill-who=WHO Whom to send signal to\n"
7924 " -s --signal=SIGNAL Which signal to send\n"
7925 " --what=RESOURCES Which types of resources to remove\n"
7926 " --now Start or stop unit after enabling or disabling it\n"
7927 " --dry-run Only print what would be done\n"
7928 " Currently supported by verbs: halt, poweroff, reboot,\n"
7929 " kexec, suspend, hibernate, suspend-then-hibernate,\n"
7930 " hybrid-sleep, default, rescue, emergency, and exit.\n"
7931 " -q --quiet Suppress output\n"
7932 " --wait For (re)start, wait until service stopped again\n"
7933 " For is-system-running, wait until startup is completed\n"
7934 " --no-block Do not wait until operation finished\n"
7935 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7936 " --no-reload Don't reload daemon after en-/dis-abling unit files\n"
7937 " --no-legend Do not print a legend (column headers and hints)\n"
7938 " --no-pager Do not pipe output into a pager\n"
7939 " --no-ask-password Do not ask for system passwords\n"
7940 " --global Enable/disable/mask unit files globally\n"
7941 " --runtime Enable/disable/mask unit files temporarily until next\n"
7943 " -f --force When enabling unit files, override existing symlinks\n"
7944 " When shutting down, execute action immediately\n"
7945 " --preset-mode= Apply only enable, only disable, or all presets\n"
7946 " --root=PATH Enable/disable/mask unit files in the specified root\n"
7948 " -n --lines=INTEGER Number of journal entries to show\n"
7949 " -o --output=STRING Change journal output mode (short, short-precise,\n"
7950 " short-iso, short-iso-precise, short-full,\n"
7951 " short-monotonic, short-unix,\n"
7952 " verbose, export, json, json-pretty, json-sse, cat)\n"
7953 " --firmware-setup Tell the firmware to show the setup menu on next boot\n"
7954 " --boot-loader-menu=TIME\n"
7955 " Boot into boot loader menu on next boot\n"
7956 " --boot-loader-entry=NAME\n"
7957 " Boot into a specific boot loader entry on next boot\n"
7958 " --plain Print unit dependencies as a list instead of a tree\n"
7959 "\nSee the %2$s for details.\n"
7960 , program_invocation_short_name
7962 , ansi_underline(), ansi_normal()
7963 , ansi_highlight(), ansi_normal()
7969 static int halt_help(void) {
7970 _cleanup_free_
char *link
= NULL
;
7973 r
= terminal_urlify_man("halt", "8", &link
);
7977 printf("%s [OPTIONS...]%s\n"
7978 "\n%s%s the system.%s\n"
7980 " --help Show this help\n"
7981 " --halt Halt the machine\n"
7982 " -p --poweroff Switch off the machine\n"
7983 " --reboot Reboot the machine\n"
7984 " -f --force Force immediate halt/power-off/reboot\n"
7985 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
7986 " -d --no-wtmp Don't write wtmp record\n"
7987 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7988 "\nSee the %s for details.\n"
7989 , program_invocation_short_name
7990 , arg_action
== ACTION_REBOOT
? " [ARG]" : ""
7992 , arg_action
== ACTION_REBOOT
? "Reboot" :
7993 arg_action
== ACTION_POWEROFF
? "Power off" :
8002 static int shutdown_help(void) {
8003 _cleanup_free_
char *link
= NULL
;
8006 r
= terminal_urlify_man("shutdown", "8", &link
);
8010 printf("%s [OPTIONS...] [TIME] [WALL...]\n"
8011 "\n%sShut down the system.%s\n"
8013 " --help Show this help\n"
8014 " -H --halt Halt the machine\n"
8015 " -P --poweroff Power-off the machine\n"
8016 " -r --reboot Reboot the machine\n"
8017 " -h Equivalent to --poweroff, overridden by --halt\n"
8018 " -k Don't halt/power-off/reboot, just send warnings\n"
8019 " --no-wall Don't send wall message before halt/power-off/reboot\n"
8020 " -c Cancel a pending shutdown\n"
8021 "\nSee the %s for details.\n"
8022 , program_invocation_short_name
8023 , ansi_highlight(), ansi_normal()
8030 static int telinit_help(void) {
8031 _cleanup_free_
char *link
= NULL
;
8034 r
= terminal_urlify_man("telinit", "8", &link
);
8038 printf("%s [OPTIONS...] COMMAND\n\n"
8039 "%sSend control commands to the init daemon.%s\n"
8041 " 0 Power-off the machine\n"
8042 " 6 Reboot the machine\n"
8043 " 2, 3, 4, 5 Start runlevelX.target unit\n"
8044 " 1, s, S Enter rescue mode\n"
8045 " q, Q Reload init daemon configuration\n"
8046 " u, U Reexecute init daemon\n"
8048 " --help Show this help\n"
8049 " --no-wall Don't send wall message before halt/power-off/reboot\n"
8050 "\nSee the %s for details.\n"
8051 , program_invocation_short_name
8052 , ansi_highlight(), ansi_normal()
8059 static int runlevel_help(void) {
8060 _cleanup_free_
char *link
= NULL
;
8063 r
= terminal_urlify_man("runlevel", "8", &link
);
8067 printf("%s [OPTIONS...]\n"
8068 "\n%sPrints the previous and current runlevel of the init system.%s\n"
8070 " --help Show this help\n"
8071 "\nSee the %s for details.\n"
8072 , program_invocation_short_name
8073 , ansi_highlight(), ansi_normal()
8080 static void help_types(void) {
8082 puts("Available unit types:");
8084 DUMP_STRING_TABLE(unit_type
, UnitType
, _UNIT_TYPE_MAX
);
8087 static void help_states(void) {
8089 puts("Available unit load states:");
8090 DUMP_STRING_TABLE(unit_load_state
, UnitLoadState
, _UNIT_LOAD_STATE_MAX
);
8093 puts("\nAvailable unit active states:");
8094 DUMP_STRING_TABLE(unit_active_state
, UnitActiveState
, _UNIT_ACTIVE_STATE_MAX
);
8097 puts("\nAvailable unit file states:");
8098 DUMP_STRING_TABLE(unit_file_state
, UnitFileState
, _UNIT_FILE_STATE_MAX
);
8101 puts("\nAvailable automount unit substates:");
8102 DUMP_STRING_TABLE(automount_state
, AutomountState
, _AUTOMOUNT_STATE_MAX
);
8105 puts("\nAvailable device unit substates:");
8106 DUMP_STRING_TABLE(device_state
, DeviceState
, _DEVICE_STATE_MAX
);
8109 puts("\nAvailable mount unit substates:");
8110 DUMP_STRING_TABLE(mount_state
, MountState
, _MOUNT_STATE_MAX
);
8113 puts("\nAvailable path unit substates:");
8114 DUMP_STRING_TABLE(path_state
, PathState
, _PATH_STATE_MAX
);
8117 puts("\nAvailable scope unit substates:");
8118 DUMP_STRING_TABLE(scope_state
, ScopeState
, _SCOPE_STATE_MAX
);
8121 puts("\nAvailable service unit substates:");
8122 DUMP_STRING_TABLE(service_state
, ServiceState
, _SERVICE_STATE_MAX
);
8125 puts("\nAvailable slice unit substates:");
8126 DUMP_STRING_TABLE(slice_state
, SliceState
, _SLICE_STATE_MAX
);
8129 puts("\nAvailable socket unit substates:");
8130 DUMP_STRING_TABLE(socket_state
, SocketState
, _SOCKET_STATE_MAX
);
8133 puts("\nAvailable swap unit substates:");
8134 DUMP_STRING_TABLE(swap_state
, SwapState
, _SWAP_STATE_MAX
);
8137 puts("\nAvailable target unit substates:");
8138 DUMP_STRING_TABLE(target_state
, TargetState
, _TARGET_STATE_MAX
);
8141 puts("\nAvailable timer unit substates:");
8142 DUMP_STRING_TABLE(timer_state
, TimerState
, _TIMER_STATE_MAX
);
8145 static int help_boot_loader_entry(void) {
8146 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
8147 _cleanup_strv_free_
char **l
= NULL
;
8152 r
= acquire_bus(BUS_FULL
, &bus
);
8156 r
= sd_bus_get_property_strv(
8158 "org.freedesktop.login1",
8159 "/org/freedesktop/login1",
8160 "org.freedesktop.login1.Manager",
8161 "BootLoaderEntries",
8165 return log_error_errno(r
, "Failed to enumerate boot loader entries: %s", bus_error_message(&error
, r
));
8167 if (strv_isempty(l
))
8168 return log_error_errno(SYNTHETIC_ERRNO(ENODATA
), "No boot loader entries discovered.");
8176 static int systemctl_parse_argv(int argc
, char *argv
[]) {
8185 ARG_IGNORE_DEPENDENCIES
,
8198 ARG_NO_ASK_PASSWORD
,
8206 ARG_BOOT_LOADER_MENU
,
8207 ARG_BOOT_LOADER_ENTRY
,
8210 ARG_WITH_DEPENDENCIES
,
8215 static const struct option options
[] = {
8216 { "help", no_argument
, NULL
, 'h' },
8217 { "version", no_argument
, NULL
, ARG_VERSION
},
8218 { "type", required_argument
, NULL
, 't' },
8219 { "property", required_argument
, NULL
, 'p' },
8220 { "all", no_argument
, NULL
, 'a' },
8221 { "reverse", no_argument
, NULL
, ARG_REVERSE
},
8222 { "after", no_argument
, NULL
, ARG_AFTER
},
8223 { "before", no_argument
, NULL
, ARG_BEFORE
},
8224 { "show-types", no_argument
, NULL
, ARG_SHOW_TYPES
},
8225 { "failed", no_argument
, NULL
, ARG_FAILED
}, /* compatibility only */
8226 { "full", no_argument
, NULL
, 'l' },
8227 { "job-mode", required_argument
, NULL
, ARG_JOB_MODE
},
8228 { "fail", no_argument
, NULL
, ARG_FAIL
}, /* compatibility only */
8229 { "irreversible", no_argument
, NULL
, ARG_IRREVERSIBLE
}, /* compatibility only */
8230 { "ignore-dependencies", no_argument
, NULL
, ARG_IGNORE_DEPENDENCIES
}, /* compatibility only */
8231 { "ignore-inhibitors", no_argument
, NULL
, 'i' },
8232 { "value", no_argument
, NULL
, ARG_VALUE
},
8233 { "user", no_argument
, NULL
, ARG_USER
},
8234 { "system", no_argument
, NULL
, ARG_SYSTEM
},
8235 { "global", no_argument
, NULL
, ARG_GLOBAL
},
8236 { "wait", no_argument
, NULL
, ARG_WAIT
},
8237 { "no-block", no_argument
, NULL
, ARG_NO_BLOCK
},
8238 { "no-legend", no_argument
, NULL
, ARG_NO_LEGEND
},
8239 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
8240 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8241 { "dry-run", no_argument
, NULL
, ARG_DRY_RUN
},
8242 { "quiet", no_argument
, NULL
, 'q' },
8243 { "root", required_argument
, NULL
, ARG_ROOT
},
8244 { "force", no_argument
, NULL
, 'f' },
8245 { "no-reload", no_argument
, NULL
, ARG_NO_RELOAD
},
8246 { "kill-who", required_argument
, NULL
, ARG_KILL_WHO
},
8247 { "signal", required_argument
, NULL
, 's' },
8248 { "no-ask-password", no_argument
, NULL
, ARG_NO_ASK_PASSWORD
},
8249 { "host", required_argument
, NULL
, 'H' },
8250 { "machine", required_argument
, NULL
, 'M' },
8251 { "runtime", no_argument
, NULL
, ARG_RUNTIME
},
8252 { "lines", required_argument
, NULL
, 'n' },
8253 { "output", required_argument
, NULL
, 'o' },
8254 { "plain", no_argument
, NULL
, ARG_PLAIN
},
8255 { "state", required_argument
, NULL
, ARG_STATE
},
8256 { "recursive", no_argument
, NULL
, 'r' },
8257 { "with-dependencies", no_argument
, NULL
, ARG_WITH_DEPENDENCIES
},
8258 { "preset-mode", required_argument
, NULL
, ARG_PRESET_MODE
},
8259 { "firmware-setup", no_argument
, NULL
, ARG_FIRMWARE_SETUP
},
8260 { "boot-loader-menu", required_argument
, NULL
, ARG_BOOT_LOADER_MENU
},
8261 { "boot-loader-entry", required_argument
, NULL
, ARG_BOOT_LOADER_ENTRY
},
8262 { "now", no_argument
, NULL
, ARG_NOW
},
8263 { "message", required_argument
, NULL
, ARG_MESSAGE
},
8264 { "show-transaction", no_argument
, NULL
, 'T' },
8265 { "what", required_argument
, NULL
, ARG_WHAT
},
8274 /* we default to allowing interactive authorization only in systemctl (not in the legacy commands) */
8275 arg_ask_password
= true;
8277 while ((c
= getopt_long(argc
, argv
, "ht:p:alqfs:H:M:n:o:iTr.::", options
, NULL
)) >= 0)
8282 return systemctl_help();
8290 if (isempty(optarg
))
8291 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8292 "--type= requires arguments.");
8294 for (p
= optarg
;;) {
8295 _cleanup_free_
char *type
= NULL
;
8297 r
= extract_first_word(&p
, &type
, ",", 0);
8299 return log_error_errno(r
, "Failed to parse type: %s", optarg
);
8303 if (streq(type
, "help")) {
8308 if (unit_type_from_string(type
) >= 0) {
8309 if (strv_consume(&arg_types
, TAKE_PTR(type
)) < 0)
8314 /* It's much nicer to use --state= for
8315 * load states, but let's support this
8316 * in --types= too for compatibility
8317 * with old versions */
8318 if (unit_load_state_from_string(type
) >= 0) {
8319 if (strv_consume(&arg_states
, TAKE_PTR(type
)) < 0)
8324 log_error("Unknown unit type or load state '%s'.", type
);
8325 return log_info_errno(SYNTHETIC_ERRNO(EINVAL
),
8326 "Use -t help to see a list of allowed values.");
8333 /* Make sure that if the empty property list was specified, we won't show any
8335 if (isempty(optarg
) && !arg_properties
) {
8336 arg_properties
= new0(char*, 1);
8337 if (!arg_properties
)
8342 for (p
= optarg
;;) {
8343 _cleanup_free_
char *prop
= NULL
;
8345 r
= extract_first_word(&p
, &prop
, ",", 0);
8347 return log_error_errno(r
, "Failed to parse property: %s", optarg
);
8351 if (strv_consume(&arg_properties
, TAKE_PTR(prop
)) < 0)
8356 /* If the user asked for a particular
8357 * property, show it to him, even if it is
8368 arg_dependency
= DEPENDENCY_REVERSE
;
8372 arg_dependency
= DEPENDENCY_AFTER
;
8373 arg_jobs_after
= true;
8377 arg_dependency
= DEPENDENCY_BEFORE
;
8378 arg_jobs_before
= true;
8381 case ARG_SHOW_TYPES
:
8382 arg_show_types
= true;
8390 arg_job_mode
= optarg
;
8394 arg_job_mode
= "fail";
8397 case ARG_IRREVERSIBLE
:
8398 arg_job_mode
= "replace-irreversibly";
8401 case ARG_IGNORE_DEPENDENCIES
:
8402 arg_job_mode
= "ignore-dependencies";
8406 arg_scope
= UNIT_FILE_USER
;
8410 arg_scope
= UNIT_FILE_SYSTEM
;
8414 arg_scope
= UNIT_FILE_GLOBAL
;
8422 arg_no_block
= true;
8426 arg_no_legend
= true;
8430 arg_pager_flags
|= PAGER_DISABLE
;
8438 r
= parse_path_argument_and_warn(optarg
, false, &arg_root
);
8448 if (strv_extend(&arg_states
, "failed") < 0)
8466 arg_no_reload
= true;
8470 arg_kill_who
= optarg
;
8474 if (streq(optarg
, "help")) {
8475 DUMP_STRING_TABLE(signal
, int, _NSIG
);
8479 arg_signal
= signal_from_string(optarg
);
8481 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8482 "Failed to parse signal string %s.",
8486 case ARG_NO_ASK_PASSWORD
:
8487 arg_ask_password
= false;
8491 arg_transport
= BUS_TRANSPORT_REMOTE
;
8496 arg_transport
= BUS_TRANSPORT_MACHINE
;
8505 if (safe_atou(optarg
, &arg_lines
) < 0)
8506 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8507 "Failed to parse lines '%s'",
8512 if (streq(optarg
, "help")) {
8513 DUMP_STRING_TABLE(output_mode
, OutputMode
, _OUTPUT_MODE_MAX
);
8517 arg_output
= output_mode_from_string(optarg
);
8519 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8520 "Unknown output '%s'.",
8525 arg_ignore_inhibitors
= true;
8532 case ARG_FIRMWARE_SETUP
:
8533 arg_firmware_setup
= true;
8536 case ARG_BOOT_LOADER_MENU
:
8538 r
= parse_sec(optarg
, &arg_boot_loader_menu
);
8540 return log_error_errno(r
, "Failed to parse --boot-loader-menu= argument '%s': %m", optarg
);
8544 case ARG_BOOT_LOADER_ENTRY
:
8546 if (streq(optarg
, "help")) { /* Yes, this means, "help" is not a valid boot loader entry name we can deal with */
8547 r
= help_boot_loader_entry();
8554 arg_boot_loader_entry
= empty_to_null(optarg
);
8560 if (isempty(optarg
))
8561 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8562 "--state= requires arguments.");
8564 for (p
= optarg
;;) {
8565 _cleanup_free_
char *s
= NULL
;
8567 r
= extract_first_word(&p
, &s
, ",", 0);
8569 return log_error_errno(r
, "Failed to parse state: %s", optarg
);
8573 if (streq(s
, "help")) {
8578 if (strv_consume(&arg_states
, TAKE_PTR(s
)) < 0)
8586 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
8587 "--recursive requires root privileges.");
8589 arg_recursive
= true;
8592 case ARG_PRESET_MODE
:
8593 if (streq(optarg
, "help")) {
8594 DUMP_STRING_TABLE(unit_file_preset_mode
, UnitFilePresetMode
, _UNIT_FILE_PRESET_MAX
);
8598 arg_preset_mode
= unit_file_preset_mode_from_string(optarg
);
8599 if (arg_preset_mode
< 0)
8600 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8601 "Failed to parse preset mode: %s.", optarg
);
8610 if (strv_extend(&arg_wall
, optarg
) < 0)
8615 arg_show_transaction
= true;
8618 case ARG_WITH_DEPENDENCIES
:
8619 arg_with_dependencies
= true;
8625 if (isempty(optarg
))
8626 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "--what= requires arguments.");
8628 for (p
= optarg
;;) {
8629 _cleanup_free_
char *k
= NULL
;
8631 r
= extract_first_word(&p
, &k
, ",", 0);
8633 return log_error_errno(r
, "Failed to parse directory type: %s", optarg
);
8637 if (streq(k
, "help")) {
8646 r
= strv_consume(&arg_clean_what
, TAKE_PTR(k
));
8655 /* Output an error mimicking getopt, and print a hint afterwards */
8656 log_error("%s: invalid option -- '.'", program_invocation_name
);
8657 log_notice("Hint: to specify units starting with a dash, use \"--\":\n"
8658 " %s [OPTIONS...] COMMAND -- -.%s ...",
8659 program_invocation_name
, optarg
?: "mount");
8666 assert_not_reached("Unhandled option");
8669 if (arg_transport
!= BUS_TRANSPORT_LOCAL
&& arg_scope
!= UNIT_FILE_SYSTEM
)
8670 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8671 "Cannot access user instance remotely.");
8673 if (arg_wait
&& arg_no_block
)
8674 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8675 "--wait may not be combined with --no-block.");
8680 static int halt_parse_argv(int argc
, char *argv
[]) {
8688 static const struct option options
[] = {
8689 { "help", no_argument
, NULL
, ARG_HELP
},
8690 { "halt", no_argument
, NULL
, ARG_HALT
},
8691 { "poweroff", no_argument
, NULL
, 'p' },
8692 { "reboot", no_argument
, NULL
, ARG_REBOOT
},
8693 { "force", no_argument
, NULL
, 'f' },
8694 { "wtmp-only", no_argument
, NULL
, 'w' },
8695 { "no-wtmp", no_argument
, NULL
, 'd' },
8696 { "no-sync", no_argument
, NULL
, 'n' },
8697 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8706 if (utmp_get_runlevel(&runlevel
, NULL
) >= 0)
8707 if (IN_SET(runlevel
, '0', '6'))
8710 while ((c
= getopt_long(argc
, argv
, "pfwdnih", options
, NULL
)) >= 0)
8717 arg_action
= ACTION_HALT
;
8721 if (arg_action
!= ACTION_REBOOT
)
8722 arg_action
= ACTION_POWEROFF
;
8726 arg_action
= ACTION_REBOOT
;
8751 /* Compatibility nops */
8758 assert_not_reached("Unhandled option");
8761 if (arg_action
== ACTION_REBOOT
&& (argc
== optind
|| argc
== optind
+ 1)) {
8762 r
= update_reboot_parameter_and_warn(argc
== optind
+ 1 ? argv
[optind
] : NULL
, false);
8765 } else if (optind
< argc
)
8766 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8767 "Too many arguments.");
8772 static int shutdown_parse_argv(int argc
, char *argv
[]) {
8778 static const struct option options
[] = {
8779 { "help", no_argument
, NULL
, ARG_HELP
},
8780 { "halt", no_argument
, NULL
, 'H' },
8781 { "poweroff", no_argument
, NULL
, 'P' },
8782 { "reboot", no_argument
, NULL
, 'r' },
8783 { "kexec", no_argument
, NULL
, 'K' }, /* not documented extension */
8784 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8794 while ((c
= getopt_long(argc
, argv
, "HPrhkKat:fFc", options
, NULL
)) >= 0)
8798 return shutdown_help();
8801 arg_action
= ACTION_HALT
;
8805 arg_action
= ACTION_POWEROFF
;
8810 arg_action
= ACTION_KEXEC
;
8812 arg_action
= ACTION_REBOOT
;
8816 arg_action
= ACTION_KEXEC
;
8820 if (arg_action
!= ACTION_HALT
)
8821 arg_action
= ACTION_POWEROFF
;
8833 case 't': /* Note that we also ignore any passed argument to -t, not just the -t itself */
8836 /* Compatibility nops */
8840 arg_action
= ACTION_CANCEL_SHUTDOWN
;
8847 assert_not_reached("Unhandled option");
8850 if (argc
> optind
&& arg_action
!= ACTION_CANCEL_SHUTDOWN
) {
8851 r
= parse_shutdown_time_spec(argv
[optind
], &arg_when
);
8853 log_error("Failed to parse time specification: %s", argv
[optind
]);
8857 arg_when
= now(CLOCK_REALTIME
) + USEC_PER_MINUTE
;
8859 if (argc
> optind
&& arg_action
== ACTION_CANCEL_SHUTDOWN
)
8860 /* No time argument for shutdown cancel */
8861 wall
= argv
+ optind
;
8862 else if (argc
> optind
+ 1)
8863 /* We skip the time argument */
8864 wall
= argv
+ optind
+ 1;
8867 arg_wall
= strv_copy(wall
);
8877 static int telinit_parse_argv(int argc
, char *argv
[]) {
8883 static const struct option options
[] = {
8884 { "help", no_argument
, NULL
, ARG_HELP
},
8885 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8889 static const struct {
8893 { '0', ACTION_POWEROFF
},
8894 { '6', ACTION_REBOOT
},
8895 { '1', ACTION_RESCUE
},
8896 { '2', ACTION_RUNLEVEL2
},
8897 { '3', ACTION_RUNLEVEL3
},
8898 { '4', ACTION_RUNLEVEL4
},
8899 { '5', ACTION_RUNLEVEL5
},
8900 { 's', ACTION_RESCUE
},
8901 { 'S', ACTION_RESCUE
},
8902 { 'q', ACTION_RELOAD
},
8903 { 'Q', ACTION_RELOAD
},
8904 { 'u', ACTION_REEXEC
},
8905 { 'U', ACTION_REEXEC
}
8914 while ((c
= getopt_long(argc
, argv
, "", options
, NULL
)) >= 0)
8918 return telinit_help();
8928 assert_not_reached("Unhandled option");
8932 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8933 "%s: required argument missing.",
8934 program_invocation_short_name
);
8936 if (optind
+ 1 < argc
)
8937 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8938 "Too many arguments.");
8940 if (strlen(argv
[optind
]) != 1)
8941 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8942 "Expected single character argument.");
8944 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
8945 if (table
[i
].from
== argv
[optind
][0])
8948 if (i
>= ELEMENTSOF(table
))
8949 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8950 "Unknown command '%s'.", argv
[optind
]);
8952 arg_action
= table
[i
].to
;
8959 static int runlevel_parse_argv(int argc
, char *argv
[]) {
8964 static const struct option options
[] = {
8965 { "help", no_argument
, NULL
, ARG_HELP
},
8974 while ((c
= getopt_long(argc
, argv
, "", options
, NULL
)) >= 0)
8978 return runlevel_help();
8984 assert_not_reached("Unhandled option");
8988 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8989 "Too many arguments.");
8994 static int parse_argv(int argc
, char *argv
[]) {
8998 if (program_invocation_short_name
) {
9000 if (strstr(program_invocation_short_name
, "halt")) {
9001 arg_action
= ACTION_HALT
;
9002 return halt_parse_argv(argc
, argv
);
9004 } else if (strstr(program_invocation_short_name
, "poweroff")) {
9005 arg_action
= ACTION_POWEROFF
;
9006 return halt_parse_argv(argc
, argv
);
9008 } else if (strstr(program_invocation_short_name
, "reboot")) {
9010 arg_action
= ACTION_KEXEC
;
9012 arg_action
= ACTION_REBOOT
;
9013 return halt_parse_argv(argc
, argv
);
9015 } else if (strstr(program_invocation_short_name
, "shutdown")) {
9016 arg_action
= ACTION_POWEROFF
;
9017 return shutdown_parse_argv(argc
, argv
);
9019 } else if (strstr(program_invocation_short_name
, "init")) {
9021 /* Matches invocations as "init" as well as "telinit", which are synonymous when run as PID !=
9024 * On SysV "telinit" was the official command to communicate with PID 1, but "init" would
9025 * redirect itself to "telinit" if called with PID != 1. We follow the same logic here still,
9026 * though we add one level of indirection, as we implement "telinit" in "systemctl". Hence, for
9027 * us if you invoke "init" you get "systemd", but it will execve() "systemctl" immediately with
9028 * argv[] unmodified if PID is != 1. If you invoke "telinit" you directly get "systemctl". In
9029 * both cases we shall do the same thing, which is why we do strstr(p_i_s_n, "init") here, as a
9030 * quick way to match both.
9032 * Also see redirect_telinit() in src/core/main.c. */
9034 if (sd_booted() > 0) {
9035 arg_action
= _ACTION_INVALID
;
9036 return telinit_parse_argv(argc
, argv
);
9038 /* Hmm, so some other init system is running, we need to forward this request to
9039 * it. For now we simply guess that it is Upstart. */
9041 (void) rlimit_nofile_safe();
9042 execv(TELINIT
, argv
);
9044 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
9045 "Couldn't find an alternative telinit implementation to spawn.");
9048 } else if (strstr(program_invocation_short_name
, "runlevel")) {
9049 arg_action
= ACTION_RUNLEVEL
;
9050 return runlevel_parse_argv(argc
, argv
);
9054 arg_action
= ACTION_SYSTEMCTL
;
9055 return systemctl_parse_argv(argc
, argv
);
9058 #if HAVE_SYSV_COMPAT
9059 _pure_
static int action_to_runlevel(void) {
9060 static const char table
[_ACTION_MAX
] = {
9061 [ACTION_HALT
] = '0',
9062 [ACTION_POWEROFF
] = '0',
9063 [ACTION_REBOOT
] = '6',
9064 [ACTION_RUNLEVEL2
] = '2',
9065 [ACTION_RUNLEVEL3
] = '3',
9066 [ACTION_RUNLEVEL4
] = '4',
9067 [ACTION_RUNLEVEL5
] = '5',
9068 [ACTION_RESCUE
] = '1'
9071 assert(arg_action
>= 0 && arg_action
< _ACTION_MAX
);
9072 return table
[arg_action
];
9076 static int systemctl_main(int argc
, char *argv
[]) {
9077 static const Verb verbs
[] = {
9078 { "list-units", VERB_ANY
, VERB_ANY
, VERB_DEFAULT
|VERB_ONLINE_ONLY
, list_units
},
9079 { "list-unit-files", VERB_ANY
, VERB_ANY
, 0, list_unit_files
},
9080 { "list-sockets", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_sockets
},
9081 { "list-timers", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_timers
},
9082 { "list-jobs", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_jobs
},
9083 { "list-machines", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_machines
},
9084 { "clear-jobs", VERB_ANY
, 1, VERB_ONLINE_ONLY
, trivial_method
},
9085 { "cancel", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, cancel_job
},
9086 { "start", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9087 { "stop", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9088 { "condstop", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with ALTLinux */
9089 { "reload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9090 { "restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9091 { "try-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9092 { "reload-or-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9093 { "reload-or-try-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with old systemctl <= 228 */
9094 { "try-reload-or-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9095 { "force-reload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with SysV */
9096 { "condreload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with ALTLinux */
9097 { "condrestart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with RH */
9098 { "isolate", 2, 2, VERB_ONLINE_ONLY
, start_unit
},
9099 { "kill", 2, VERB_ANY
, VERB_ONLINE_ONLY
, kill_unit
},
9100 { "clean", 2, VERB_ANY
, VERB_ONLINE_ONLY
, clean_unit
},
9101 { "is-active", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_active
},
9102 { "check", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_active
}, /* deprecated alias of is-active */
9103 { "is-failed", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_failed
},
9104 { "show", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
9105 { "cat", 2, VERB_ANY
, VERB_ONLINE_ONLY
, cat
},
9106 { "status", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
9107 { "help", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
9108 { "daemon-reload", VERB_ANY
, 1, VERB_ONLINE_ONLY
, daemon_reload
},
9109 { "daemon-reexec", VERB_ANY
, 1, VERB_ONLINE_ONLY
, daemon_reload
},
9110 { "log-level", VERB_ANY
, 2, 0, log_level
},
9111 { "log-target", VERB_ANY
, 2, 0, log_target
},
9112 { "service-watchdogs", VERB_ANY
, 2, 0, service_watchdogs
},
9113 { "show-environment", VERB_ANY
, 1, VERB_ONLINE_ONLY
, show_environment
},
9114 { "set-environment", 2, VERB_ANY
, VERB_ONLINE_ONLY
, set_environment
},
9115 { "unset-environment", 2, VERB_ANY
, VERB_ONLINE_ONLY
, set_environment
},
9116 { "import-environment", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, import_environment
},
9117 { "halt", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9118 { "poweroff", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9119 { "reboot", VERB_ANY
, 2, VERB_ONLINE_ONLY
, start_system_special
},
9120 { "kexec", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9121 { "suspend", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9122 { "hibernate", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9123 { "hybrid-sleep", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9124 { "suspend-then-hibernate",VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9125 { "default", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_special
},
9126 { "rescue", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9127 { "emergency", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9128 { "exit", VERB_ANY
, 2, VERB_ONLINE_ONLY
, start_special
},
9129 { "reset-failed", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, reset_failed
},
9130 { "enable", 2, VERB_ANY
, 0, enable_unit
},
9131 { "disable", 2, VERB_ANY
, 0, enable_unit
},
9132 { "is-enabled", 2, VERB_ANY
, 0, unit_is_enabled
},
9133 { "reenable", 2, VERB_ANY
, 0, enable_unit
},
9134 { "preset", 2, VERB_ANY
, 0, enable_unit
},
9135 { "preset-all", VERB_ANY
, 1, 0, preset_all
},
9136 { "mask", 2, VERB_ANY
, 0, enable_unit
},
9137 { "unmask", 2, VERB_ANY
, 0, enable_unit
},
9138 { "link", 2, VERB_ANY
, 0, enable_unit
},
9139 { "revert", 2, VERB_ANY
, 0, enable_unit
},
9140 { "switch-root", 2, VERB_ANY
, VERB_ONLINE_ONLY
, switch_root
},
9141 { "list-dependencies", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_dependencies
},
9142 { "set-default", 2, 2, 0, set_default
},
9143 { "get-default", VERB_ANY
, 1, 0, get_default
},
9144 { "set-property", 3, VERB_ANY
, VERB_ONLINE_ONLY
, set_property
},
9145 { "is-system-running", VERB_ANY
, 1, 0, is_system_running
},
9146 { "add-wants", 3, VERB_ANY
, 0, add_dependency
},
9147 { "add-requires", 3, VERB_ANY
, 0, add_dependency
},
9148 { "edit", 2, VERB_ANY
, VERB_ONLINE_ONLY
, edit
},
9152 return dispatch_verb(argc
, argv
, verbs
, NULL
);
9155 static int reload_with_fallback(void) {
9156 /* First, try systemd via D-Bus. */
9157 if (daemon_reload(0, NULL
, NULL
) >= 0)
9160 /* Nothing else worked, so let's try signals */
9161 assert(IN_SET(arg_action
, ACTION_RELOAD
, ACTION_REEXEC
));
9163 if (kill(1, arg_action
== ACTION_RELOAD
? SIGHUP
: SIGTERM
) < 0)
9164 return log_error_errno(errno
, "kill() failed: %m");
9169 static int start_with_fallback(void) {
9170 /* First, try systemd via D-Bus. */
9171 if (start_unit(0, NULL
, NULL
) == 0)
9174 #if HAVE_SYSV_COMPAT
9175 /* Nothing else worked, so let's try /dev/initctl */
9176 if (talk_initctl(action_to_runlevel()) > 0)
9180 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
9181 "Failed to talk to init daemon.");
9184 static int halt_now(enum action a
) {
9185 /* The kernel will automatically flush ATA disks and suchlike on reboot(), but the file systems need to be
9186 * synced explicitly in advance. */
9187 if (!arg_no_sync
&& !arg_dry_run
)
9190 /* Make sure C-A-D is handled by the kernel from this point on... */
9192 (void) reboot(RB_ENABLE_CAD
);
9198 log_info("Halting.");
9201 (void) reboot(RB_HALT_SYSTEM
);
9204 case ACTION_POWEROFF
:
9206 log_info("Powering off.");
9209 (void) reboot(RB_POWER_OFF
);
9214 return reboot_with_parameter(REBOOT_FALLBACK
|
9215 (arg_quiet
? 0 : REBOOT_LOG
) |
9216 (arg_dry_run
? REBOOT_DRY_RUN
: 0));
9219 assert_not_reached("Unknown action.");
9223 static int logind_schedule_shutdown(void) {
9226 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
9227 char date
[FORMAT_TIMESTAMP_MAX
];
9229 const char *log_action
;
9233 r
= acquire_bus(BUS_FULL
, &bus
);
9237 switch (arg_action
) {
9240 log_action
= "Shutdown";
9242 case ACTION_POWEROFF
:
9243 action
= "poweroff";
9244 log_action
= "Shutdown";
9248 log_action
= "Reboot via kexec";
9252 log_action
= "Shutdown";
9257 log_action
= "Reboot";
9262 action
= strjoina("dry-", action
);
9264 (void) logind_set_wall_message();
9266 r
= sd_bus_call_method(
9268 "org.freedesktop.login1",
9269 "/org/freedesktop/login1",
9270 "org.freedesktop.login1.Manager",
9278 return log_warning_errno(r
, "Failed to call ScheduleShutdown in logind, proceeding with immediate shutdown: %s", bus_error_message(&error
, r
));
9281 log_info("%s scheduled for %s, use 'shutdown -c' to cancel.", log_action
, format_timestamp(date
, sizeof(date
), arg_when
));
9284 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
9285 "Cannot schedule shutdown without logind support, proceeding with immediate shutdown.");
9289 static int halt_main(void) {
9292 r
= logind_check_inhibitors(arg_action
);
9296 /* Delayed shutdown requested, and was successful */
9297 if (arg_when
> 0 && logind_schedule_shutdown() == 0)
9299 /* no delay, or logind failed or is not at all available */
9301 if (geteuid() != 0) {
9302 if (arg_dry_run
|| arg_force
> 0) {
9303 (void) must_be_root();
9307 /* Try logind if we are a normal user and no special
9308 * mode applies. Maybe polkit allows us to shutdown
9310 if (IN_SET(arg_action
, ACTION_POWEROFF
, ACTION_REBOOT
, ACTION_HALT
)) {
9311 r
= logind_reboot(arg_action
);
9314 if (IN_SET(r
, -EOPNOTSUPP
, -EINPROGRESS
))
9315 /* requested operation is not
9316 * supported on the local system or
9317 * already in progress */
9319 /* on all other errors, try low-level operation */
9323 /* In order to minimize the difference between operation with and
9324 * without logind, we explicitly enable non-blocking mode for this,
9325 * as logind's shutdown operations are always non-blocking. */
9326 arg_no_block
= true;
9328 if (!arg_dry_run
&& !arg_force
)
9329 return start_with_fallback();
9331 assert(geteuid() == 0);
9334 if (sd_booted() > 0)
9335 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
9337 r
= utmp_put_shutdown();
9339 log_warning_errno(r
, "Failed to write utmp record: %m");
9346 r
= halt_now(arg_action
);
9347 return log_error_errno(r
, "Failed to reboot: %m");
9350 static int runlevel_main(void) {
9351 int r
, runlevel
, previous
;
9353 r
= utmp_get_runlevel(&runlevel
, &previous
);
9360 previous
<= 0 ? 'N' : previous
,
9361 runlevel
<= 0 ? 'N' : runlevel
);
9366 static int logind_cancel_shutdown(void) {
9368 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
9372 r
= acquire_bus(BUS_FULL
, &bus
);
9376 (void) logind_set_wall_message();
9378 r
= sd_bus_call_method(
9380 "org.freedesktop.login1",
9381 "/org/freedesktop/login1",
9382 "org.freedesktop.login1.Manager",
9383 "CancelScheduledShutdown",
9387 return log_warning_errno(r
, "Failed to talk to logind, shutdown hasn't been cancelled: %s", bus_error_message(&error
, r
));
9391 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
9392 "Not compiled with logind support, cannot cancel scheduled shutdowns.");
9396 static int run(int argc
, char *argv
[]) {
9399 setlocale(LC_ALL
, "");
9400 log_parse_environment();
9403 /* The journal merging logic potentially needs a lot of fds. */
9404 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE
);
9408 /* Explicitly not on_tty() to avoid setting cached value.
9409 * This becomes relevant for piping output which might be
9411 original_stdout_is_tty
= isatty(STDOUT_FILENO
);
9413 r
= parse_argv(argc
, argv
);
9417 if (arg_action
!= ACTION_SYSTEMCTL
&& running_in_chroot() > 0) {
9419 log_info("Running in chroot, ignoring request.");
9424 /* systemctl_main() will print an error message for the bus
9425 * connection, but only if it needs to */
9427 switch (arg_action
) {
9429 case ACTION_SYSTEMCTL
:
9430 r
= systemctl_main(argc
, argv
);
9433 /* Legacy command aliases set arg_action. They provide some fallbacks,
9434 * e.g. to tell sysvinit to reboot after you have installed systemd
9438 case ACTION_POWEROFF
:
9444 case ACTION_RUNLEVEL2
:
9445 case ACTION_RUNLEVEL3
:
9446 case ACTION_RUNLEVEL4
:
9447 case ACTION_RUNLEVEL5
:
9449 r
= start_with_fallback();
9454 r
= reload_with_fallback();
9457 case ACTION_CANCEL_SHUTDOWN
:
9458 r
= logind_cancel_shutdown();
9461 case ACTION_RUNLEVEL
:
9462 r
= runlevel_main();
9466 case ACTION_SUSPEND
:
9467 case ACTION_HIBERNATE
:
9468 case ACTION_HYBRID_SLEEP
:
9469 case ACTION_SUSPEND_THEN_HIBERNATE
:
9470 case ACTION_EMERGENCY
:
9471 case ACTION_DEFAULT
:
9472 /* systemctl verbs with no equivalent in the legacy commands.
9473 * These cannot appear in arg_action. Fall through. */
9475 case _ACTION_INVALID
:
9477 assert_not_reached("Unknown action");
9483 /* Note that we return r here, not 0, so that we can implement the LSB-like return codes */
9487 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);