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 --plain 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
, NULL
, 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
++)
1668 static int list_dependencies_print(const char *name
, int level
, unsigned branches
, bool last
) {
1669 _cleanup_free_
char *n
= NULL
;
1670 size_t max_len
= MAX(columns(),20u);
1676 for (i
= level
- 1; i
>= 0; i
--) {
1678 if (len
> max_len
- 3 && !arg_full
) {
1679 printf("%s...\n",max_len
% 2 ? "" : " ");
1682 printf("%s", special_glyph(branches
& (1 << i
) ? SPECIAL_GLYPH_TREE_VERTICAL
: SPECIAL_GLYPH_TREE_SPACE
));
1686 if (len
> max_len
- 3 && !arg_full
) {
1687 printf("%s...\n",max_len
% 2 ? "" : " ");
1691 printf("%s", special_glyph(last
? SPECIAL_GLYPH_TREE_RIGHT
: SPECIAL_GLYPH_TREE_BRANCH
));
1695 printf("%s\n", name
);
1699 n
= ellipsize(name
, max_len
-len
, 100);
1707 static int list_dependencies_compare(char * const *a
, char * const *b
) {
1708 if (unit_name_to_type(*a
) == UNIT_TARGET
&& unit_name_to_type(*b
) != UNIT_TARGET
)
1710 if (unit_name_to_type(*a
) != UNIT_TARGET
&& unit_name_to_type(*b
) == UNIT_TARGET
)
1713 return strcasecmp(*a
, *b
);
1716 static int list_dependencies_one(
1721 unsigned branches
) {
1723 _cleanup_strv_free_
char **deps
= NULL
;
1731 r
= strv_extend(units
, name
);
1735 r
= list_dependencies_get_dependencies(bus
, name
, &deps
);
1739 typesafe_qsort(deps
, strv_length(deps
), list_dependencies_compare
);
1741 STRV_FOREACH(c
, deps
) {
1742 if (strv_contains(*units
, *c
)) {
1745 r
= list_dependencies_print("...", level
+ 1, (branches
<< 1) | (c
[1] == NULL
? 0 : 1), 1);
1755 UnitActiveState active_state
= _UNIT_ACTIVE_STATE_INVALID
;
1758 (void) get_state_one_unit(bus
, *c
, &active_state
);
1760 switch (active_state
) {
1762 case UNIT_RELOADING
:
1763 case UNIT_ACTIVATING
:
1764 on
= ansi_highlight_green();
1768 case UNIT_DEACTIVATING
:
1773 on
= ansi_highlight_red();
1777 printf("%s%s%s ", on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), ansi_normal());
1780 r
= list_dependencies_print(*c
, level
, branches
, c
[1] == NULL
);
1784 if (arg_all
|| unit_name_to_type(*c
) == UNIT_TARGET
) {
1785 r
= list_dependencies_one(bus
, *c
, level
+ 1, units
, (branches
<< 1) | (c
[1] == NULL
? 0 : 1));
1792 strv_remove(*units
, name
);
1797 static int list_dependencies(int argc
, char *argv
[], void *userdata
) {
1798 _cleanup_strv_free_
char **units
= NULL
, **done
= NULL
;
1799 char **u
, **patterns
;
1803 r
= acquire_bus(BUS_MANAGER
, &bus
);
1807 patterns
= strv_skip(argv
, 1);
1808 if (strv_isempty(patterns
)) {
1809 units
= strv_new(SPECIAL_DEFAULT_TARGET
);
1813 r
= expand_names(bus
, patterns
, NULL
, &units
, NULL
);
1815 return log_error_errno(r
, "Failed to expand names: %m");
1818 (void) pager_open(arg_pager_flags
);
1820 STRV_FOREACH(u
, units
) {
1825 r
= list_dependencies_one(bus
, *u
, 0, &done
, 0);
1833 struct machine_info
{
1837 char *control_group
;
1838 uint32_t n_failed_units
;
1843 static const struct bus_properties_map machine_info_property_map
[] = {
1844 { "SystemState", "s", NULL
, offsetof(struct machine_info
, state
) },
1845 { "NJobs", "u", NULL
, offsetof(struct machine_info
, n_jobs
) },
1846 { "NFailedUnits", "u", NULL
, offsetof(struct machine_info
, n_failed_units
) },
1847 { "ControlGroup", "s", NULL
, offsetof(struct machine_info
, control_group
) },
1848 { "UserspaceTimestamp", "t", NULL
, offsetof(struct machine_info
, timestamp
) },
1852 static void machine_info_clear(struct machine_info
*info
) {
1857 free(info
->control_group
);
1861 static void free_machines_list(struct machine_info
*machine_infos
, int n
) {
1867 for (i
= 0; i
< n
; i
++)
1868 machine_info_clear(&machine_infos
[i
]);
1870 free(machine_infos
);
1873 static int compare_machine_info(const struct machine_info
*a
, const struct machine_info
*b
) {
1876 r
= CMP(b
->is_host
, a
->is_host
);
1880 return strcasecmp(a
->name
, b
->name
);
1883 static int get_machine_properties(sd_bus
*bus
, struct machine_info
*mi
) {
1884 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*container
= NULL
;
1890 r
= sd_bus_open_system_machine(&container
, mi
->name
);
1897 r
= bus_map_all_properties(
1899 "org.freedesktop.systemd1",
1900 "/org/freedesktop/systemd1",
1901 machine_info_property_map
,
1912 static bool output_show_machine(const char *name
, char **patterns
) {
1913 return strv_fnmatch_or_empty(patterns
, name
, FNM_NOESCAPE
);
1916 static int get_machine_list(
1918 struct machine_info
**_machine_infos
,
1921 struct machine_info
*machine_infos
= NULL
;
1922 _cleanup_strv_free_
char **m
= NULL
;
1923 _cleanup_free_
char *hn
= NULL
;
1928 hn
= gethostname_malloc();
1932 if (output_show_machine(hn
, patterns
)) {
1933 if (!GREEDY_REALLOC0(machine_infos
, sz
, c
+1))
1936 machine_infos
[c
].is_host
= true;
1937 machine_infos
[c
].name
= TAKE_PTR(hn
);
1939 (void) get_machine_properties(bus
, &machine_infos
[c
]);
1943 r
= sd_get_machine_names(&m
);
1945 return log_error_errno(r
, "Failed to get machine list: %m");
1947 STRV_FOREACH(i
, m
) {
1948 _cleanup_free_
char *class = NULL
;
1950 if (!output_show_machine(*i
, patterns
))
1953 sd_machine_get_class(*i
, &class);
1954 if (!streq_ptr(class, "container"))
1957 if (!GREEDY_REALLOC0(machine_infos
, sz
, c
+1)) {
1958 free_machines_list(machine_infos
, c
);
1962 machine_infos
[c
].is_host
= false;
1963 machine_infos
[c
].name
= strdup(*i
);
1964 if (!machine_infos
[c
].name
) {
1965 free_machines_list(machine_infos
, c
);
1969 (void) get_machine_properties(NULL
, &machine_infos
[c
]);
1973 *_machine_infos
= machine_infos
;
1977 static int output_machines_list(struct machine_info
*machine_infos
, unsigned n
) {
1978 _cleanup_(table_unrefp
) Table
*table
= NULL
;
1979 struct machine_info
*m
;
1980 bool state_missing
= false;
1983 assert(machine_infos
|| n
== 0);
1985 table
= table_new("", "name", "state", "failed", "jobs");
1989 table_set_header(table
, !arg_no_legend
);
1991 /* Hide the 'glyph' column when --plain is requested */
1992 r
= table_hide_column_from_display(table
, 0);
1994 return log_error_errno(r
, "Failed to hide column: %m");
1997 table_set_width(table
, 0);
1999 for (m
= machine_infos
; m
< machine_infos
+ n
; m
++) {
2000 _cleanup_free_
char *mname
= NULL
;
2001 const char *on_state
= "", *on_failed
= "";
2002 bool circle
= false;
2004 if (streq_ptr(m
->state
, "degraded")) {
2005 on_state
= ansi_highlight_red();
2007 } else if (!streq_ptr(m
->state
, "running")) {
2008 on_state
= ansi_highlight_yellow();
2012 if (m
->n_failed_units
> 0)
2013 on_failed
= ansi_highlight_red();
2018 state_missing
= true;
2021 mname
= strjoin(strna(m
->name
), " (host)");
2023 r
= table_add_many(table
,
2024 TABLE_STRING
, circle
? special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
) : " ",
2025 TABLE_SET_COLOR
, on_state
,
2026 TABLE_STRING
, m
->is_host
? mname
: strna(m
->name
),
2027 TABLE_STRING
, strna(m
->state
),
2028 TABLE_SET_COLOR
, on_state
,
2029 TABLE_UINT32
, m
->n_failed_units
,
2030 TABLE_SET_COLOR
, on_failed
,
2031 TABLE_UINT32
, m
->n_jobs
);
2033 return table_log_add_error(r
);
2036 r
= table_print(table
, NULL
);
2038 return log_error_errno(r
, "Failed to print the table: %m");
2040 if (!arg_no_legend
) {
2042 if (state_missing
&& geteuid() != 0)
2043 printf("Notice: some information only available to privileged users was not shown.\n");
2044 printf("%u machines listed.\n", n
);
2050 static int list_machines(int argc
, char *argv
[], void *userdata
) {
2051 struct machine_info
*machine_infos
= NULL
;
2055 r
= acquire_bus(BUS_MANAGER
, &bus
);
2059 r
= get_machine_list(bus
, &machine_infos
, strv_skip(argv
, 1));
2063 (void) pager_open(arg_pager_flags
);
2065 typesafe_qsort(machine_infos
, r
, compare_machine_info
);
2066 rc
= output_machines_list(machine_infos
, r
);
2067 free_machines_list(machine_infos
, r
);
2072 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
2075 if (streq(key
, "systemd.unit")) {
2076 if (proc_cmdline_value_missing(key
, value
))
2078 if (!unit_name_is_valid(value
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
2079 return log_warning("Unit name specified on %s= is not valid, ignoring: %s", key
, value
);
2081 return free_and_strdup_warn(ret
, key
);
2083 } else if (!value
) {
2084 if (runlevel_to_target(key
))
2085 return free_and_strdup_warn(ret
, key
);
2091 static void emit_cmdline_warning(void) {
2092 if (arg_quiet
|| arg_root
)
2093 /* don't bother checking the commandline if we're operating on a container */
2096 _cleanup_free_
char *override
= NULL
;
2099 r
= proc_cmdline_parse(parse_proc_cmdline_item
, &override
, 0);
2101 log_debug_errno(r
, "Failed to parse kernel command line, ignoring: %m");
2103 log_notice("Note: found \"%s\" on the kernel commandline, which overrides the default unit.",
2107 static int determine_default(char **ret_name
) {
2110 if (install_client_side()) {
2111 r
= unit_file_get_default(arg_scope
, arg_root
, ret_name
);
2113 return log_error_errno(r
, "Failed to get default target: %m");
2118 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2119 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2122 r
= acquire_bus(BUS_MANAGER
, &bus
);
2126 r
= sd_bus_call_method(
2128 "org.freedesktop.systemd1",
2129 "/org/freedesktop/systemd1",
2130 "org.freedesktop.systemd1.Manager",
2136 return log_error_errno(r
, "Failed to get default target: %s", bus_error_message(&error
, r
));
2138 r
= sd_bus_message_read(reply
, "s", &name
);
2140 return bus_log_parse_error(r
);
2142 return free_and_strdup_warn(ret_name
, name
);
2146 static int get_default(int argc
, char *argv
[], void *userdata
) {
2147 _cleanup_free_
char *name
= NULL
;
2150 r
= determine_default(&name
);
2154 printf("%s\n", name
);
2156 emit_cmdline_warning();
2161 static int set_default(int argc
, char *argv
[], void *userdata
) {
2162 _cleanup_free_
char *unit
= NULL
;
2163 UnitFileChange
*changes
= NULL
;
2164 size_t n_changes
= 0;
2170 r
= unit_name_mangle_with_suffix(argv
[1], "set-default",
2171 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
2174 return log_error_errno(r
, "Failed to mangle unit name: %m");
2176 if (install_client_side()) {
2177 r
= unit_file_set_default(arg_scope
, UNIT_FILE_FORCE
, arg_root
, unit
, &changes
, &n_changes
);
2178 unit_file_dump_changes(r
, "set default", changes
, n_changes
, arg_quiet
);
2183 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2184 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2187 polkit_agent_open_maybe();
2189 r
= acquire_bus(BUS_MANAGER
, &bus
);
2193 r
= sd_bus_call_method(
2195 "org.freedesktop.systemd1",
2196 "/org/freedesktop/systemd1",
2197 "org.freedesktop.systemd1.Manager",
2203 return log_error_errno(r
, "Failed to set default target: %s", bus_error_message(&error
, r
));
2205 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
2209 /* Try to reload if enabled */
2211 r
= daemon_reload(argc
, argv
, userdata
);
2216 emit_cmdline_warning();
2219 _cleanup_free_
char *final
= NULL
;
2221 r
= determine_default(&final
);
2225 if (!streq(final
, unit
))
2226 log_notice("Note: \"%s\" is the default unit (possibly a runtime override).", final
);
2230 unit_file_changes_free(changes
, n_changes
);
2235 static int output_waiting_jobs(sd_bus
*bus
, Table
*table
, uint32_t id
, const char *method
, const char *prefix
) {
2236 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2237 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2238 const char *name
, *type
;
2244 r
= sd_bus_call_method(
2246 "org.freedesktop.systemd1",
2247 "/org/freedesktop/systemd1",
2248 "org.freedesktop.systemd1.Manager",
2254 return log_debug_errno(r
, "Failed to get waiting jobs for job %" PRIu32
, id
);
2256 r
= sd_bus_message_enter_container(reply
, 'a', "(usssoo)");
2258 return bus_log_parse_error(r
);
2260 while ((r
= sd_bus_message_read(reply
, "(usssoo)", &other_id
, &name
, &type
, NULL
, NULL
, NULL
)) > 0) {
2261 _cleanup_free_
char *row
= NULL
;
2264 if (asprintf(&row
, "%s %u (%s/%s)", prefix
, other_id
, name
, type
) < 0)
2267 rc
= table_add_many(table
,
2268 TABLE_STRING
, special_glyph(SPECIAL_GLYPH_TREE_RIGHT
),
2273 return table_log_add_error(r
);
2277 return bus_log_parse_error(r
);
2279 r
= sd_bus_message_exit_container(reply
);
2281 return bus_log_parse_error(r
);
2288 const char *name
, *type
, *state
;
2291 static int output_jobs_list(sd_bus
*bus
, const struct job_info
* jobs
, unsigned n
, bool skipped
) {
2292 _cleanup_(table_unrefp
) Table
*table
= NULL
;
2293 const struct job_info
*j
;
2294 const char *on
, *off
;
2297 assert(n
== 0 || jobs
);
2300 if (!arg_no_legend
) {
2301 on
= ansi_highlight_green();
2302 off
= ansi_normal();
2304 printf("%sNo jobs %s.%s\n", on
, skipped
? "listed" : "running", off
);
2309 (void) pager_open(arg_pager_flags
);
2311 table
= table_new("job", "unit", "type", "state");
2315 table_set_header(table
, !arg_no_legend
);
2317 table_set_width(table
, 0);
2319 for (j
= jobs
; j
< jobs
+ n
; j
++) {
2320 if (streq(j
->state
, "running"))
2321 on
= ansi_highlight();
2326 r
= table_add_many(table
,
2328 TABLE_STRING
, j
->name
,
2329 TABLE_SET_COLOR
, on
,
2330 TABLE_STRING
, j
->type
,
2331 TABLE_STRING
, j
->state
,
2332 TABLE_SET_COLOR
, on
);
2334 return table_log_add_error(r
);
2337 output_waiting_jobs(bus
, table
, j
->id
, "GetJobAfter", "\twaiting for job");
2338 if (arg_jobs_before
)
2339 output_waiting_jobs(bus
, table
, j
->id
, "GetJobBefore", "\tblocking job");
2342 r
= table_print(table
, NULL
);
2344 return log_error_errno(r
, "Failed to print the table: %m");
2346 if (!arg_no_legend
) {
2347 on
= ansi_highlight();
2348 off
= ansi_normal();
2350 printf("\n%s%u jobs listed%s.\n", on
, n
, off
);
2356 static bool output_show_job(struct job_info
*job
, char **patterns
) {
2357 return strv_fnmatch_or_empty(patterns
, job
->name
, FNM_NOESCAPE
);
2360 static int list_jobs(int argc
, char *argv
[], void *userdata
) {
2361 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2362 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2363 _cleanup_free_
struct job_info
*jobs
= NULL
;
2364 const char *name
, *type
, *state
;
2365 bool skipped
= false;
2372 r
= acquire_bus(BUS_MANAGER
, &bus
);
2376 r
= sd_bus_call_method(
2378 "org.freedesktop.systemd1",
2379 "/org/freedesktop/systemd1",
2380 "org.freedesktop.systemd1.Manager",
2386 return log_error_errno(r
, "Failed to list jobs: %s", bus_error_message(&error
, r
));
2388 r
= sd_bus_message_enter_container(reply
, 'a', "(usssoo)");
2390 return bus_log_parse_error(r
);
2392 while ((r
= sd_bus_message_read(reply
, "(usssoo)", &id
, &name
, &type
, &state
, NULL
, NULL
)) > 0) {
2393 struct job_info job
= { id
, name
, type
, state
};
2395 if (!output_show_job(&job
, strv_skip(argv
, 1))) {
2400 if (!GREEDY_REALLOC(jobs
, size
, c
+ 1))
2406 return bus_log_parse_error(r
);
2408 r
= sd_bus_message_exit_container(reply
);
2410 return bus_log_parse_error(r
);
2412 (void) pager_open(arg_pager_flags
);
2414 return output_jobs_list(bus
, jobs
, c
, skipped
);
2417 static int cancel_job(int argc
, char *argv
[], void *userdata
) {
2423 return trivial_method(argc
, argv
, userdata
);
2425 r
= acquire_bus(BUS_MANAGER
, &bus
);
2429 polkit_agent_open_maybe();
2431 STRV_FOREACH(name
, strv_skip(argv
, 1)) {
2432 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2436 q
= safe_atou32(*name
, &id
);
2438 return log_error_errno(q
, "Failed to parse job id \"%s\": %m", *name
);
2440 q
= sd_bus_call_method(
2442 "org.freedesktop.systemd1",
2443 "/org/freedesktop/systemd1",
2444 "org.freedesktop.systemd1.Manager",
2450 log_error_errno(q
, "Failed to cancel job %"PRIu32
": %s", id
, bus_error_message(&error
, q
));
2459 static int need_daemon_reload(sd_bus
*bus
, const char *unit
) {
2460 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2464 /* We ignore all errors here, since this is used to show a
2467 /* We don't use unit_dbus_path_from_name() directly since we
2468 * don't want to load the unit if it isn't loaded. */
2470 r
= sd_bus_call_method(
2472 "org.freedesktop.systemd1",
2473 "/org/freedesktop/systemd1",
2474 "org.freedesktop.systemd1.Manager",
2482 r
= sd_bus_message_read(reply
, "o", &path
);
2486 r
= sd_bus_get_property_trivial(
2488 "org.freedesktop.systemd1",
2490 "org.freedesktop.systemd1.Unit",
2500 static void warn_unit_file_changed(const char *name
) {
2503 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.",
2504 ansi_highlight_red(),
2507 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user");
2510 static int unit_file_find_path(LookupPaths
*lp
, const char *unit_name
, char **ret_unit_path
) {
2516 STRV_FOREACH(p
, lp
->search_path
) {
2517 _cleanup_free_
char *path
= NULL
, *lpath
= NULL
;
2520 path
= path_join(*p
, unit_name
);
2524 r
= chase_symlinks(path
, arg_root
, 0, &lpath
, NULL
);
2530 return log_error_errno(r
, "Failed to access path \"%s\": %m", path
);
2533 *ret_unit_path
= TAKE_PTR(lpath
);
2539 *ret_unit_path
= NULL
;
2544 static int unit_find_template_path(
2545 const char *unit_name
,
2547 char **ret_fragment_path
,
2548 char **ret_template
) {
2550 _cleanup_free_
char *t
= NULL
, *f
= NULL
;
2553 /* Returns 1 if a fragment was found, 0 if not found, negative on error. */
2555 r
= unit_file_find_path(lp
, unit_name
, &f
);
2559 if (ret_fragment_path
)
2560 *ret_fragment_path
= TAKE_PTR(f
);
2562 *ret_template
= NULL
;
2563 return r
; /* found a real unit */
2566 r
= unit_name_template(unit_name
, &t
);
2568 if (ret_fragment_path
)
2569 *ret_fragment_path
= NULL
;
2571 *ret_template
= NULL
;
2573 return 0; /* not a template, does not exist */
2576 return log_error_errno(r
, "Failed to determine template name: %m");
2578 r
= unit_file_find_path(lp
, t
, ret_fragment_path
);
2583 *ret_template
= r
> 0 ? TAKE_PTR(t
) : NULL
;
2588 static int unit_find_paths(
2590 const char *unit_name
,
2592 bool force_client_side
,
2593 char **ret_fragment_path
,
2594 char ***ret_dropin_paths
) {
2596 _cleanup_strv_free_
char **dropins
= NULL
;
2597 _cleanup_free_
char *path
= NULL
;
2601 * Finds where the unit is defined on disk. Returns 0 if the unit is not found. Returns 1 if it is
2603 * - the path to the unit in *ret_frament_path, if it exists on disk,
2604 * - and a strv of existing drop-ins in *ret_dropin_paths, if the arg is not NULL and any dropins
2607 * Returns -ERFKILL if the unit is masked, and -EKEYREJECTED if the unit file could not be loaded for
2608 * some reason (the latter only applies if we are going through the service manager).
2612 assert(ret_fragment_path
);
2615 /* Go via the bus to acquire the path, unless we are explicitly told not to, or when the unit name is a template */
2616 if (!force_client_side
&&
2617 !install_client_side() &&
2618 !unit_name_is_valid(unit_name
, UNIT_NAME_TEMPLATE
)) {
2619 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2620 _cleanup_free_
char *load_state
= NULL
, *dbus_path
= NULL
;
2622 dbus_path
= unit_dbus_path_from_name(unit_name
);
2626 r
= sd_bus_get_property_string(
2628 "org.freedesktop.systemd1",
2630 "org.freedesktop.systemd1.Unit",
2635 return log_error_errno(r
, "Failed to get LoadState: %s", bus_error_message(&error
, r
));
2637 if (streq(load_state
, "masked"))
2639 if (streq(load_state
, "not-found")) {
2643 if (!STR_IN_SET(load_state
, "loaded", "bad-setting"))
2644 return -EKEYREJECTED
;
2646 r
= sd_bus_get_property_string(
2648 "org.freedesktop.systemd1",
2650 "org.freedesktop.systemd1.Unit",
2655 return log_error_errno(r
, "Failed to get FragmentPath: %s", bus_error_message(&error
, r
));
2657 if (ret_dropin_paths
) {
2658 r
= sd_bus_get_property_strv(
2660 "org.freedesktop.systemd1",
2662 "org.freedesktop.systemd1.Unit",
2667 return log_error_errno(r
, "Failed to get DropInPaths: %s", bus_error_message(&error
, r
));
2671 _cleanup_set_free_free_ Set
*names
= NULL
;
2673 if (!cached_name_map
) {
2674 r
= unit_file_build_name_map(lp
, NULL
, &cached_id_map
, &cached_name_map
, NULL
);
2679 r
= unit_file_find_fragment(cached_id_map
, cached_name_map
, unit_name
, &_path
, &names
);
2684 path
= strdup(_path
);
2689 if (ret_dropin_paths
) {
2690 r
= unit_file_find_dropin_paths(arg_root
, lp
->search_path
, NULL
,
2698 if (isempty(path
)) {
2699 *ret_fragment_path
= NULL
;
2702 *ret_fragment_path
= TAKE_PTR(path
);
2706 if (ret_dropin_paths
) {
2707 if (!strv_isempty(dropins
)) {
2708 *ret_dropin_paths
= TAKE_PTR(dropins
);
2711 *ret_dropin_paths
= NULL
;
2715 if (r
== 0 && !arg_force
)
2716 log_error("No files found for %s.", unit_name
);
2721 static int get_state_one_unit(sd_bus
*bus
, const char *name
, UnitActiveState
*active_state
) {
2722 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2723 _cleanup_free_
char *buf
= NULL
, *dbus_path
= NULL
;
2724 UnitActiveState state
;
2728 assert(active_state
);
2730 dbus_path
= unit_dbus_path_from_name(name
);
2734 r
= sd_bus_get_property_string(
2736 "org.freedesktop.systemd1",
2738 "org.freedesktop.systemd1.Unit",
2743 return log_error_errno(r
, "Failed to retrieve unit state: %s", bus_error_message(&error
, r
));
2745 state
= unit_active_state_from_string(buf
);
2747 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid unit state '%s' for: %s", buf
, name
);
2749 *active_state
= state
;
2753 static int unit_is_masked(sd_bus
*bus
, LookupPaths
*lp
, const char *name
) {
2754 _cleanup_free_
char *load_state
= NULL
;
2757 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
2758 _cleanup_free_
char *path
= NULL
;
2760 /* A template cannot be loaded, but it can be still masked, so
2761 * we need to use a different method. */
2763 r
= unit_file_find_path(lp
, name
, &path
);
2768 return null_or_empty_path(path
);
2771 r
= unit_load_state(bus
, name
, &load_state
);
2775 return streq(load_state
, "masked");
2778 static int check_triggering_units(sd_bus
*bus
, const char *name
) {
2779 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2780 _cleanup_free_
char *n
= NULL
, *dbus_path
= NULL
, *load_state
= NULL
;
2781 _cleanup_strv_free_
char **triggered_by
= NULL
;
2782 bool print_warning_label
= true;
2783 UnitActiveState active_state
;
2787 r
= unit_name_mangle(name
, 0, &n
);
2789 return log_error_errno(r
, "Failed to mangle unit name: %m");
2791 r
= unit_load_state(bus
, name
, &load_state
);
2795 if (streq(load_state
, "masked"))
2798 dbus_path
= unit_dbus_path_from_name(n
);
2802 r
= sd_bus_get_property_strv(
2804 "org.freedesktop.systemd1",
2806 "org.freedesktop.systemd1.Unit",
2811 return log_error_errno(r
, "Failed to get triggered by array of %s: %s", n
, bus_error_message(&error
, r
));
2813 STRV_FOREACH(i
, triggered_by
) {
2814 r
= get_state_one_unit(bus
, *i
, &active_state
);
2818 if (!IN_SET(active_state
, UNIT_ACTIVE
, UNIT_RELOADING
))
2821 if (print_warning_label
) {
2822 log_warning("Warning: Stopping %s, but it can still be activated by:", n
);
2823 print_warning_label
= false;
2826 log_warning(" %s", *i
);
2832 static const struct {
2833 const char *verb
; /* systemctl verb */
2834 const char *method
; /* Name of the specific D-Bus method */
2835 const char *job_type
; /* Job type when passing to the generic EnqueueUnitJob() method */
2836 } unit_actions
[] = {
2837 { "start", "StartUnit", "start" },
2838 { "stop", "StopUnit", "stop" },
2839 { "condstop", "StopUnit", "stop" }, /* legacy alias */
2840 { "reload", "ReloadUnit", "reload" },
2841 { "restart", "RestartUnit", "restart" },
2842 { "try-restart", "TryRestartUnit", "try-restart" },
2843 { "condrestart", "TryRestartUnit", "try-restart" }, /* legacy alias */
2844 { "reload-or-restart", "ReloadOrRestartUnit", "reload-or-restart" },
2845 { "try-reload-or-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" },
2846 { "reload-or-try-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2847 { "condreload", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2848 { "force-reload", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2851 static const char *verb_to_method(const char *verb
) {
2854 for (i
= 0; i
< ELEMENTSOF(unit_actions
); i
++)
2855 if (streq_ptr(unit_actions
[i
].verb
, verb
))
2856 return unit_actions
[i
].method
;
2861 static const char *verb_to_job_type(const char *verb
) {
2864 for (i
= 0; i
< ELEMENTSOF(unit_actions
); i
++)
2865 if (streq_ptr(unit_actions
[i
].verb
, verb
))
2866 return unit_actions
[i
].job_type
;
2871 static int start_unit_one(
2873 const char *method
, /* When using classic per-job bus methods */
2874 const char *job_type
, /* When using new-style EnqueueUnitJob() */
2877 sd_bus_error
*error
,
2879 BusWaitForUnits
*wu
) {
2881 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2891 log_debug("%s dbus call org.freedesktop.systemd1.Manager %s(%s, %s)",
2892 arg_dry_run
? "Would execute" : "Executing",
2893 method
, name
, mode
);
2898 if (arg_show_transaction
) {
2899 _cleanup_(sd_bus_error_free
) sd_bus_error enqueue_error
= SD_BUS_ERROR_NULL
;
2901 /* Use the new, fancy EnqueueUnitJob() API if the user wants us to print the transaction */
2902 r
= sd_bus_call_method(
2904 "org.freedesktop.systemd1",
2905 "/org/freedesktop/systemd1",
2906 "org.freedesktop.systemd1.Manager",
2911 name
, job_type
, mode
);
2913 if (!sd_bus_error_has_name(&enqueue_error
, SD_BUS_ERROR_UNKNOWN_METHOD
)) {
2914 (void) sd_bus_error_move(error
, &enqueue_error
);
2918 /* Hmm, the API is not yet available. Let's use the classic API instead (see below). */
2919 log_notice("--show-transaction not supported by this service manager, proceeding without.");
2924 r
= sd_bus_message_read(reply
, "uosos", &id
, &path
, &u
, NULL
, &jt
);
2926 return bus_log_parse_error(r
);
2928 log_info("Enqueued anchor job %" PRIu32
" %s/%s.", id
, u
, jt
);
2930 r
= sd_bus_message_enter_container(reply
, 'a', "(uosos)");
2932 return bus_log_parse_error(r
);
2934 r
= sd_bus_message_read(reply
, "(uosos)", &id
, NULL
, &u
, NULL
, &jt
);
2936 return bus_log_parse_error(r
);
2940 log_info("Enqueued auxiliary job %" PRIu32
" %s/%s.", id
, u
, jt
);
2943 r
= sd_bus_message_exit_container(reply
);
2945 return bus_log_parse_error(r
);
2952 r
= sd_bus_call_method(
2954 "org.freedesktop.systemd1",
2955 "/org/freedesktop/systemd1",
2956 "org.freedesktop.systemd1.Manager",
2964 r
= sd_bus_message_read(reply
, "o", &path
);
2966 return bus_log_parse_error(r
);
2969 if (need_daemon_reload(bus
, name
) > 0)
2970 warn_unit_file_changed(name
);
2973 log_debug("Adding %s to the set", path
);
2974 r
= bus_wait_for_jobs_add(w
, path
);
2976 return log_error_errno(r
, "Failed to watch job for %s: %m", name
);
2980 r
= bus_wait_for_units_add_unit(wu
, name
, BUS_WAIT_FOR_INACTIVE
|BUS_WAIT_NO_JOB
, NULL
, NULL
);
2982 return log_error_errno(r
, "Failed to watch unit %s: %m", name
);
2988 /* There's always a fallback possible for legacy actions. */
2989 if (arg_action
!= ACTION_SYSTEMCTL
)
2992 log_error_errno(r
, "Failed to %s %s: %s", job_type
, name
, bus_error_message(error
, r
));
2994 if (!sd_bus_error_has_name(error
, BUS_ERROR_NO_SUCH_UNIT
) &&
2995 !sd_bus_error_has_name(error
, BUS_ERROR_UNIT_MASKED
) &&
2996 !sd_bus_error_has_name(error
, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE
))
2997 log_error("See %s logs and 'systemctl%s status%s %s' for details.",
2998 arg_scope
== UNIT_FILE_SYSTEM
? "system" : "user",
2999 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user",
3000 name
[0] == '-' ? " --" : "",
3006 static const struct {
3010 } action_table
[_ACTION_MAX
] = {
3011 [ACTION_HALT
] = { SPECIAL_HALT_TARGET
, "halt", "replace-irreversibly" },
3012 [ACTION_POWEROFF
] = { SPECIAL_POWEROFF_TARGET
, "poweroff", "replace-irreversibly" },
3013 [ACTION_REBOOT
] = { SPECIAL_REBOOT_TARGET
, "reboot", "replace-irreversibly" },
3014 [ACTION_KEXEC
] = { SPECIAL_KEXEC_TARGET
, "kexec", "replace-irreversibly" },
3015 [ACTION_RUNLEVEL2
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
3016 [ACTION_RUNLEVEL3
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
3017 [ACTION_RUNLEVEL4
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
3018 [ACTION_RUNLEVEL5
] = { SPECIAL_GRAPHICAL_TARGET
, NULL
, "isolate" },
3019 [ACTION_RESCUE
] = { SPECIAL_RESCUE_TARGET
, "rescue", "isolate" },
3020 [ACTION_EMERGENCY
] = { SPECIAL_EMERGENCY_TARGET
, "emergency", "isolate" },
3021 [ACTION_DEFAULT
] = { SPECIAL_DEFAULT_TARGET
, "default", "isolate" },
3022 [ACTION_EXIT
] = { SPECIAL_EXIT_TARGET
, "exit", "replace-irreversibly" },
3023 [ACTION_SUSPEND
] = { SPECIAL_SUSPEND_TARGET
, "suspend", "replace-irreversibly" },
3024 [ACTION_HIBERNATE
] = { SPECIAL_HIBERNATE_TARGET
, "hibernate", "replace-irreversibly" },
3025 [ACTION_HYBRID_SLEEP
] = { SPECIAL_HYBRID_SLEEP_TARGET
, "hybrid-sleep", "replace-irreversibly" },
3026 [ACTION_SUSPEND_THEN_HIBERNATE
] = { SPECIAL_SUSPEND_THEN_HIBERNATE_TARGET
, "suspend-then-hibernate", "replace-irreversibly" },
3029 static enum action
verb_to_action(const char *verb
) {
3032 for (i
= 0; i
< _ACTION_MAX
; i
++)
3033 if (streq_ptr(action_table
[i
].verb
, verb
))
3036 return _ACTION_INVALID
;
3039 static const char** make_extra_args(const char *extra_args
[static 4]) {
3044 if (arg_scope
!= UNIT_FILE_SYSTEM
)
3045 extra_args
[n
++] = "--user";
3047 if (arg_transport
== BUS_TRANSPORT_REMOTE
) {
3048 extra_args
[n
++] = "-H";
3049 extra_args
[n
++] = arg_host
;
3050 } else if (arg_transport
== BUS_TRANSPORT_MACHINE
) {
3051 extra_args
[n
++] = "-M";
3052 extra_args
[n
++] = arg_host
;
3054 assert(arg_transport
== BUS_TRANSPORT_LOCAL
);
3056 extra_args
[n
] = NULL
;
3060 static int start_unit(int argc
, char *argv
[], void *userdata
) {
3061 _cleanup_(bus_wait_for_units_freep
) BusWaitForUnits
*wu
= NULL
;
3062 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
3063 const char *method
, *job_type
, *mode
, *one_name
, *suffix
= NULL
;
3064 _cleanup_free_
char **stopped_units
= NULL
; /* Do not use _cleanup_strv_free_ */
3065 _cleanup_strv_free_
char **names
= NULL
;
3066 int r
, ret
= EXIT_SUCCESS
;
3070 if (arg_wait
&& !STR_IN_SET(argv
[0], "start", "restart"))
3071 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3072 "--wait may only be used with the 'start' or 'restart' commands.");
3074 /* we cannot do sender tracking on the private bus, so we need the full
3075 * one for RefUnit to implement --wait */
3076 r
= acquire_bus(arg_wait
? BUS_FULL
: BUS_MANAGER
, &bus
);
3080 ask_password_agent_open_maybe();
3081 polkit_agent_open_maybe();
3083 if (arg_action
== ACTION_SYSTEMCTL
) {
3086 action
= verb_to_action(argv
[0]);
3088 if (action
!= _ACTION_INVALID
) {
3089 /* A command in style "systemctl reboot", "systemctl poweroff", … */
3090 method
= "StartUnit";
3092 mode
= action_table
[action
].mode
;
3093 one_name
= action_table
[action
].target
;
3095 if (streq(argv
[0], "isolate")) {
3096 /* A "systemctl isolate <unit1> <unit2> …" command */
3097 method
= "StartUnit";
3102 /* A command in style of "systemctl start <unit1> <unit2> …", "sysemctl stop <unit1> <unit2> …" and so on */
3103 method
= verb_to_method(argv
[0]);
3104 job_type
= verb_to_job_type(argv
[0]);
3105 mode
= arg_job_mode
;
3110 /* A SysV legacy command such as "halt", "reboot", "poweroff", … */
3111 assert(arg_action
>= 0 && arg_action
< _ACTION_MAX
);
3112 assert(action_table
[arg_action
].target
);
3113 assert(action_table
[arg_action
].mode
);
3115 method
= "StartUnit";
3117 mode
= action_table
[arg_action
].mode
;
3118 one_name
= action_table
[arg_action
].target
;
3122 names
= strv_new(one_name
);
3128 r
= expand_names(bus
, strv_skip(argv
, 1), suffix
, &names
, &expanded
);
3130 return log_error_errno(r
, "Failed to expand names: %m");
3132 if (!arg_all
&& expanded
&& streq(job_type
, "start") && !arg_quiet
) {
3133 log_warning("Warning: %ssystemctl start called with a glob pattern.%s",
3134 ansi_highlight_red(),
3136 log_notice("Hint: unit globs expand to loaded units, so start will usually have no effect.\n"
3137 " Passing --all will also load units which are pulled in by other units.\n"
3138 " See systemctl(1) for more details.");
3142 if (!arg_no_block
) {
3143 r
= bus_wait_for_jobs_new(bus
, &w
);
3145 return log_error_errno(r
, "Could not watch jobs: %m");
3149 r
= sd_bus_call_method_async(
3152 "org.freedesktop.systemd1",
3153 "/org/freedesktop/systemd1",
3154 "org.freedesktop.systemd1.Manager",
3159 return log_error_errno(r
, "Failed to enable subscription: %m");
3161 r
= bus_wait_for_units_new(bus
, &wu
);
3163 return log_error_errno(r
, "Failed to allocate unit watch context: %m");
3166 STRV_FOREACH(name
, names
) {
3167 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3169 r
= start_unit_one(bus
, method
, job_type
, *name
, mode
, &error
, w
, wu
);
3170 if (ret
== EXIT_SUCCESS
&& r
< 0)
3171 ret
= translate_bus_error_to_exit_status(r
, &error
);
3173 if (r
>= 0 && streq(method
, "StopUnit")) {
3174 r
= strv_push(&stopped_units
, *name
);
3180 if (!arg_no_block
) {
3181 const char* extra_args
[4];
3183 r
= bus_wait_for_jobs(w
, arg_quiet
, make_extra_args(extra_args
));
3187 /* When stopping units, warn if they can still be triggered by
3188 * another active unit (socket, path, timer) */
3190 STRV_FOREACH(name
, stopped_units
)
3191 (void) check_triggering_units(bus
, *name
);
3195 r
= bus_wait_for_units_run(wu
);
3197 return log_error_errno(r
, "Failed to wait for units: %m");
3198 if (r
== BUS_WAIT_FAILURE
&& ret
== EXIT_SUCCESS
)
3206 static int logind_set_wall_message(void) {
3207 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3209 _cleanup_free_
char *m
= NULL
;
3212 r
= acquire_bus(BUS_FULL
, &bus
);
3216 m
= strv_join(arg_wall
, " ");
3220 log_debug("%s wall message \"%s\".", arg_dry_run
? "Would set" : "Setting", m
);
3224 r
= sd_bus_call_method(
3226 "org.freedesktop.login1",
3227 "/org/freedesktop/login1",
3228 "org.freedesktop.login1.Manager",
3237 return log_warning_errno(r
, "Failed to set wall message, ignoring: %s", bus_error_message(&error
, r
));
3242 /* Ask systemd-logind, which might grant access to unprivileged users through polkit */
3243 static int logind_reboot(enum action a
) {
3245 static const struct {
3247 const char *description
;
3248 } actions
[_ACTION_MAX
] = {
3249 [ACTION_POWEROFF
] = { "PowerOff", "power off system" },
3250 [ACTION_REBOOT
] = { "Reboot", "reboot system" },
3251 [ACTION_HALT
] = { "Halt", "halt system" },
3252 [ACTION_SUSPEND
] = { "Suspend", "suspend system" },
3253 [ACTION_HIBERNATE
] = { "Hibernate", "hibernate system" },
3254 [ACTION_HYBRID_SLEEP
] = { "HybridSleep", "put system into hybrid sleep" },
3255 [ACTION_SUSPEND_THEN_HIBERNATE
] = { "SuspendThenHibernate", "suspend system, hibernate later" },
3258 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3262 if (a
< 0 || a
>= _ACTION_MAX
|| !actions
[a
].method
)
3265 r
= acquire_bus(BUS_FULL
, &bus
);
3269 polkit_agent_open_maybe();
3270 (void) logind_set_wall_message();
3272 log_debug("%s org.freedesktop.login1.Manager %s dbus call.", arg_dry_run
? "Would execute" : "Executing", actions
[a
].method
);
3277 r
= sd_bus_call_method(
3279 "org.freedesktop.login1",
3280 "/org/freedesktop/login1",
3281 "org.freedesktop.login1.Manager",
3285 "b", arg_ask_password
);
3287 return log_error_errno(r
, "Failed to %s via logind: %s", actions
[a
].description
, bus_error_message(&error
, r
));
3295 static int logind_check_inhibitors(enum action a
) {
3297 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
3298 _cleanup_strv_free_
char **sessions
= NULL
;
3299 const char *what
, *who
, *why
, *mode
;
3306 if (arg_ignore_inhibitors
|| arg_force
> 0)
3318 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
3321 r
= acquire_bus(BUS_FULL
, &bus
);
3325 r
= sd_bus_call_method(
3327 "org.freedesktop.login1",
3328 "/org/freedesktop/login1",
3329 "org.freedesktop.login1.Manager",
3335 /* If logind is not around, then there are no inhibitors... */
3338 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssuu)");
3340 return bus_log_parse_error(r
);
3342 while ((r
= sd_bus_message_read(reply
, "(ssssuu)", &what
, &who
, &why
, &mode
, &uid
, &pid
)) > 0) {
3343 _cleanup_free_
char *comm
= NULL
, *user
= NULL
;
3344 _cleanup_strv_free_
char **sv
= NULL
;
3346 if (!streq(mode
, "block"))
3349 sv
= strv_split(what
, ":");
3353 if (!pid_is_valid((pid_t
) pid
))
3354 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Invalid PID "PID_FMT
".", (pid_t
) pid
);
3356 if (!strv_contains(sv
,
3361 ACTION_KEXEC
) ? "shutdown" : "sleep"))
3364 get_process_comm(pid
, &comm
);
3365 user
= uid_to_name(uid
);
3367 log_warning("Operation inhibited by \"%s\" (PID "PID_FMT
" \"%s\", user %s), reason is \"%s\".",
3368 who
, (pid_t
) pid
, strna(comm
), strna(user
), why
);
3373 return bus_log_parse_error(r
);
3375 r
= sd_bus_message_exit_container(reply
);
3377 return bus_log_parse_error(r
);
3379 /* Check for current sessions */
3380 sd_get_sessions(&sessions
);
3381 STRV_FOREACH(s
, sessions
) {
3382 _cleanup_free_
char *type
= NULL
, *tty
= NULL
, *seat
= NULL
, *user
= NULL
, *service
= NULL
, *class = NULL
;
3384 if (sd_session_get_uid(*s
, &uid
) < 0 || uid
== getuid())
3387 if (sd_session_get_class(*s
, &class) < 0 || !streq(class, "user"))
3390 if (sd_session_get_type(*s
, &type
) < 0 || !STR_IN_SET(type
, "x11", "wayland", "tty", "mir"))
3393 sd_session_get_tty(*s
, &tty
);
3394 sd_session_get_seat(*s
, &seat
);
3395 sd_session_get_service(*s
, &service
);
3396 user
= uid_to_name(uid
);
3398 log_warning("User %s is logged in on %s.", strna(user
), isempty(tty
) ? (isempty(seat
) ? strna(service
) : seat
) : tty
);
3405 log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'systemctl %s -i'.",
3406 action_table
[a
].verb
);
3414 static int prepare_firmware_setup(void) {
3416 if (!arg_firmware_setup
)
3420 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3424 r
= acquire_bus(BUS_FULL
, &bus
);
3428 r
= sd_bus_call_method(
3430 "org.freedesktop.login1",
3431 "/org/freedesktop/login1",
3432 "org.freedesktop.login1.Manager",
3433 "SetRebootToFirmwareSetup",
3438 return log_error_errno(r
, "Cannot indicate to EFI to boot into setup mode: %s", bus_error_message(&error
, r
));
3442 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3443 "Booting into firmware setup not supported.");
3447 static int prepare_boot_loader_menu(void) {
3449 if (arg_boot_loader_menu
== USEC_INFINITY
)
3453 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3457 r
= acquire_bus(BUS_FULL
, &bus
);
3461 r
= sd_bus_call_method(
3463 "org.freedesktop.login1",
3464 "/org/freedesktop/login1",
3465 "org.freedesktop.login1.Manager",
3466 "SetRebootToBootLoaderMenu",
3469 "t", arg_boot_loader_menu
);
3471 return log_error_errno(r
, "Cannot indicate to boot loader to enter boot loader entry menu: %s", bus_error_message(&error
, r
));
3475 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3476 "Booting into boot loader menu not supported.");
3480 static int prepare_boot_loader_entry(void) {
3482 if (!arg_boot_loader_entry
)
3486 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3490 r
= acquire_bus(BUS_FULL
, &bus
);
3494 r
= sd_bus_call_method(
3496 "org.freedesktop.login1",
3497 "/org/freedesktop/login1",
3498 "org.freedesktop.login1.Manager",
3499 "SetRebootToBootLoaderEntry",
3502 "s", arg_boot_loader_entry
);
3504 return log_error_errno(r
, "Cannot set boot into loader entry '%s': %s", arg_boot_loader_entry
, bus_error_message(&error
, r
));
3508 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3509 "Booting into boot loader entry not supported.");
3513 static int load_kexec_kernel(void) {
3514 _cleanup_(boot_config_free
) BootConfig config
= {};
3515 _cleanup_free_
char *kernel
= NULL
, *initrd
= NULL
, *options
= NULL
;
3520 if (kexec_loaded()) {
3521 log_debug("Kexec kernel already loaded.");
3525 if (access(KEXEC
, X_OK
) < 0)
3526 return log_error_errno(errno
, KEXEC
" is not available: %m");
3528 r
= boot_entries_load_config_auto(NULL
, NULL
, &config
);
3530 /* The call doesn't log about ENOKEY, let's do so here. */
3531 return log_error_errno(r
,
3532 "No kexec kernel loaded and autodetection failed.\n%s",
3534 ? "Cannot automatically load kernel: ESP partition mount point not found."
3535 : "Automatic loading works only on systems booted with EFI.");
3539 e
= boot_config_default_entry(&config
);
3541 return log_error_errno(SYNTHETIC_ERRNO(ENOENT
),
3542 "No boot loader entry suitable as default, refusing to guess.");
3544 log_debug("Found default boot loader entry in file \"%s\"", e
->path
);
3547 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3548 "Boot entry does not refer to Linux kernel, which is not supported currently.");
3549 if (strv_length(e
->initrd
) > 1)
3550 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3551 "Boot entry specifies multiple initrds, which is not supported currently.");
3553 kernel
= path_join(e
->root
, e
->kernel
);
3557 if (!strv_isempty(e
->initrd
)) {
3558 initrd
= path_join(e
->root
, e
->initrd
[0]);
3563 options
= strv_join(e
->options
, " ");
3567 log_full(arg_quiet
? LOG_DEBUG
: LOG_INFO
,
3568 "%s "KEXEC
" --load \"%s\" --append \"%s\"%s%s%s",
3569 arg_dry_run
? "Would run" : "Running",
3572 initrd
? " --initrd \"" : NULL
, strempty(initrd
), initrd
? "\"" : "");
3576 r
= safe_fork("(kexec)", FORK_WAIT
|FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
, &pid
);
3580 const char* const args
[] = {
3583 "--append", options
,
3584 initrd
? "--initrd" : NULL
, initrd
,
3589 execv(args
[0], (char * const *) args
);
3590 _exit(EXIT_FAILURE
);
3596 static int set_exit_code(uint8_t code
) {
3597 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3601 r
= acquire_bus(BUS_MANAGER
, &bus
);
3605 r
= sd_bus_call_method(
3607 "org.freedesktop.systemd1",
3608 "/org/freedesktop/systemd1",
3609 "org.freedesktop.systemd1.Manager",
3615 return log_error_errno(r
, "Failed to set exit code: %s", bus_error_message(&error
, r
));
3620 static int start_special(int argc
, char *argv
[], void *userdata
) {
3623 bool termination_action
; /* an action that terminates the manager,
3624 * can be performed also by signal. */
3628 a
= verb_to_action(argv
[0]);
3630 r
= logind_check_inhibitors(a
);
3634 if (arg_force
>= 2) {
3640 r
= prepare_firmware_setup();
3644 r
= prepare_boot_loader_menu();
3648 r
= prepare_boot_loader_entry();
3652 if (a
== ACTION_REBOOT
&& argc
> 1) {
3653 r
= update_reboot_parameter_and_warn(argv
[1], false);
3657 } else if (a
== ACTION_KEXEC
) {
3658 r
= load_kexec_kernel();
3659 if (r
< 0 && arg_force
>= 1)
3660 log_notice("Failed to load kexec kernel, continuing without.");
3664 } else if (a
== ACTION_EXIT
&& argc
> 1) {
3667 /* If the exit code is not given on the command line,
3668 * don't reset it to zero: just keep it as it might
3669 * have been set previously. */
3671 r
= safe_atou8(argv
[1], &code
);
3673 return log_error_errno(r
, "Invalid exit code.");
3675 r
= set_exit_code(code
);
3680 termination_action
= IN_SET(a
,
3684 if (termination_action
&& arg_force
>= 2)
3687 if (arg_force
>= 1 &&
3688 (termination_action
|| IN_SET(a
, ACTION_KEXEC
, ACTION_EXIT
)))
3689 r
= trivial_method(argc
, argv
, userdata
);
3691 /* First try logind, to allow authentication with polkit */
3698 ACTION_HYBRID_SLEEP
,
3699 ACTION_SUSPEND_THEN_HIBERNATE
)) {
3701 r
= logind_reboot(a
);
3704 if (IN_SET(r
, -EOPNOTSUPP
, -EINPROGRESS
))
3705 /* requested operation is not supported or already in progress */
3708 /* On all other errors, try low-level operation. In order to minimize the difference between
3709 * operation with and without logind, we explicitly enable non-blocking mode for this, as
3710 * logind's shutdown operations are always non-blocking. */
3712 arg_no_block
= true;
3714 } else if (IN_SET(a
, ACTION_EXIT
, ACTION_KEXEC
))
3715 /* Since exit/kexec are so close in behaviour to power-off/reboot, let's also make them
3716 * asynchronous, in order to not confuse the user needlessly with unexpected behaviour. */
3717 arg_no_block
= true;
3719 r
= start_unit(argc
, argv
, userdata
);
3722 if (termination_action
&& arg_force
< 2 &&
3723 IN_SET(r
, -ENOENT
, -ETIMEDOUT
))
3724 log_notice("It is possible to perform action directly, see discussion of --force --force in man:systemctl(1).");
3729 static int start_system_special(int argc
, char *argv
[], void *userdata
) {
3730 /* Like start_special above, but raises an error when running in user mode */
3732 if (arg_scope
!= UNIT_FILE_SYSTEM
)
3733 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3734 "Bad action for %s mode.",
3735 arg_scope
== UNIT_FILE_GLOBAL
? "--global" : "--user");
3737 return start_special(argc
, argv
, userdata
);
3740 static int check_unit_generic(int code
, const UnitActiveState good_states
[], int nb_states
, char **args
) {
3741 _cleanup_strv_free_
char **names
= NULL
;
3742 UnitActiveState active_state
;
3748 r
= acquire_bus(BUS_MANAGER
, &bus
);
3752 r
= expand_names(bus
, args
, NULL
, &names
, NULL
);
3754 return log_error_errno(r
, "Failed to expand names: %m");
3756 STRV_FOREACH(name
, names
) {
3757 r
= get_state_one_unit(bus
, *name
, &active_state
);
3762 puts(unit_active_state_to_string(active_state
));
3764 for (i
= 0; i
< nb_states
; ++i
)
3765 if (good_states
[i
] == active_state
)
3769 /* use the given return code for the case that we won't find
3770 * any unit which matches the list */
3771 return found
? 0 : code
;
3774 static int check_unit_active(int argc
, char *argv
[], void *userdata
) {
3775 static const UnitActiveState states
[] = {
3780 /* According to LSB: 3, "program is not running" */
3781 return check_unit_generic(EXIT_PROGRAM_NOT_RUNNING
, states
, ELEMENTSOF(states
), strv_skip(argv
, 1));
3784 static int check_unit_failed(int argc
, char *argv
[], void *userdata
) {
3785 static const UnitActiveState states
[] = {
3789 return check_unit_generic(EXIT_PROGRAM_DEAD_AND_PID_EXISTS
, states
, ELEMENTSOF(states
), strv_skip(argv
, 1));
3792 static int kill_unit(int argc
, char *argv
[], void *userdata
) {
3793 _cleanup_strv_free_
char **names
= NULL
;
3794 char *kill_who
= NULL
, **name
;
3798 r
= acquire_bus(BUS_MANAGER
, &bus
);
3802 polkit_agent_open_maybe();
3805 arg_kill_who
= "all";
3807 /* --fail was specified */
3808 if (streq(arg_job_mode
, "fail"))
3809 kill_who
= strjoina(arg_kill_who
, "-fail");
3811 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
3813 return log_error_errno(r
, "Failed to expand names: %m");
3815 STRV_FOREACH(name
, names
) {
3816 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3818 q
= sd_bus_call_method(
3820 "org.freedesktop.systemd1",
3821 "/org/freedesktop/systemd1",
3822 "org.freedesktop.systemd1.Manager",
3826 "ssi", *name
, kill_who
? kill_who
: arg_kill_who
, arg_signal
);
3828 log_error_errno(q
, "Failed to kill unit %s: %s", *name
, bus_error_message(&error
, q
));
3837 static int clean_unit(int argc
, char *argv
[], void *userdata
) {
3838 _cleanup_(bus_wait_for_units_freep
) BusWaitForUnits
*w
= NULL
;
3839 _cleanup_strv_free_
char **names
= NULL
;
3840 int r
, ret
= EXIT_SUCCESS
;
3844 r
= acquire_bus(BUS_FULL
, &bus
);
3848 polkit_agent_open_maybe();
3850 if (!arg_clean_what
) {
3851 arg_clean_what
= strv_new("cache", "runtime");
3852 if (!arg_clean_what
)
3856 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
3858 return log_error_errno(r
, "Failed to expand names: %m");
3860 if (!arg_no_block
) {
3861 r
= bus_wait_for_units_new(bus
, &w
);
3863 return log_error_errno(r
, "Failed to allocate unit waiter: %m");
3866 STRV_FOREACH(name
, names
) {
3867 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3868 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
3871 /* If we shall wait for the cleaning to complete, let's add a ref on the unit first */
3872 r
= sd_bus_call_method(
3874 "org.freedesktop.systemd1",
3875 "/org/freedesktop/systemd1",
3876 "org.freedesktop.systemd1.Manager",
3882 log_error_errno(r
, "Failed to add reference to unit %s: %s", *name
, bus_error_message(&error
, r
));
3883 if (ret
== EXIT_SUCCESS
)
3889 r
= sd_bus_message_new_method_call(
3892 "org.freedesktop.systemd1",
3893 "/org/freedesktop/systemd1",
3894 "org.freedesktop.systemd1.Manager",
3897 return bus_log_create_error(r
);
3899 r
= sd_bus_message_append(m
, "s", *name
);
3901 return bus_log_create_error(r
);
3903 r
= sd_bus_message_append_strv(m
, arg_clean_what
);
3905 return bus_log_create_error(r
);
3907 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
3909 log_error_errno(r
, "Failed to clean unit %s: %s", *name
, bus_error_message(&error
, r
));
3910 if (ret
== EXIT_SUCCESS
) {
3917 r
= bus_wait_for_units_add_unit(w
, *name
, BUS_WAIT_REFFED
|BUS_WAIT_FOR_MAINTENANCE_END
, NULL
, NULL
);
3919 return log_error_errno(r
, "Failed to watch unit %s: %m", *name
);
3923 r
= bus_wait_for_units_run(w
);
3925 return log_error_errno(r
, "Failed to wait for units: %m");
3926 if (r
== BUS_WAIT_FAILURE
)
3932 typedef struct ExecStatusInfo
{
3940 usec_t start_timestamp
;
3941 usec_t exit_timestamp
;
3946 ExecCommandFlags flags
;
3948 LIST_FIELDS(struct ExecStatusInfo
, exec
);
3951 static void exec_status_info_free(ExecStatusInfo
*i
) {
3960 static int exec_status_info_deserialize(sd_bus_message
*m
, ExecStatusInfo
*i
, bool is_ex_prop
) {
3961 _cleanup_strv_free_
char **ex_opts
= NULL
;
3962 uint64_t start_timestamp
, exit_timestamp
, start_timestamp_monotonic
, exit_timestamp_monotonic
;
3965 int32_t code
, status
;
3971 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_STRUCT
, is_ex_prop
? "sasasttttuii" : "sasbttttuii");
3973 return bus_log_parse_error(r
);
3977 r
= sd_bus_message_read(m
, "s", &path
);
3979 return bus_log_parse_error(r
);
3981 i
->path
= strdup(path
);
3985 r
= sd_bus_message_read_strv(m
, &i
->argv
);
3987 return bus_log_parse_error(r
);
3989 r
= is_ex_prop
? sd_bus_message_read_strv(m
, &ex_opts
) : sd_bus_message_read(m
, "b", &ignore
);
3991 return bus_log_parse_error(r
);
3993 r
= sd_bus_message_read(m
,
3995 &start_timestamp
, &start_timestamp_monotonic
,
3996 &exit_timestamp
, &exit_timestamp_monotonic
,
4000 return bus_log_parse_error(r
);
4003 r
= exec_command_flags_from_strv(ex_opts
, &i
->flags
);
4005 return log_error_errno(r
, "Failed to convert strv to ExecCommandFlags: %m");
4007 i
->ignore
= FLAGS_SET(i
->flags
, EXEC_COMMAND_IGNORE_FAILURE
);
4011 i
->start_timestamp
= (usec_t
) start_timestamp
;
4012 i
->exit_timestamp
= (usec_t
) exit_timestamp
;
4013 i
->pid
= (pid_t
) pid
;
4017 r
= sd_bus_message_exit_container(m
);
4019 return bus_log_parse_error(r
);
4024 typedef struct UnitCondition
{
4031 LIST_FIELDS(struct UnitCondition
, conditions
);
4034 static void unit_condition_free(UnitCondition
*c
) {
4043 DEFINE_TRIVIAL_CLEANUP_FUNC(UnitCondition
*, unit_condition_free
);
4045 typedef struct UnitStatusInfo
{
4047 const char *load_state
;
4048 const char *active_state
;
4049 const char *sub_state
;
4050 const char *unit_file_state
;
4051 const char *unit_file_preset
;
4053 const char *description
;
4054 const char *following
;
4056 char **documentation
;
4058 const char *fragment_path
;
4059 const char *source_path
;
4060 const char *control_group
;
4062 char **dropin_paths
;
4064 char **triggered_by
;
4067 const char *load_error
;
4070 usec_t inactive_exit_timestamp
;
4071 usec_t inactive_exit_timestamp_monotonic
;
4072 usec_t active_enter_timestamp
;
4073 usec_t active_exit_timestamp
;
4074 usec_t inactive_enter_timestamp
;
4076 bool need_daemon_reload
;
4082 const char *status_text
;
4083 const char *pid_file
;
4087 usec_t start_timestamp
;
4088 usec_t exit_timestamp
;
4090 int exit_code
, exit_status
;
4092 const char *log_namespace
;
4094 usec_t condition_timestamp
;
4095 bool condition_result
;
4096 LIST_HEAD(UnitCondition
, conditions
);
4098 usec_t assert_timestamp
;
4100 bool failed_assert_trigger
;
4101 bool failed_assert_negate
;
4102 const char *failed_assert
;
4103 const char *failed_assert_parameter
;
4104 usec_t next_elapse_real
;
4105 usec_t next_elapse_monotonic
;
4108 unsigned n_accepted
;
4109 unsigned n_connections
;
4113 /* Pairs of type, path */
4117 const char *sysfs_path
;
4119 /* Mount, Automount */
4126 uint64_t memory_current
;
4127 uint64_t memory_min
;
4128 uint64_t memory_low
;
4129 uint64_t memory_high
;
4130 uint64_t memory_max
;
4131 uint64_t memory_swap_max
;
4132 uint64_t memory_limit
;
4133 uint64_t cpu_usage_nsec
;
4134 uint64_t tasks_current
;
4136 uint64_t ip_ingress_bytes
;
4137 uint64_t ip_egress_bytes
;
4138 uint64_t io_read_bytes
;
4139 uint64_t io_write_bytes
;
4141 uint64_t default_memory_min
;
4142 uint64_t default_memory_low
;
4144 LIST_HEAD(ExecStatusInfo
, exec
);
4147 static void unit_status_info_free(UnitStatusInfo
*info
) {
4151 strv_free(info
->documentation
);
4152 strv_free(info
->dropin_paths
);
4153 strv_free(info
->triggered_by
);
4154 strv_free(info
->triggers
);
4155 strv_free(info
->listen
);
4157 while ((c
= info
->conditions
)) {
4158 LIST_REMOVE(conditions
, info
->conditions
, c
);
4159 unit_condition_free(c
);
4162 while ((p
= info
->exec
)) {
4163 LIST_REMOVE(exec
, info
->exec
, p
);
4164 exec_status_info_free(p
);
4168 static void format_active_state(const char *active_state
, const char **active_on
, const char **active_off
) {
4169 if (streq_ptr(active_state
, "failed")) {
4170 *active_on
= ansi_highlight_red();
4171 *active_off
= ansi_normal();
4172 } else if (STRPTR_IN_SET(active_state
, "active", "reloading")) {
4173 *active_on
= ansi_highlight_green();
4174 *active_off
= ansi_normal();
4176 *active_on
= *active_off
= "";
4179 static void print_status_info(
4184 char since1
[FORMAT_TIMESTAMP_RELATIVE_MAX
], since2
[FORMAT_TIMESTAMP_MAX
];
4185 const char *s1
, *s2
, *active_on
, *active_off
, *on
, *off
, *ss
;
4186 _cleanup_free_
char *formatted_path
= NULL
;
4195 /* This shows pretty information about a unit. See
4196 * print_property() for a low-level property printer */
4198 format_active_state(i
->active_state
, &active_on
, &active_off
);
4200 printf("%s%s%s %s", active_on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), active_off
, strna(i
->id
));
4202 if (i
->description
&& !streq_ptr(i
->id
, i
->description
))
4203 printf(" - %s", i
->description
);
4208 printf(" Follow: unit currently follows state of %s\n", i
->following
);
4210 if (STRPTR_IN_SET(i
->load_state
, "error", "not-found", "bad-setting")) {
4211 on
= ansi_highlight_red();
4212 off
= ansi_normal();
4216 path
= i
->source_path
?: i
->fragment_path
;
4217 if (path
&& terminal_urlify_path(path
, NULL
, &formatted_path
) >= 0)
4218 path
= formatted_path
;
4220 if (!isempty(i
->load_error
))
4221 printf(" Loaded: %s%s%s (Reason: %s)\n",
4222 on
, strna(i
->load_state
), off
, i
->load_error
);
4223 else if (path
&& !isempty(i
->unit_file_state
) && !isempty(i
->unit_file_preset
) &&
4224 !STR_IN_SET(i
->unit_file_state
, "generated", "transient"))
4225 printf(" Loaded: %s%s%s (%s; %s; vendor preset: %s)\n",
4226 on
, strna(i
->load_state
), off
, path
, i
->unit_file_state
, i
->unit_file_preset
);
4227 else if (path
&& !isempty(i
->unit_file_state
))
4228 printf(" Loaded: %s%s%s (%s; %s)\n",
4229 on
, strna(i
->load_state
), off
, path
, i
->unit_file_state
);
4231 printf(" Loaded: %s%s%s (%s)\n",
4232 on
, strna(i
->load_state
), off
, path
);
4234 printf(" Loaded: %s%s%s\n",
4235 on
, strna(i
->load_state
), off
);
4238 printf(" Transient: yes\n");
4240 if (!strv_isempty(i
->dropin_paths
)) {
4241 _cleanup_free_
char *dir
= NULL
;
4245 STRV_FOREACH(dropin
, i
->dropin_paths
) {
4246 _cleanup_free_
char *dropin_formatted
= NULL
;
4255 dir
= dirname_malloc(*dropin
);
4263 special_glyph(SPECIAL_GLYPH_TREE_RIGHT
));
4266 last
= ! (*(dropin
+ 1) && startswith(*(dropin
+ 1), dir
));
4268 if (terminal_urlify_path(*dropin
, basename(*dropin
), &dropin_formatted
) >= 0)
4269 df
= dropin_formatted
;
4273 printf("%s%s", df
, last
? "\n" : ", ");
4277 ss
= streq_ptr(i
->active_state
, i
->sub_state
) ? NULL
: i
->sub_state
;
4279 printf(" Active: %s%s (%s)%s",
4280 active_on
, strna(i
->active_state
), ss
, active_off
);
4282 printf(" Active: %s%s%s",
4283 active_on
, strna(i
->active_state
), active_off
);
4285 if (!isempty(i
->result
) && !streq(i
->result
, "success"))
4286 printf(" (Result: %s)", i
->result
);
4288 timestamp
= STRPTR_IN_SET(i
->active_state
, "active", "reloading") ? i
->active_enter_timestamp
:
4289 STRPTR_IN_SET(i
->active_state
, "inactive", "failed") ? i
->inactive_enter_timestamp
:
4290 STRPTR_IN_SET(i
->active_state
, "activating") ? i
->inactive_exit_timestamp
:
4291 i
->active_exit_timestamp
;
4293 s1
= format_timestamp_relative(since1
, sizeof(since1
), timestamp
);
4294 s2
= format_timestamp(since2
, sizeof(since2
), timestamp
);
4297 printf(" since %s; %s\n", s2
, s1
);
4299 printf(" since %s\n", s2
);
4303 STRV_FOREACH(t
, i
->triggered_by
) {
4304 UnitActiveState state
= _UNIT_ACTIVE_STATE_INVALID
;
4306 (void) get_state_one_unit(bus
, *t
, &state
);
4307 format_active_state(unit_active_state_to_string(state
), &on
, &off
);
4309 printf("%s %s%s%s %s\n",
4310 t
== i
->triggered_by
? "TriggeredBy:" : " ",
4311 on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
,
4315 if (endswith(i
->id
, ".timer")) {
4316 char tstamp1
[FORMAT_TIMESTAMP_RELATIVE_MAX
],
4317 tstamp2
[FORMAT_TIMESTAMP_MAX
];
4318 const char *next_rel_time
, *next_time
;
4319 dual_timestamp nw
, next
= {i
->next_elapse_real
,
4320 i
->next_elapse_monotonic
};
4323 printf(" Trigger: ");
4325 dual_timestamp_get(&nw
);
4326 next_elapse
= calc_next_elapse(&nw
, &next
);
4327 next_rel_time
= format_timestamp_relative(tstamp1
, sizeof tstamp1
, next_elapse
);
4328 next_time
= format_timestamp(tstamp2
, sizeof tstamp2
, next_elapse
);
4330 if (next_time
&& next_rel_time
)
4331 printf("%s; %s\n", next_time
, next_rel_time
);
4336 STRV_FOREACH(t
, i
->triggers
) {
4337 UnitActiveState state
= _UNIT_ACTIVE_STATE_INVALID
;
4339 (void) get_state_one_unit(bus
, *t
, &state
);
4340 format_active_state(unit_active_state_to_string(state
), &on
, &off
);
4342 printf("%s %s%s%s %s\n",
4343 t
== i
->triggers
? " Triggers:" : " ",
4344 on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
,
4348 if (!i
->condition_result
&& i
->condition_timestamp
> 0) {
4352 s1
= format_timestamp_relative(since1
, sizeof(since1
), i
->condition_timestamp
);
4353 s2
= format_timestamp(since2
, sizeof(since2
), i
->condition_timestamp
);
4355 printf(" Condition: start %scondition failed%s at %s%s%s\n",
4356 ansi_highlight_yellow(), ansi_normal(),
4357 s2
, s1
? "; " : "", strempty(s1
));
4359 LIST_FOREACH(conditions
, c
, i
->conditions
)
4360 if (c
->tristate
< 0)
4363 LIST_FOREACH(conditions
, c
, i
->conditions
)
4364 if (c
->tristate
< 0)
4365 printf(" %s %s=%s%s%s was not met\n",
4366 --n
? special_glyph(SPECIAL_GLYPH_TREE_BRANCH
) : special_glyph(SPECIAL_GLYPH_TREE_RIGHT
),
4368 c
->trigger
? "|" : "",
4369 c
->negate
? "!" : "",
4373 if (!i
->assert_result
&& i
->assert_timestamp
> 0) {
4374 s1
= format_timestamp_relative(since1
, sizeof(since1
), i
->assert_timestamp
);
4375 s2
= format_timestamp(since2
, sizeof(since2
), i
->assert_timestamp
);
4377 printf(" Assert: start %sassertion failed%s at %s%s%s\n",
4378 ansi_highlight_red(), ansi_normal(),
4379 s2
, s1
? "; " : "", strempty(s1
));
4380 if (i
->failed_assert_trigger
)
4381 printf(" none of the trigger assertions were met\n");
4382 else if (i
->failed_assert
)
4383 printf(" %s=%s%s was not met\n",
4385 i
->failed_assert_negate
? "!" : "",
4386 i
->failed_assert_parameter
);
4390 printf(" Device: %s\n", i
->sysfs_path
);
4392 printf(" Where: %s\n", i
->where
);
4394 printf(" What: %s\n", i
->what
);
4396 STRV_FOREACH(t
, i
->documentation
) {
4397 _cleanup_free_
char *formatted
= NULL
;
4400 if (terminal_urlify(*t
, NULL
, &formatted
) >= 0)
4405 printf(" %*s %s\n", 9, t
== i
->documentation
? "Docs:" : "", q
);
4408 STRV_FOREACH_PAIR(t
, t2
, i
->listen
)
4409 printf(" %*s %s (%s)\n", 9, t
== i
->listen
? "Listen:" : "", *t2
, *t
);
4412 printf(" Accepted: %u; Connected: %u;", i
->n_accepted
, i
->n_connections
);
4414 printf(" Refused: %u", i
->n_refused
);
4418 LIST_FOREACH(exec
, p
, i
->exec
) {
4419 _cleanup_free_
char *argv
= NULL
;
4422 /* Only show exited processes here */
4426 /* Don't print ExecXYZEx= properties here since it will appear as a
4427 * duplicate of the non-Ex= variant. */
4428 if (endswith(p
->name
, "Ex"))
4431 argv
= strv_join(p
->argv
, " ");
4432 printf(" Process: "PID_FMT
" %s=%s ", p
->pid
, p
->name
, strna(argv
));
4434 good
= is_clean_exit(p
->code
, p
->status
, EXIT_CLEAN_DAEMON
, NULL
);
4436 on
= ansi_highlight_red();
4437 off
= ansi_normal();
4441 printf("%s(code=%s, ", on
, sigchld_code_to_string(p
->code
));
4443 if (p
->code
== CLD_EXITED
) {
4446 printf("status=%i", p
->status
);
4448 c
= exit_status_to_string(p
->status
, EXIT_STATUS_LIBC
| EXIT_STATUS_SYSTEMD
);
4453 printf("signal=%s", signal_to_string(p
->status
));
4455 printf(")%s\n", off
);
4457 if (i
->main_pid
== p
->pid
&&
4458 i
->start_timestamp
== p
->start_timestamp
&&
4459 i
->exit_timestamp
== p
->start_timestamp
)
4460 /* Let's not show this twice */
4463 if (p
->pid
== i
->control_pid
)
4467 if (i
->main_pid
> 0 || i
->control_pid
> 0) {
4468 if (i
->main_pid
> 0) {
4469 printf(" Main PID: "PID_FMT
, i
->main_pid
);
4473 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
4474 _cleanup_free_
char *comm
= NULL
;
4476 (void) get_process_comm(i
->main_pid
, &comm
);
4478 printf(" (%s)", comm
);
4481 } else if (i
->exit_code
> 0) {
4482 printf(" (code=%s, ", sigchld_code_to_string(i
->exit_code
));
4484 if (i
->exit_code
== CLD_EXITED
) {
4487 printf("status=%i", i
->exit_status
);
4489 c
= exit_status_to_string(i
->exit_status
,
4490 EXIT_STATUS_LIBC
| EXIT_STATUS_SYSTEMD
);
4495 printf("signal=%s", signal_to_string(i
->exit_status
));
4500 if (i
->control_pid
> 0) {
4501 _cleanup_free_
char *c
= NULL
;
4503 if (i
->main_pid
> 0)
4504 fputs("; Control PID: ", stdout
);
4506 fputs("Cntrl PID: ", stdout
); /* if first in column, abbreviated so it fits alignment */
4508 printf(PID_FMT
, i
->control_pid
);
4510 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
4511 (void) get_process_comm(i
->control_pid
, &c
);
4521 printf(" Status: \"%s\"\n", i
->status_text
);
4522 if (i
->status_errno
> 0)
4523 printf(" Error: %i (%s)\n", i
->status_errno
, strerror_safe(i
->status_errno
));
4525 if (i
->ip_ingress_bytes
!= (uint64_t) -1 && i
->ip_egress_bytes
!= (uint64_t) -1) {
4526 char buf_in
[FORMAT_BYTES_MAX
], buf_out
[FORMAT_BYTES_MAX
];
4528 printf(" IP: %s in, %s out\n",
4529 format_bytes(buf_in
, sizeof(buf_in
), i
->ip_ingress_bytes
),
4530 format_bytes(buf_out
, sizeof(buf_out
), i
->ip_egress_bytes
));
4533 if (i
->io_read_bytes
!= UINT64_MAX
&& i
->io_write_bytes
!= UINT64_MAX
) {
4534 char buf_in
[FORMAT_BYTES_MAX
], buf_out
[FORMAT_BYTES_MAX
];
4536 printf(" IO: %s read, %s written\n",
4537 format_bytes(buf_in
, sizeof(buf_in
), i
->io_read_bytes
),
4538 format_bytes(buf_out
, sizeof(buf_out
), i
->io_write_bytes
));
4541 if (i
->tasks_current
!= (uint64_t) -1) {
4542 printf(" Tasks: %" PRIu64
, i
->tasks_current
);
4544 if (i
->tasks_max
!= (uint64_t) -1)
4545 printf(" (limit: %" PRIu64
")\n", i
->tasks_max
);
4550 if (i
->memory_current
!= (uint64_t) -1) {
4551 char buf
[FORMAT_BYTES_MAX
];
4553 printf(" Memory: %s", format_bytes(buf
, sizeof(buf
), i
->memory_current
));
4555 if (i
->memory_min
> 0 || i
->memory_low
> 0 ||
4556 i
->memory_high
!= CGROUP_LIMIT_MAX
|| i
->memory_max
!= CGROUP_LIMIT_MAX
||
4557 i
->memory_swap_max
!= CGROUP_LIMIT_MAX
||
4558 i
->memory_limit
!= CGROUP_LIMIT_MAX
) {
4559 const char *prefix
= "";
4562 if (i
->memory_min
> 0) {
4563 printf("%smin: %s", prefix
, format_bytes_cgroup_protection(buf
, sizeof(buf
), i
->memory_min
));
4566 if (i
->memory_low
> 0) {
4567 printf("%slow: %s", prefix
, format_bytes_cgroup_protection(buf
, sizeof(buf
), i
->memory_low
));
4570 if (i
->memory_high
!= CGROUP_LIMIT_MAX
) {
4571 printf("%shigh: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_high
));
4574 if (i
->memory_max
!= CGROUP_LIMIT_MAX
) {
4575 printf("%smax: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_max
));
4578 if (i
->memory_swap_max
!= CGROUP_LIMIT_MAX
) {
4579 printf("%sswap max: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_swap_max
));
4582 if (i
->memory_limit
!= CGROUP_LIMIT_MAX
) {
4583 printf("%slimit: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_limit
));
4591 if (i
->cpu_usage_nsec
!= (uint64_t) -1) {
4592 char buf
[FORMAT_TIMESPAN_MAX
];
4593 printf(" CPU: %s\n", format_timespan(buf
, sizeof(buf
), i
->cpu_usage_nsec
/ NSEC_PER_USEC
, USEC_PER_MSEC
));
4596 if (i
->control_group
) {
4597 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
4598 static const char prefix
[] = " ";
4601 printf(" CGroup: %s\n", i
->control_group
);
4604 if (c
> sizeof(prefix
) - 1)
4605 c
-= sizeof(prefix
) - 1;
4609 r
= unit_show_processes(bus
, i
->id
, i
->control_group
, prefix
, c
, get_output_flags(), &error
);
4614 /* Fallback for older systemd versions where the GetUnitProcesses() call is not yet available */
4616 if (i
->main_pid
> 0)
4617 extra
[k
++] = i
->main_pid
;
4619 if (i
->control_pid
> 0)
4620 extra
[k
++] = i
->control_pid
;
4622 show_cgroup_and_extra(SYSTEMD_CGROUP_CONTROLLER
, i
->control_group
, prefix
, c
, extra
, k
, get_output_flags());
4624 log_warning_errno(r
, "Failed to dump process list for '%s', ignoring: %s",
4625 i
->id
, bus_error_message(&error
, r
));
4628 if (i
->id
&& arg_transport
== BUS_TRANSPORT_LOCAL
)
4629 show_journal_by_unit(
4635 i
->inactive_exit_timestamp_monotonic
,
4638 get_output_flags() | OUTPUT_BEGIN_NEWLINE
,
4639 SD_JOURNAL_LOCAL_ONLY
,
4640 arg_scope
== UNIT_FILE_SYSTEM
,
4643 if (i
->need_daemon_reload
)
4644 warn_unit_file_changed(i
->id
);
4647 static void show_unit_help(UnitStatusInfo
*i
) {
4652 if (!i
->documentation
) {
4653 log_info("Documentation for %s not known.", i
->id
);
4657 STRV_FOREACH(p
, i
->documentation
)
4658 if (startswith(*p
, "man:"))
4659 show_man_page(*p
+ 4, false);
4661 log_info("Can't show: %s", *p
);
4664 static int map_main_pid(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4665 UnitStatusInfo
*i
= userdata
;
4669 r
= sd_bus_message_read(m
, "u", &u
);
4673 i
->main_pid
= (pid_t
) u
;
4679 static int map_load_error(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4680 const char *message
, **p
= userdata
;
4683 r
= sd_bus_message_read(m
, "(ss)", NULL
, &message
);
4687 if (!isempty(message
))
4693 static int map_listen(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4694 const char *type
, *path
;
4695 char ***p
= userdata
;
4698 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
4702 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0) {
4704 r
= strv_extend(p
, type
);
4708 r
= strv_extend(p
, path
);
4715 r
= sd_bus_message_exit_container(m
);
4722 static int map_conditions(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4723 UnitStatusInfo
*i
= userdata
;
4724 const char *cond
, *param
;
4725 int trigger
, negate
;
4729 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sbbsi)");
4733 while ((r
= sd_bus_message_read(m
, "(sbbsi)", &cond
, &trigger
, &negate
, ¶m
, &state
)) > 0) {
4734 _cleanup_(unit_condition_freep
) UnitCondition
*c
= NULL
;
4736 c
= new(UnitCondition
, 1);
4740 *c
= (UnitCondition
) {
4741 .name
= strdup(cond
),
4742 .param
= strdup(param
),
4748 if (!c
->name
|| !c
->param
)
4751 LIST_PREPEND(conditions
, i
->conditions
, TAKE_PTR(c
));
4756 r
= sd_bus_message_exit_container(m
);
4763 static int map_asserts(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4764 UnitStatusInfo
*i
= userdata
;
4765 const char *cond
, *param
;
4766 int trigger
, negate
;
4770 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sbbsi)");
4774 while ((r
= sd_bus_message_read(m
, "(sbbsi)", &cond
, &trigger
, &negate
, ¶m
, &state
)) > 0) {
4775 if (state
< 0 && (!trigger
|| !i
->failed_assert
)) {
4776 i
->failed_assert
= cond
;
4777 i
->failed_assert_trigger
= trigger
;
4778 i
->failed_assert_negate
= negate
;
4779 i
->failed_assert_parameter
= param
;
4785 r
= sd_bus_message_exit_container(m
);
4792 static int map_exec(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4793 _cleanup_free_ ExecStatusInfo
*info
= NULL
;
4794 ExecStatusInfo
*last
;
4795 UnitStatusInfo
*i
= userdata
;
4796 bool is_ex_prop
= endswith(member
, "Ex");
4799 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, is_ex_prop
? "(sasasttttuii)" : "(sasbttttuii)");
4803 info
= new0(ExecStatusInfo
, 1);
4807 LIST_FIND_TAIL(exec
, i
->exec
, last
);
4809 while ((r
= exec_status_info_deserialize(m
, info
, is_ex_prop
)) > 0) {
4811 info
->name
= strdup(member
);
4815 LIST_INSERT_AFTER(exec
, i
->exec
, last
, info
);
4818 info
= new0(ExecStatusInfo
, 1);
4825 r
= sd_bus_message_exit_container(m
);
4832 static int print_property(const char *name
, const char *expected_value
, sd_bus_message
*m
, bool value
, bool all
) {
4834 const char *contents
;
4840 /* This is a low-level property printer, see
4841 * print_status_info() for the nicer output */
4843 r
= sd_bus_message_peek_type(m
, &bus_type
, &contents
);
4849 case SD_BUS_TYPE_INT32
:
4850 if (endswith(name
, "ActionExitStatus")) {
4853 r
= sd_bus_message_read_basic(m
, bus_type
, &i
);
4857 if (i
>= 0 && i
<= 255)
4858 bus_print_property_valuef(name
, expected_value
, value
, "%"PRIi32
, i
);
4860 bus_print_property_value(name
, expected_value
, value
, "[not set]");
4863 } else if (streq(name
, "NUMAPolicy")) {
4866 r
= sd_bus_message_read_basic(m
, bus_type
, &i
);
4870 bus_print_property_valuef(name
, expected_value
, value
, "%s", strna(mpol_to_string(i
)));
4876 case SD_BUS_TYPE_STRUCT
:
4878 if (contents
[0] == SD_BUS_TYPE_UINT32
&& streq(name
, "Job")) {
4881 r
= sd_bus_message_read(m
, "(uo)", &u
, NULL
);
4883 return bus_log_parse_error(r
);
4886 bus_print_property_valuef(name
, expected_value
, value
, "%"PRIu32
, u
);
4888 bus_print_property_value(name
, expected_value
, value
, "");
4892 } else if (contents
[0] == SD_BUS_TYPE_STRING
&& streq(name
, "Unit")) {
4895 r
= sd_bus_message_read(m
, "(so)", &s
, NULL
);
4897 return bus_log_parse_error(r
);
4899 if (all
|| !isempty(s
))
4900 bus_print_property_value(name
, expected_value
, value
, s
);
4904 } else if (contents
[0] == SD_BUS_TYPE_STRING
&& streq(name
, "LoadError")) {
4905 const char *a
= NULL
, *b
= NULL
;
4907 r
= sd_bus_message_read(m
, "(ss)", &a
, &b
);
4909 return bus_log_parse_error(r
);
4911 if (!isempty(a
) || !isempty(b
))
4912 bus_print_property_valuef(name
, expected_value
, value
, "%s \"%s\"", strempty(a
), strempty(b
));
4914 bus_print_property_value(name
, expected_value
, value
, "");
4918 } else if (STR_IN_SET(name
, "SystemCallFilter", "RestrictAddressFamilies")) {
4919 _cleanup_strv_free_
char **l
= NULL
;
4922 r
= sd_bus_message_enter_container(m
, 'r', "bas");
4924 return bus_log_parse_error(r
);
4926 r
= sd_bus_message_read(m
, "b", &whitelist
);
4928 return bus_log_parse_error(r
);
4930 r
= sd_bus_message_read_strv(m
, &l
);
4932 return bus_log_parse_error(r
);
4934 r
= sd_bus_message_exit_container(m
);
4936 return bus_log_parse_error(r
);
4938 if (all
|| whitelist
|| !strv_isempty(l
)) {
4943 fputs(name
, stdout
);
4950 STRV_FOREACH(i
, l
) {
4958 fputc('\n', stdout
);
4963 } else if (STR_IN_SET(name
, "SELinuxContext", "AppArmorProfile", "SmackProcessLabel")) {
4967 r
= sd_bus_message_read(m
, "(bs)", &ignore
, &s
);
4969 return bus_log_parse_error(r
);
4972 bus_print_property_valuef(name
, expected_value
, value
, "%s%s", ignore
? "-" : "", s
);
4974 bus_print_property_value(name
, expected_value
, value
, "");
4978 } else if (endswith(name
, "ExitStatus") && streq(contents
, "aiai")) {
4979 const int32_t *status
, *signal
;
4980 size_t n_status
, n_signal
, i
;
4982 r
= sd_bus_message_enter_container(m
, 'r', "aiai");
4984 return bus_log_parse_error(r
);
4986 r
= sd_bus_message_read_array(m
, 'i', (const void **) &status
, &n_status
);
4988 return bus_log_parse_error(r
);
4990 r
= sd_bus_message_read_array(m
, 'i', (const void **) &signal
, &n_signal
);
4992 return bus_log_parse_error(r
);
4994 r
= sd_bus_message_exit_container(m
);
4996 return bus_log_parse_error(r
);
4998 n_status
/= sizeof(int32_t);
4999 n_signal
/= sizeof(int32_t);
5001 if (all
|| n_status
> 0 || n_signal
> 0) {
5005 fputs(name
, stdout
);
5009 for (i
= 0; i
< n_status
; i
++) {
5015 printf("%"PRIi32
, status
[i
]);
5018 for (i
= 0; i
< n_signal
; i
++) {
5021 str
= signal_to_string((int) signal
[i
]);
5031 printf("%"PRIi32
, status
[i
]);
5034 fputc('\n', stdout
);
5041 case SD_BUS_TYPE_ARRAY
:
5043 if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "EnvironmentFiles")) {
5047 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sb)");
5049 return bus_log_parse_error(r
);
5051 while ((r
= sd_bus_message_read(m
, "(sb)", &path
, &ignore
)) > 0)
5052 bus_print_property_valuef(name
, expected_value
, value
, "%s (ignore_errors=%s)", path
, yes_no(ignore
));
5055 return bus_log_parse_error(r
);
5057 r
= sd_bus_message_exit_container(m
);
5059 return bus_log_parse_error(r
);
5063 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "Paths")) {
5064 const char *type
, *path
;
5066 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5068 return bus_log_parse_error(r
);
5070 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0)
5071 bus_print_property_valuef(name
, expected_value
, value
, "%s (%s)", path
, type
);
5073 return bus_log_parse_error(r
);
5075 r
= sd_bus_message_exit_container(m
);
5077 return bus_log_parse_error(r
);
5081 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "Listen")) {
5082 const char *type
, *path
;
5084 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5086 return bus_log_parse_error(r
);
5088 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0)
5089 bus_print_property_valuef(name
, expected_value
, value
, "%s (%s)", path
, type
);
5091 return bus_log_parse_error(r
);
5093 r
= sd_bus_message_exit_container(m
);
5095 return bus_log_parse_error(r
);
5099 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "TimersMonotonic")) {
5101 uint64_t v
, next_elapse
;
5103 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(stt)");
5105 return bus_log_parse_error(r
);
5107 while ((r
= sd_bus_message_read(m
, "(stt)", &base
, &v
, &next_elapse
)) > 0) {
5108 char timespan1
[FORMAT_TIMESPAN_MAX
] = "n/a", timespan2
[FORMAT_TIMESPAN_MAX
] = "n/a";
5110 (void) format_timespan(timespan1
, sizeof timespan1
, v
, 0);
5111 (void) format_timespan(timespan2
, sizeof timespan2
, next_elapse
, 0);
5113 bus_print_property_valuef(name
, expected_value
, value
,
5114 "{ %s=%s ; next_elapse=%s }", base
, timespan1
, timespan2
);
5117 return bus_log_parse_error(r
);
5119 r
= sd_bus_message_exit_container(m
);
5121 return bus_log_parse_error(r
);
5125 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "TimersCalendar")) {
5126 const char *base
, *spec
;
5127 uint64_t next_elapse
;
5129 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sst)");
5131 return bus_log_parse_error(r
);
5133 while ((r
= sd_bus_message_read(m
, "(sst)", &base
, &spec
, &next_elapse
)) > 0) {
5134 char timestamp
[FORMAT_TIMESTAMP_MAX
] = "n/a";
5136 (void) format_timestamp(timestamp
, sizeof(timestamp
), next_elapse
);
5137 bus_print_property_valuef(name
, expected_value
, value
,
5138 "{ %s=%s ; next_elapse=%s }", base
, spec
, timestamp
);
5141 return bus_log_parse_error(r
);
5143 r
= sd_bus_message_exit_container(m
);
5145 return bus_log_parse_error(r
);
5149 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& startswith(name
, "Exec")) {
5150 ExecStatusInfo info
= {};
5151 bool is_ex_prop
= endswith(name
, "Ex");
5153 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, is_ex_prop
? "(sasasttttuii)" : "(sasbttttuii)");
5155 return bus_log_parse_error(r
);
5157 while ((r
= exec_status_info_deserialize(m
, &info
, is_ex_prop
)) > 0) {
5158 char timestamp1
[FORMAT_TIMESTAMP_MAX
], timestamp2
[FORMAT_TIMESTAMP_MAX
];
5159 _cleanup_strv_free_
char **optv
= NULL
;
5160 _cleanup_free_
char *tt
, *o
= NULL
;
5162 tt
= strv_join(info
.argv
, " ");
5165 r
= exec_command_flags_to_strv(info
.flags
, &optv
);
5167 return log_error_errno(r
, "Failed to convert ExecCommandFlags to strv: %m");
5169 o
= strv_join(optv
, " ");
5171 bus_print_property_valuef(name
, expected_value
, value
,
5172 "{ path=%s ; argv[]=%s ; flags=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT
" ; code=%s ; status=%i%s%s }",
5176 strna(format_timestamp(timestamp1
, sizeof(timestamp1
), info
.start_timestamp
)),
5177 strna(format_timestamp(timestamp2
, sizeof(timestamp2
), info
.exit_timestamp
)),
5179 sigchld_code_to_string(info
.code
),
5181 info
.code
== CLD_EXITED
? "" : "/",
5182 strempty(info
.code
== CLD_EXITED
? NULL
: signal_to_string(info
.status
)));
5184 bus_print_property_valuef(name
, expected_value
, value
,
5185 "{ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT
" ; code=%s ; status=%i%s%s }",
5188 yes_no(info
.ignore
),
5189 strna(format_timestamp(timestamp1
, sizeof(timestamp1
), info
.start_timestamp
)),
5190 strna(format_timestamp(timestamp2
, sizeof(timestamp2
), info
.exit_timestamp
)),
5192 sigchld_code_to_string(info
.code
),
5194 info
.code
== CLD_EXITED
? "" : "/",
5195 strempty(info
.code
== CLD_EXITED
? NULL
: signal_to_string(info
.status
)));
5198 strv_free(info
.argv
);
5202 r
= sd_bus_message_exit_container(m
);
5204 return bus_log_parse_error(r
);
5208 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "DeviceAllow")) {
5209 const char *path
, *rwm
;
5211 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5213 return bus_log_parse_error(r
);
5215 while ((r
= sd_bus_message_read(m
, "(ss)", &path
, &rwm
)) > 0)
5216 bus_print_property_valuef(name
, expected_value
, value
, "%s %s", strna(path
), strna(rwm
));
5218 return bus_log_parse_error(r
);
5220 r
= sd_bus_message_exit_container(m
);
5222 return bus_log_parse_error(r
);
5226 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5227 STR_IN_SET(name
, "IODeviceWeight", "BlockIODeviceWeight")) {
5231 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5233 return bus_log_parse_error(r
);
5235 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &weight
)) > 0)
5236 bus_print_property_valuef(name
, expected_value
, value
, "%s %"PRIu64
, strna(path
), weight
);
5238 return bus_log_parse_error(r
);
5240 r
= sd_bus_message_exit_container(m
);
5242 return bus_log_parse_error(r
);
5246 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5247 (cgroup_io_limit_type_from_string(name
) >= 0 ||
5248 STR_IN_SET(name
, "BlockIOReadBandwidth", "BlockIOWriteBandwidth"))) {
5252 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5254 return bus_log_parse_error(r
);
5256 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &bandwidth
)) > 0)
5257 bus_print_property_valuef(name
, expected_value
, value
, "%s %"PRIu64
, strna(path
), bandwidth
);
5259 return bus_log_parse_error(r
);
5261 r
= sd_bus_message_exit_container(m
);
5263 return bus_log_parse_error(r
);
5267 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5268 streq(name
, "IODeviceLatencyTargetUSec")) {
5269 char ts
[FORMAT_TIMESPAN_MAX
];
5273 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5275 return bus_log_parse_error(r
);
5277 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &target
)) > 0)
5278 bus_print_property_valuef(name
, expected_value
, value
, "%s %s", strna(path
),
5279 format_timespan(ts
, sizeof(ts
), target
, 1));
5281 return bus_log_parse_error(r
);
5283 r
= sd_bus_message_exit_container(m
);
5285 return bus_log_parse_error(r
);
5289 } else if (contents
[0] == SD_BUS_TYPE_BYTE
&& streq(name
, "StandardInputData")) {
5290 _cleanup_free_
char *h
= NULL
;
5295 r
= sd_bus_message_read_array(m
, 'y', &p
, &sz
);
5297 return bus_log_parse_error(r
);
5299 n
= base64mem(p
, sz
, &h
);
5303 bus_print_property_value(name
, expected_value
, value
, h
);
5307 } else if (STR_IN_SET(name
, "IPAddressAllow", "IPAddressDeny")) {
5308 _cleanup_free_
char *addresses
= NULL
;
5310 r
= sd_bus_message_enter_container(m
, 'a', "(iayu)");
5312 return bus_log_parse_error(r
);
5315 _cleanup_free_
char *str
= NULL
;
5321 r
= sd_bus_message_enter_container(m
, 'r', "iayu");
5323 return bus_log_parse_error(r
);
5327 r
= sd_bus_message_read(m
, "i", &family
);
5329 return bus_log_parse_error(r
);
5331 r
= sd_bus_message_read_array(m
, 'y', &ap
, &an
);
5333 return bus_log_parse_error(r
);
5335 r
= sd_bus_message_read(m
, "u", &prefixlen
);
5337 return bus_log_parse_error(r
);
5339 r
= sd_bus_message_exit_container(m
);
5341 return bus_log_parse_error(r
);
5343 if (!IN_SET(family
, AF_INET
, AF_INET6
))
5346 if (an
!= FAMILY_ADDRESS_SIZE(family
))
5349 if (prefixlen
> FAMILY_ADDRESS_SIZE(family
) * 8)
5352 if (in_addr_prefix_to_string(family
, (union in_addr_union
*) ap
, prefixlen
, &str
) < 0)
5355 if (!strextend_with_separator(&addresses
, " ", str
, NULL
))
5359 r
= sd_bus_message_exit_container(m
);
5361 return bus_log_parse_error(r
);
5363 if (all
|| !isempty(addresses
))
5364 bus_print_property_value(name
, expected_value
, value
, strempty(addresses
));
5368 } else if (STR_IN_SET(name
, "BindPaths", "BindReadOnlyPaths")) {
5369 _cleanup_free_
char *paths
= NULL
;
5370 const char *source
, *dest
;
5374 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ssbt)");
5376 return bus_log_parse_error(r
);
5378 while ((r
= sd_bus_message_read(m
, "(ssbt)", &source
, &dest
, &ignore_enoent
, &rbind
)) > 0) {
5379 _cleanup_free_
char *str
= NULL
;
5381 if (isempty(source
))
5384 if (asprintf(&str
, "%s%s%s%s%s",
5385 ignore_enoent
? "-" : "",
5387 isempty(dest
) ? "" : ":",
5389 rbind
== MS_REC
? ":rbind" : "") < 0)
5392 if (!strextend_with_separator(&paths
, " ", str
, NULL
))
5396 return bus_log_parse_error(r
);
5398 r
= sd_bus_message_exit_container(m
);
5400 return bus_log_parse_error(r
);
5402 if (all
|| !isempty(paths
))
5403 bus_print_property_value(name
, expected_value
, value
, strempty(paths
));
5407 } else if (streq(name
, "TemporaryFileSystem")) {
5408 _cleanup_free_
char *paths
= NULL
;
5409 const char *target
, *option
;
5411 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5413 return bus_log_parse_error(r
);
5415 while ((r
= sd_bus_message_read(m
, "(ss)", &target
, &option
)) > 0) {
5416 _cleanup_free_
char *str
= NULL
;
5418 if (isempty(target
))
5421 if (asprintf(&str
, "%s%s%s", target
, isempty(option
) ? "" : ":", strempty(option
)) < 0)
5424 if (!strextend_with_separator(&paths
, " ", str
, NULL
))
5428 return bus_log_parse_error(r
);
5430 r
= sd_bus_message_exit_container(m
);
5432 return bus_log_parse_error(r
);
5434 if (all
|| !isempty(paths
))
5435 bus_print_property_value(name
, expected_value
, value
, strempty(paths
));
5439 } else if (streq(name
, "LogExtraFields")) {
5440 _cleanup_free_
char *fields
= NULL
;
5444 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "ay");
5446 return bus_log_parse_error(r
);
5448 while ((r
= sd_bus_message_read_array(m
, 'y', &p
, &sz
)) > 0) {
5449 _cleanup_free_
char *str
= NULL
;
5452 if (memchr(p
, 0, sz
))
5455 eq
= memchr(p
, '=', sz
);
5459 if (!journal_field_valid(p
, eq
- (const char*) p
, false))
5462 str
= malloc(sz
+ 1);
5469 if (!utf8_is_valid(str
))
5472 if (!strextend_with_separator(&fields
, " ", str
, NULL
))
5476 return bus_log_parse_error(r
);
5478 r
= sd_bus_message_exit_container(m
);
5480 return bus_log_parse_error(r
);
5482 if (all
|| !isempty(fields
))
5483 bus_print_property_value(name
, expected_value
, value
, strempty(fields
));
5486 } else if (contents
[0] == SD_BUS_TYPE_BYTE
&& STR_IN_SET(name
, "CPUAffinity", "NUMAMask", "AllowedCPUs", "AllowedMemoryNodes", "EffectiveCPUs", "EffectiveMemoryNodes")) {
5487 _cleanup_free_
char *affinity
= NULL
;
5488 _cleanup_(cpu_set_reset
) CPUSet set
= {};
5492 r
= sd_bus_message_read_array(m
, 'y', &a
, &n
);
5494 return bus_log_parse_error(r
);
5496 r
= cpu_set_from_dbus(a
, n
, &set
);
5498 return log_error_errno(r
, "Failed to deserialize %s: %m", name
);
5500 affinity
= cpu_set_to_range_string(&set
);
5504 bus_print_property_value(name
, expected_value
, value
, affinity
);
5515 typedef enum SystemctlShowMode
{
5516 SYSTEMCTL_SHOW_PROPERTIES
,
5517 SYSTEMCTL_SHOW_STATUS
,
5518 SYSTEMCTL_SHOW_HELP
,
5519 _SYSTEMCTL_SHOW_MODE_MAX
,
5520 _SYSTEMCTL_SHOW_MODE_INVALID
= -1,
5521 } SystemctlShowMode
;
5523 static const char* const systemctl_show_mode_table
[_SYSTEMCTL_SHOW_MODE_MAX
] = {
5524 [SYSTEMCTL_SHOW_PROPERTIES
] = "show",
5525 [SYSTEMCTL_SHOW_STATUS
] = "status",
5526 [SYSTEMCTL_SHOW_HELP
] = "help",
5529 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(systemctl_show_mode
, SystemctlShowMode
);
5531 static int show_one(
5535 SystemctlShowMode show_mode
,
5539 static const struct bus_properties_map property_map
[] = {
5540 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
5541 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
) },
5542 { "Documentation", "as", NULL
, offsetof(UnitStatusInfo
, documentation
) },
5545 { "Id", "s", NULL
, offsetof(UnitStatusInfo
, id
) },
5546 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
5547 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
) },
5548 { "SubState", "s", NULL
, offsetof(UnitStatusInfo
, sub_state
) },
5549 { "UnitFileState", "s", NULL
, offsetof(UnitStatusInfo
, unit_file_state
) },
5550 { "UnitFilePreset", "s", NULL
, offsetof(UnitStatusInfo
, unit_file_preset
) },
5551 { "Description", "s", NULL
, offsetof(UnitStatusInfo
, description
) },
5552 { "Following", "s", NULL
, offsetof(UnitStatusInfo
, following
) },
5553 { "Documentation", "as", NULL
, offsetof(UnitStatusInfo
, documentation
) },
5554 { "FragmentPath", "s", NULL
, offsetof(UnitStatusInfo
, fragment_path
) },
5555 { "SourcePath", "s", NULL
, offsetof(UnitStatusInfo
, source_path
) },
5556 { "ControlGroup", "s", NULL
, offsetof(UnitStatusInfo
, control_group
) },
5557 { "DropInPaths", "as", NULL
, offsetof(UnitStatusInfo
, dropin_paths
) },
5558 { "LoadError", "(ss)", map_load_error
, offsetof(UnitStatusInfo
, load_error
) },
5559 { "Result", "s", NULL
, offsetof(UnitStatusInfo
, result
) },
5560 { "TriggeredBy", "as", NULL
, offsetof(UnitStatusInfo
, triggered_by
) },
5561 { "Triggers", "as", NULL
, offsetof(UnitStatusInfo
, triggers
) },
5562 { "InactiveExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, inactive_exit_timestamp
) },
5563 { "InactiveExitTimestampMonotonic", "t", NULL
, offsetof(UnitStatusInfo
, inactive_exit_timestamp_monotonic
) },
5564 { "ActiveEnterTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, active_enter_timestamp
) },
5565 { "ActiveExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, active_exit_timestamp
) },
5566 { "InactiveEnterTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, inactive_enter_timestamp
) },
5567 { "NeedDaemonReload", "b", NULL
, offsetof(UnitStatusInfo
, need_daemon_reload
) },
5568 { "Transient", "b", NULL
, offsetof(UnitStatusInfo
, transient
) },
5569 { "ExecMainPID", "u", NULL
, offsetof(UnitStatusInfo
, main_pid
) },
5570 { "MainPID", "u", map_main_pid
, 0 },
5571 { "ControlPID", "u", NULL
, offsetof(UnitStatusInfo
, control_pid
) },
5572 { "StatusText", "s", NULL
, offsetof(UnitStatusInfo
, status_text
) },
5573 { "PIDFile", "s", NULL
, offsetof(UnitStatusInfo
, pid_file
) },
5574 { "StatusErrno", "i", NULL
, offsetof(UnitStatusInfo
, status_errno
) },
5575 { "ExecMainStartTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, start_timestamp
) },
5576 { "ExecMainExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, exit_timestamp
) },
5577 { "ExecMainCode", "i", NULL
, offsetof(UnitStatusInfo
, exit_code
) },
5578 { "ExecMainStatus", "i", NULL
, offsetof(UnitStatusInfo
, exit_status
) },
5579 { "LogNamespace", "s", NULL
, offsetof(UnitStatusInfo
, log_namespace
) },
5580 { "ConditionTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, condition_timestamp
) },
5581 { "ConditionResult", "b", NULL
, offsetof(UnitStatusInfo
, condition_result
) },
5582 { "Conditions", "a(sbbsi)", map_conditions
, 0 },
5583 { "AssertTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, assert_timestamp
) },
5584 { "AssertResult", "b", NULL
, offsetof(UnitStatusInfo
, assert_result
) },
5585 { "Asserts", "a(sbbsi)", map_asserts
, 0 },
5586 { "NextElapseUSecRealtime", "t", NULL
, offsetof(UnitStatusInfo
, next_elapse_real
) },
5587 { "NextElapseUSecMonotonic", "t", NULL
, offsetof(UnitStatusInfo
, next_elapse_monotonic
) },
5588 { "NAccepted", "u", NULL
, offsetof(UnitStatusInfo
, n_accepted
) },
5589 { "NConnections", "u", NULL
, offsetof(UnitStatusInfo
, n_connections
) },
5590 { "NRefused", "u", NULL
, offsetof(UnitStatusInfo
, n_refused
) },
5591 { "Accept", "b", NULL
, offsetof(UnitStatusInfo
, accept
) },
5592 { "Listen", "a(ss)", map_listen
, offsetof(UnitStatusInfo
, listen
) },
5593 { "SysFSPath", "s", NULL
, offsetof(UnitStatusInfo
, sysfs_path
) },
5594 { "Where", "s", NULL
, offsetof(UnitStatusInfo
, where
) },
5595 { "What", "s", NULL
, offsetof(UnitStatusInfo
, what
) },
5596 { "MemoryCurrent", "t", NULL
, offsetof(UnitStatusInfo
, memory_current
) },
5597 { "DefaultMemoryMin", "t", NULL
, offsetof(UnitStatusInfo
, default_memory_min
) },
5598 { "DefaultMemoryLow", "t", NULL
, offsetof(UnitStatusInfo
, default_memory_low
) },
5599 { "MemoryMin", "t", NULL
, offsetof(UnitStatusInfo
, memory_min
) },
5600 { "MemoryLow", "t", NULL
, offsetof(UnitStatusInfo
, memory_low
) },
5601 { "MemoryHigh", "t", NULL
, offsetof(UnitStatusInfo
, memory_high
) },
5602 { "MemoryMax", "t", NULL
, offsetof(UnitStatusInfo
, memory_max
) },
5603 { "MemorySwapMax", "t", NULL
, offsetof(UnitStatusInfo
, memory_swap_max
) },
5604 { "MemoryLimit", "t", NULL
, offsetof(UnitStatusInfo
, memory_limit
) },
5605 { "CPUUsageNSec", "t", NULL
, offsetof(UnitStatusInfo
, cpu_usage_nsec
) },
5606 { "TasksCurrent", "t", NULL
, offsetof(UnitStatusInfo
, tasks_current
) },
5607 { "TasksMax", "t", NULL
, offsetof(UnitStatusInfo
, tasks_max
) },
5608 { "IPIngressBytes", "t", NULL
, offsetof(UnitStatusInfo
, ip_ingress_bytes
) },
5609 { "IPEgressBytes", "t", NULL
, offsetof(UnitStatusInfo
, ip_egress_bytes
) },
5610 { "IOReadBytes", "t", NULL
, offsetof(UnitStatusInfo
, io_read_bytes
) },
5611 { "IOWriteBytes", "t", NULL
, offsetof(UnitStatusInfo
, io_write_bytes
) },
5612 { "ExecCondition", "a(sasbttttuii)", map_exec
, 0 },
5613 { "ExecConditionEx", "a(sasasttttuii)", map_exec
, 0 },
5614 { "ExecStartPre", "a(sasbttttuii)", map_exec
, 0 },
5615 { "ExecStartPreEx", "a(sasasttttuii)", map_exec
, 0 },
5616 { "ExecStart", "a(sasbttttuii)", map_exec
, 0 },
5617 { "ExecStartEx", "a(sasasttttuii)", map_exec
, 0 },
5618 { "ExecStartPost", "a(sasbttttuii)", map_exec
, 0 },
5619 { "ExecStartPostEx", "a(sasasttttuii)", map_exec
, 0 },
5620 { "ExecReload", "a(sasbttttuii)", map_exec
, 0 },
5621 { "ExecReloadEx", "a(sasasttttuii)", map_exec
, 0 },
5622 { "ExecStopPre", "a(sasbttttuii)", map_exec
, 0 },
5623 { "ExecStop", "a(sasbttttuii)", map_exec
, 0 },
5624 { "ExecStopEx", "a(sasasttttuii)", map_exec
, 0 },
5625 { "ExecStopPost", "a(sasbttttuii)", map_exec
, 0 },
5626 { "ExecStopPostEx", "a(sasasttttuii)", map_exec
, 0 },
5630 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5631 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5632 _cleanup_set_free_ Set
*found_properties
= NULL
;
5633 _cleanup_(unit_status_info_free
) UnitStatusInfo info
= {
5634 .memory_current
= (uint64_t) -1,
5635 .memory_high
= CGROUP_LIMIT_MAX
,
5636 .memory_max
= CGROUP_LIMIT_MAX
,
5637 .memory_swap_max
= CGROUP_LIMIT_MAX
,
5638 .memory_limit
= (uint64_t) -1,
5639 .cpu_usage_nsec
= (uint64_t) -1,
5640 .tasks_current
= (uint64_t) -1,
5641 .tasks_max
= (uint64_t) -1,
5642 .ip_ingress_bytes
= (uint64_t) -1,
5643 .ip_egress_bytes
= (uint64_t) -1,
5644 .io_read_bytes
= UINT64_MAX
,
5645 .io_write_bytes
= UINT64_MAX
,
5653 log_debug("Showing one %s", path
);
5655 r
= bus_map_all_properties(
5657 "org.freedesktop.systemd1",
5659 show_mode
== SYSTEMCTL_SHOW_STATUS
? status_map
: property_map
,
5660 BUS_MAP_BOOLEAN_AS_BOOL
,
5665 return log_error_errno(r
, "Failed to get properties: %s", bus_error_message(&error
, r
));
5667 if (unit
&& streq_ptr(info
.load_state
, "not-found") && streq_ptr(info
.active_state
, "inactive")) {
5668 log_full(show_mode
== SYSTEMCTL_SHOW_STATUS
? LOG_ERR
: LOG_DEBUG
,
5669 "Unit %s could not be found.", unit
);
5671 if (show_mode
== SYSTEMCTL_SHOW_STATUS
)
5672 return EXIT_PROGRAM_OR_SERVICES_STATUS_UNKNOWN
;
5673 else if (show_mode
== SYSTEMCTL_SHOW_HELP
)
5682 if (show_mode
== SYSTEMCTL_SHOW_STATUS
) {
5683 print_status_info(bus
, &info
, ellipsized
);
5685 if (info
.active_state
&& !STR_IN_SET(info
.active_state
, "active", "reloading"))
5686 return EXIT_PROGRAM_NOT_RUNNING
;
5688 return EXIT_PROGRAM_RUNNING_OR_SERVICE_OK
;
5690 } else if (show_mode
== SYSTEMCTL_SHOW_HELP
) {
5691 show_unit_help(&info
);
5695 r
= sd_bus_message_rewind(reply
, true);
5697 return log_error_errno(r
, "Failed to rewind: %s", bus_error_message(&error
, r
));
5699 r
= bus_message_print_all_properties(reply
, print_property
, arg_properties
, arg_value
, arg_all
, &found_properties
);
5701 return bus_log_parse_error(r
);
5703 STRV_FOREACH(pp
, arg_properties
)
5704 if (!set_contains(found_properties
, *pp
))
5705 log_debug("Property %s does not exist.", *pp
);
5710 static int get_unit_dbus_path_by_pid(
5715 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5716 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5720 r
= sd_bus_call_method(
5722 "org.freedesktop.systemd1",
5723 "/org/freedesktop/systemd1",
5724 "org.freedesktop.systemd1.Manager",
5730 return log_error_errno(r
, "Failed to get unit for PID %"PRIu32
": %s", pid
, bus_error_message(&error
, r
));
5732 r
= sd_bus_message_read(reply
, "o", &u
);
5734 return bus_log_parse_error(r
);
5744 static int show_all(
5749 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5750 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
5755 r
= get_unit_list(bus
, NULL
, NULL
, &unit_infos
, 0, &reply
);
5759 (void) pager_open(arg_pager_flags
);
5763 typesafe_qsort(unit_infos
, c
, compare_unit_info
);
5765 for (u
= unit_infos
; u
< unit_infos
+ c
; u
++) {
5766 _cleanup_free_
char *p
= NULL
;
5768 p
= unit_dbus_path_from_name(u
->id
);
5772 r
= show_one(bus
, p
, u
->id
, SYSTEMCTL_SHOW_STATUS
, new_line
, ellipsized
);
5775 else if (r
> 0 && ret
== 0)
5782 static int show_system_status(sd_bus
*bus
) {
5783 char since1
[FORMAT_TIMESTAMP_RELATIVE_MAX
], since2
[FORMAT_TIMESTAMP_MAX
];
5784 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5785 _cleanup_(machine_info_clear
) struct machine_info mi
= {};
5786 _cleanup_free_
char *hn
= NULL
;
5787 const char *on
, *off
;
5790 hn
= gethostname_malloc();
5794 r
= bus_map_all_properties(
5796 "org.freedesktop.systemd1",
5797 "/org/freedesktop/systemd1",
5798 machine_info_property_map
,
5804 return log_error_errno(r
, "Failed to read server status: %s", bus_error_message(&error
, r
));
5806 if (streq_ptr(mi
.state
, "degraded")) {
5807 on
= ansi_highlight_red();
5808 off
= ansi_normal();
5809 } else if (streq_ptr(mi
.state
, "running")) {
5810 on
= ansi_highlight_green();
5811 off
= ansi_normal();
5813 on
= ansi_highlight_yellow();
5814 off
= ansi_normal();
5817 printf("%s%s%s %s\n", on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
, arg_host
? arg_host
: hn
);
5819 printf(" State: %s%s%s\n",
5820 on
, strna(mi
.state
), off
);
5822 printf(" Jobs: %" PRIu32
" queued\n", mi
.n_jobs
);
5823 printf(" Failed: %" PRIu32
" units\n", mi
.n_failed_units
);
5825 printf(" Since: %s; %s\n",
5826 format_timestamp(since2
, sizeof(since2
), mi
.timestamp
),
5827 format_timestamp_relative(since1
, sizeof(since1
), mi
.timestamp
));
5829 printf(" CGroup: %s\n", mi
.control_group
?: "/");
5830 if (IN_SET(arg_transport
,
5831 BUS_TRANSPORT_LOCAL
,
5832 BUS_TRANSPORT_MACHINE
)) {
5833 static const char prefix
[] = " ";
5837 if (c
> sizeof(prefix
) - 1)
5838 c
-= sizeof(prefix
) - 1;
5842 show_cgroup(SYSTEMD_CGROUP_CONTROLLER
, strempty(mi
.control_group
), prefix
, c
, get_output_flags());
5848 static int show(int argc
, char *argv
[], void *userdata
) {
5849 bool new_line
= false, ellipsized
= false;
5850 SystemctlShowMode show_mode
;
5856 show_mode
= systemctl_show_mode_from_string(argv
[0]);
5858 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
5859 "Invalid argument.");
5861 if (show_mode
== SYSTEMCTL_SHOW_HELP
&& argc
<= 1)
5862 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
5863 "'help' command expects one or more unit names.\n"
5864 "(Alternatively, help for systemctl itself may be shown with --help)");
5866 r
= acquire_bus(BUS_MANAGER
, &bus
);
5870 (void) pager_open(arg_pager_flags
);
5872 /* If no argument is specified inspect the manager itself */
5873 if (show_mode
== SYSTEMCTL_SHOW_PROPERTIES
&& argc
<= 1)
5874 return show_one(bus
, "/org/freedesktop/systemd1", NULL
, show_mode
, &new_line
, &ellipsized
);
5876 if (show_mode
== SYSTEMCTL_SHOW_STATUS
&& argc
<= 1) {
5878 show_system_status(bus
);
5882 ret
= show_all(bus
, &new_line
, &ellipsized
);
5884 _cleanup_free_
char **patterns
= NULL
;
5887 STRV_FOREACH(name
, strv_skip(argv
, 1)) {
5888 _cleanup_free_
char *path
= NULL
, *unit
= NULL
;
5891 if (safe_atou32(*name
, &id
) < 0) {
5892 if (strv_push(&patterns
, *name
) < 0)
5896 } else if (show_mode
== SYSTEMCTL_SHOW_PROPERTIES
) {
5897 /* Interpret as job id */
5898 if (asprintf(&path
, "/org/freedesktop/systemd1/job/%u", id
) < 0)
5902 /* Interpret as PID */
5903 r
= get_unit_dbus_path_by_pid(bus
, id
, &path
);
5909 r
= unit_name_from_dbus_path(path
, &unit
);
5914 r
= show_one(bus
, path
, unit
, show_mode
, &new_line
, &ellipsized
);
5917 else if (r
> 0 && ret
== 0)
5921 if (!strv_isempty(patterns
)) {
5922 _cleanup_strv_free_
char **names
= NULL
;
5924 r
= expand_names(bus
, patterns
, NULL
, &names
, NULL
);
5926 return log_error_errno(r
, "Failed to expand names: %m");
5928 r
= maybe_extend_with_unit_dependencies(bus
, &names
);
5932 STRV_FOREACH(name
, names
) {
5933 _cleanup_free_
char *path
;
5935 path
= unit_dbus_path_from_name(*name
);
5939 r
= show_one(bus
, path
, *name
, show_mode
, &new_line
, &ellipsized
);
5942 if (r
> 0 && ret
== 0)
5948 if (ellipsized
&& !arg_quiet
)
5949 printf("Hint: Some lines were ellipsized, use -l to show in full.\n");
5954 static int cat(int argc
, char *argv
[], void *userdata
) {
5955 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
5956 _cleanup_strv_free_
char **names
= NULL
;
5962 /* Include all units by default — i.e. continue as if the --all
5963 * option was used */
5964 if (strv_isempty(arg_states
))
5967 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
5968 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot remotely cat units.");
5970 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
5972 return log_error_errno(r
, "Failed to determine unit paths: %m");
5974 r
= acquire_bus(BUS_MANAGER
, &bus
);
5978 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
5980 return log_error_errno(r
, "Failed to expand names: %m");
5982 r
= maybe_extend_with_unit_dependencies(bus
, &names
);
5986 (void) pager_open(arg_pager_flags
);
5988 STRV_FOREACH(name
, names
) {
5989 _cleanup_free_
char *fragment_path
= NULL
;
5990 _cleanup_strv_free_
char **dropin_paths
= NULL
;
5992 r
= unit_find_paths(bus
, *name
, &lp
, false, &fragment_path
, &dropin_paths
);
5993 if (r
== -ERFKILL
) {
5994 printf("%s# Unit %s is masked%s.\n",
5995 ansi_highlight_magenta(),
6000 if (r
== -EKEYREJECTED
) {
6001 printf("%s# Unit %s could not be loaded.%s\n",
6002 ansi_highlight_magenta(),
6010 /* Skip units which have no on-disk counterpart, but
6011 * propagate the error to the user */
6021 if (need_daemon_reload(bus
, *name
) > 0) /* ignore errors (<0), this is informational output */
6023 "%s# Warning: %s changed on disk, the version systemd has loaded is outdated.\n"
6024 "%s# This output shows the current version of the unit's original fragment and drop-in files.\n"
6025 "%s# If fragments or drop-ins were added or removed, they are not properly reflected in this output.\n"
6026 "%s# Run 'systemctl%s daemon-reload' to reload units.%s\n",
6027 ansi_highlight_red(),
6029 ansi_highlight_red(),
6030 ansi_highlight_red(),
6031 ansi_highlight_red(),
6032 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user",
6035 r
= cat_files(fragment_path
, dropin_paths
, 0);
6043 static int set_property(int argc
, char *argv
[], void *userdata
) {
6044 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6045 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6046 _cleanup_free_
char *n
= NULL
;
6051 r
= acquire_bus(BUS_MANAGER
, &bus
);
6055 polkit_agent_open_maybe();
6057 r
= sd_bus_message_new_method_call(
6060 "org.freedesktop.systemd1",
6061 "/org/freedesktop/systemd1",
6062 "org.freedesktop.systemd1.Manager",
6063 "SetUnitProperties");
6065 return bus_log_create_error(r
);
6067 r
= unit_name_mangle(argv
[1], arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, &n
);
6069 return log_error_errno(r
, "Failed to mangle unit name: %m");
6071 t
= unit_name_to_type(n
);
6073 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid unit type: %s", n
);
6075 r
= sd_bus_message_append(m
, "sb", n
, arg_runtime
);
6077 return bus_log_create_error(r
);
6079 r
= sd_bus_message_open_container(m
, SD_BUS_TYPE_ARRAY
, "(sv)");
6081 return bus_log_create_error(r
);
6083 r
= bus_append_unit_property_assignment_many(m
, t
, strv_skip(argv
, 2));
6087 r
= sd_bus_message_close_container(m
);
6089 return bus_log_create_error(r
);
6091 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6093 return log_error_errno(r
, "Failed to set unit properties on %s: %s", n
, bus_error_message(&error
, r
));
6098 static int daemon_reload(int argc
, char *argv
[], void *userdata
) {
6099 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6100 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6105 r
= acquire_bus(BUS_MANAGER
, &bus
);
6109 polkit_agent_open_maybe();
6111 switch (arg_action
) {
6118 method
= "Reexecute";
6121 case ACTION_SYSTEMCTL
:
6122 method
= streq(argv
[0], "daemon-reexec") ? "Reexecute" :
6123 /* "daemon-reload" */ "Reload";
6127 assert_not_reached("Unexpected action");
6130 r
= sd_bus_message_new_method_call(
6133 "org.freedesktop.systemd1",
6134 "/org/freedesktop/systemd1",
6135 "org.freedesktop.systemd1.Manager",
6138 return bus_log_create_error(r
);
6140 /* Note we use an extra-long timeout here. This is because a reload or reexec means generators are rerun which
6141 * are timed out after DEFAULT_TIMEOUT_USEC. Let's use twice that time here, so that the generators can have
6142 * their timeout, and for everything else there's the same time budget in place. */
6144 r
= sd_bus_call(bus
, m
, DEFAULT_TIMEOUT_USEC
* 2, &error
, NULL
);
6146 /* On reexecution, we expect a disconnect, not a reply */
6147 if (IN_SET(r
, -ETIMEDOUT
, -ECONNRESET
) && streq(method
, "Reexecute"))
6150 if (r
< 0 && arg_action
== ACTION_SYSTEMCTL
)
6151 return log_error_errno(r
, "Failed to reload daemon: %s", bus_error_message(&error
, r
));
6153 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
6154 * old ways of doing things, hence don't log any error in that case here. */
6156 return r
< 0 ? r
: 0;
6159 static int trivial_method(int argc
, char *argv
[], void *userdata
) {
6160 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6168 r
= acquire_bus(BUS_MANAGER
, &bus
);
6172 polkit_agent_open_maybe();
6175 streq(argv
[0], "clear-jobs") ||
6176 streq(argv
[0], "cancel") ? "ClearJobs" :
6177 streq(argv
[0], "reset-failed") ? "ResetFailed" :
6178 streq(argv
[0], "halt") ? "Halt" :
6179 streq(argv
[0], "reboot") ? "Reboot" :
6180 streq(argv
[0], "kexec") ? "KExec" :
6181 streq(argv
[0], "exit") ? "Exit" :
6182 /* poweroff */ "PowerOff";
6184 r
= sd_bus_call_method(
6186 "org.freedesktop.systemd1",
6187 "/org/freedesktop/systemd1",
6188 "org.freedesktop.systemd1.Manager",
6193 if (r
< 0 && arg_action
== ACTION_SYSTEMCTL
)
6194 return log_error_errno(r
, "Failed to execute operation: %s", bus_error_message(&error
, r
));
6196 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
6197 * old ways of doing things, hence don't log any error in that case here. */
6199 return r
< 0 ? r
: 0;
6202 static int reset_failed(int argc
, char *argv
[], void *userdata
) {
6203 _cleanup_strv_free_
char **names
= NULL
;
6209 return trivial_method(argc
, argv
, userdata
);
6211 r
= acquire_bus(BUS_MANAGER
, &bus
);
6215 polkit_agent_open_maybe();
6217 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
6219 return log_error_errno(r
, "Failed to expand names: %m");
6221 STRV_FOREACH(name
, names
) {
6222 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6224 q
= sd_bus_call_method(
6226 "org.freedesktop.systemd1",
6227 "/org/freedesktop/systemd1",
6228 "org.freedesktop.systemd1.Manager",
6234 log_error_errno(q
, "Failed to reset failed state of unit %s: %s", *name
, bus_error_message(&error
, q
));
6243 static int print_variable(const char *s
) {
6245 _cleanup_free_
char *esc
= NULL
;
6247 sep
= strchr(s
, '=');
6249 return log_error_errno(SYNTHETIC_ERRNO(EUCLEAN
),
6250 "Invalid environment block");
6252 esc
= shell_maybe_quote(sep
+ 1, ESCAPE_POSIX
);
6256 printf("%.*s=%s\n", (int)(sep
-s
), s
, esc
);
6260 static int show_environment(int argc
, char *argv
[], void *userdata
) {
6261 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6262 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
6267 r
= acquire_bus(BUS_MANAGER
, &bus
);
6271 (void) pager_open(arg_pager_flags
);
6273 r
= sd_bus_get_property(
6275 "org.freedesktop.systemd1",
6276 "/org/freedesktop/systemd1",
6277 "org.freedesktop.systemd1.Manager",
6283 return log_error_errno(r
, "Failed to get environment: %s", bus_error_message(&error
, r
));
6285 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "s");
6287 return bus_log_parse_error(r
);
6289 while ((r
= sd_bus_message_read_basic(reply
, SD_BUS_TYPE_STRING
, &text
)) > 0) {
6290 r
= print_variable(text
);
6295 return bus_log_parse_error(r
);
6297 r
= sd_bus_message_exit_container(reply
);
6299 return bus_log_parse_error(r
);
6304 static int switch_root(int argc
, char *argv
[], void *userdata
) {
6305 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6306 _cleanup_free_
char *cmdline_init
= NULL
;
6307 const char *root
, *init
;
6311 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
6312 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot switch root remotely.");
6314 if (argc
< 2 || argc
> 3)
6315 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Wrong number of arguments.");
6322 r
= proc_cmdline_get_key("init", 0, &cmdline_init
);
6324 log_debug_errno(r
, "Failed to parse /proc/cmdline: %m");
6326 init
= cmdline_init
;
6329 init
= empty_to_null(init
);
6331 const char *root_systemd_path
= NULL
, *root_init_path
= NULL
;
6333 root_systemd_path
= prefix_roota(root
, "/" SYSTEMD_BINARY_PATH
);
6334 root_init_path
= prefix_roota(root
, init
);
6336 /* If the passed init is actually the same as the
6337 * systemd binary, then let's suppress it. */
6338 if (files_same(root_init_path
, root_systemd_path
, 0) > 0)
6342 /* Instruct PID1 to exclude us from its killing spree applied during the transition. Otherwise we
6343 * would exit with a failure status even though the switch to the new root has succeed. */
6345 assert(saved_argv
[0]);
6346 saved_argv
[0][0] = '@';
6348 r
= acquire_bus(BUS_MANAGER
, &bus
);
6352 /* If we are slow to exit after the root switch, the new systemd instance
6353 * will send us a signal to terminate. Just ignore it and exit normally.
6354 * This way the unit does not end up as failed.
6356 r
= ignore_signals(SIGTERM
, -1);
6358 log_warning_errno(r
, "Failed to change disposition of SIGTERM to ignore: %m");
6360 log_debug("Switching root - root: %s; init: %s", root
, strna(init
));
6362 r
= sd_bus_call_method(
6364 "org.freedesktop.systemd1",
6365 "/org/freedesktop/systemd1",
6366 "org.freedesktop.systemd1.Manager",
6372 (void) default_signals(SIGTERM
, -1);
6374 return log_error_errno(r
, "Failed to switch root: %s", bus_error_message(&error
, r
));
6380 static int log_level(int argc
, char *argv
[], void *userdata
) {
6382 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6385 r
= acquire_bus(BUS_MANAGER
, &bus
);
6390 _cleanup_free_
char *level
= NULL
;
6392 r
= sd_bus_get_property_string(
6394 "org.freedesktop.systemd1",
6395 "/org/freedesktop/systemd1",
6396 "org.freedesktop.systemd1.Manager",
6401 return log_error_errno(r
, "Failed to get log level: %s", bus_error_message(&error
, r
));
6408 r
= sd_bus_set_property(
6410 "org.freedesktop.systemd1",
6411 "/org/freedesktop/systemd1",
6412 "org.freedesktop.systemd1.Manager",
6418 return log_error_errno(r
, "Failed to set log level: %s", bus_error_message(&error
, r
));
6424 static int log_target(int argc
, char *argv
[], void *userdata
) {
6426 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6429 r
= acquire_bus(BUS_MANAGER
, &bus
);
6434 _cleanup_free_
char *target
= NULL
;
6436 r
= sd_bus_get_property_string(
6438 "org.freedesktop.systemd1",
6439 "/org/freedesktop/systemd1",
6440 "org.freedesktop.systemd1.Manager",
6445 return log_error_errno(r
, "Failed to get log target: %s", bus_error_message(&error
, r
));
6452 r
= sd_bus_set_property(
6454 "org.freedesktop.systemd1",
6455 "/org/freedesktop/systemd1",
6456 "org.freedesktop.systemd1.Manager",
6462 return log_error_errno(r
, "Failed to set log target: %s", bus_error_message(&error
, r
));
6468 static int service_watchdogs(int argc
, char *argv
[], void *userdata
) {
6470 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6475 r
= acquire_bus(BUS_MANAGER
, &bus
);
6480 /* get ServiceWatchdogs */
6481 r
= sd_bus_get_property_trivial(
6483 "org.freedesktop.systemd1",
6484 "/org/freedesktop/systemd1",
6485 "org.freedesktop.systemd1.Manager",
6491 return log_error_errno(r
, "Failed to get service-watchdog state: %s", bus_error_message(&error
, r
));
6493 printf("%s\n", yes_no(!!b
));
6496 /* set ServiceWatchdogs */
6499 b
= parse_boolean(argv
[1]);
6501 return log_error_errno(b
, "Failed to parse service-watchdogs argument: %m");
6503 r
= sd_bus_set_property(
6505 "org.freedesktop.systemd1",
6506 "/org/freedesktop/systemd1",
6507 "org.freedesktop.systemd1.Manager",
6513 return log_error_errno(r
, "Failed to set service-watchdog state: %s", bus_error_message(&error
, r
));
6519 static int set_environment(int argc
, char *argv
[], void *userdata
) {
6520 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6521 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6529 r
= acquire_bus(BUS_MANAGER
, &bus
);
6533 polkit_agent_open_maybe();
6535 method
= streq(argv
[0], "set-environment")
6537 : "UnsetEnvironment";
6539 r
= sd_bus_message_new_method_call(
6542 "org.freedesktop.systemd1",
6543 "/org/freedesktop/systemd1",
6544 "org.freedesktop.systemd1.Manager",
6547 return bus_log_create_error(r
);
6549 r
= sd_bus_message_append_strv(m
, strv_skip(argv
, 1));
6551 return bus_log_create_error(r
);
6553 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6555 return log_error_errno(r
, "Failed to set environment: %s", bus_error_message(&error
, r
));
6560 static int import_environment(int argc
, char *argv
[], void *userdata
) {
6561 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6562 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6566 r
= acquire_bus(BUS_MANAGER
, &bus
);
6570 polkit_agent_open_maybe();
6572 r
= sd_bus_message_new_method_call(
6575 "org.freedesktop.systemd1",
6576 "/org/freedesktop/systemd1",
6577 "org.freedesktop.systemd1.Manager",
6580 return bus_log_create_error(r
);
6583 r
= sd_bus_message_append_strv(m
, environ
);
6587 r
= sd_bus_message_open_container(m
, 'a', "s");
6589 return bus_log_create_error(r
);
6591 STRV_FOREACH(a
, strv_skip(argv
, 1)) {
6593 if (!env_name_is_valid(*a
))
6594 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Not a valid environment variable name: %s", *a
);
6596 STRV_FOREACH(b
, environ
) {
6599 eq
= startswith(*b
, *a
);
6600 if (eq
&& *eq
== '=') {
6602 r
= sd_bus_message_append(m
, "s", *b
);
6604 return bus_log_create_error(r
);
6611 r
= sd_bus_message_close_container(m
);
6614 return bus_log_create_error(r
);
6616 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6618 return log_error_errno(r
, "Failed to import environment: %s", bus_error_message(&error
, r
));
6623 static int enable_sysv_units(const char *verb
, char **args
) {
6626 #if HAVE_SYSV_COMPAT
6627 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
6630 /* Processes all SysV units, and reshuffles the array so that afterwards only the native units remain */
6632 if (arg_scope
!= UNIT_FILE_SYSTEM
)
6635 if (getenv_bool("SYSTEMCTL_SKIP_SYSV") > 0)
6638 if (!STR_IN_SET(verb
,
6644 r
= lookup_paths_init(&paths
, arg_scope
, LOOKUP_PATHS_EXCLUDE_GENERATED
, arg_root
);
6651 const char *argv
[] = {
6652 ROOTLIBEXECDIR
"/systemd-sysv-install",
6659 _cleanup_free_
char *p
= NULL
, *q
= NULL
, *l
= NULL
, *v
= NULL
;
6660 bool found_native
= false, found_sysv
;
6668 if (!endswith(name
, ".service"))
6671 if (path_is_absolute(name
))
6674 j
= unit_file_exists(arg_scope
, &paths
, name
);
6675 if (j
< 0 && !IN_SET(j
, -ELOOP
, -ERFKILL
, -EADDRNOTAVAIL
))
6676 return log_error_errno(j
, "Failed to look up unit file state: %m");
6677 found_native
= j
!= 0;
6679 /* If we have both a native unit and a SysV script, enable/disable them both (below); for is-enabled,
6680 * prefer the native unit */
6681 if (found_native
&& streq(verb
, "is-enabled"))
6684 p
= path_join(arg_root
, SYSTEM_SYSVINIT_PATH
, name
);
6688 p
[strlen(p
) - STRLEN(".service")] = 0;
6689 found_sysv
= access(p
, F_OK
) >= 0;
6695 log_info("Synchronizing state of %s with SysV service script with %s.", name
, argv
[0]);
6697 log_info("%s is not a native service, redirecting to systemd-sysv-install.", name
);
6700 if (!isempty(arg_root
)) {
6701 q
= strjoin("--root=", arg_root
);
6708 /* Let's copy the verb, since it's still pointing directly into the original argv[] array we
6709 * got passed, but safe_fork() is likely going to rewrite that for the new child */
6715 argv
[c
++] = basename(p
);
6718 l
= strv_join((char**)argv
, " ");
6723 log_info("Executing: %s", l
);
6725 j
= safe_fork("(sysv-install)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
, &pid
);
6730 execv(argv
[0], (char**) argv
);
6731 log_error_errno(errno
, "Failed to execute %s: %m", argv
[0]);
6732 _exit(EXIT_FAILURE
);
6735 j
= wait_for_terminate_and_check("sysv-install", pid
, WAIT_LOG_ABNORMAL
);
6738 if (streq(verb
, "is-enabled")) {
6739 if (j
== EXIT_SUCCESS
) {
6748 } else if (j
!= EXIT_SUCCESS
)
6749 return -EBADE
; /* We don't warn here, under the assumption the script already showed an explanation */
6754 /* Remove this entry, so that we don't try enabling it as native unit */
6757 assert(args
[f
] == name
);
6758 strv_remove(args
+ f
, name
);
6765 static int mangle_names(const char *operation
, char **original_names
, char ***mangled_names
) {
6766 char **i
, **l
, **name
;
6769 l
= i
= new(char*, strv_length(original_names
) + 1);
6773 STRV_FOREACH(name
, original_names
) {
6775 /* When enabling units qualified path names are OK,
6776 * too, hence allow them explicitly. */
6778 if (is_path(*name
)) {
6785 r
= unit_name_mangle_with_suffix(*name
, operation
,
6786 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
6791 return log_error_errno(r
, "Failed to mangle unit name: %m");
6804 static int normalize_filenames(char **names
) {
6808 STRV_FOREACH(u
, names
)
6809 if (!path_is_absolute(*u
)) {
6810 char* normalized_path
;
6812 if (!isempty(arg_root
))
6813 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6814 "Non-absolute paths are not allowed when --root is used: %s",
6817 if (!strchr(*u
,'/'))
6818 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6819 "Link argument does contain at least one directory separator: %s",
6822 r
= path_make_absolute_cwd(*u
, &normalized_path
);
6826 free_and_replace(*u
, normalized_path
);
6832 static int normalize_names(char **names
, bool warn_if_path
) {
6834 bool was_path
= false;
6836 STRV_FOREACH(u
, names
) {
6842 r
= free_and_strdup(u
, basename(*u
));
6844 return log_error_errno(r
, "Failed to normalize unit file path: %m");
6849 if (warn_if_path
&& was_path
)
6850 log_warning("Warning: Can't execute disable on the unit file path. Proceeding with the unit name.");
6855 static int unit_exists(LookupPaths
*lp
, const char *unit
) {
6856 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6857 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6858 _cleanup_free_
char *path
= NULL
;
6859 static const struct bus_properties_map property_map
[] = {
6860 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
6861 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
)},
6864 UnitStatusInfo info
= {};
6868 if (unit_name_is_valid(unit
, UNIT_NAME_TEMPLATE
))
6869 return unit_find_template_path(unit
, lp
, NULL
, NULL
);
6871 path
= unit_dbus_path_from_name(unit
);
6875 r
= acquire_bus(BUS_MANAGER
, &bus
);
6879 r
= bus_map_all_properties(bus
, "org.freedesktop.systemd1", path
, property_map
, 0, &error
, &m
, &info
);
6881 return log_error_errno(r
, "Failed to get properties: %s", bus_error_message(&error
, r
));
6883 return !streq_ptr(info
.load_state
, "not-found") || !streq_ptr(info
.active_state
, "inactive");
6886 static int enable_unit(int argc
, char *argv
[], void *userdata
) {
6887 _cleanup_strv_free_
char **names
= NULL
;
6888 const char *verb
= argv
[0];
6889 UnitFileChange
*changes
= NULL
;
6890 size_t n_changes
= 0;
6891 int carries_install_info
= -1;
6892 bool ignore_carries_install_info
= arg_quiet
;
6898 r
= mangle_names("to enable", strv_skip(argv
, 1), &names
);
6902 r
= enable_sysv_units(verb
, names
);
6906 /* If the operation was fully executed by the SysV compat, let's finish early */
6907 if (strv_isempty(names
)) {
6908 if (arg_no_reload
|| install_client_side())
6910 return daemon_reload(argc
, argv
, userdata
);
6913 if (streq(verb
, "disable")) {
6914 r
= normalize_names(names
, true);
6919 if (streq(verb
, "link")) {
6920 r
= normalize_filenames(names
);
6925 if (install_client_side()) {
6926 UnitFileFlags flags
;
6928 flags
= args_to_flags();
6929 if (streq(verb
, "enable")) {
6930 r
= unit_file_enable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6931 carries_install_info
= r
;
6932 } else if (streq(verb
, "disable"))
6933 r
= unit_file_disable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6934 else if (streq(verb
, "reenable")) {
6935 r
= unit_file_reenable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6936 carries_install_info
= r
;
6937 } else if (streq(verb
, "link"))
6938 r
= unit_file_link(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6939 else if (streq(verb
, "preset")) {
6940 r
= unit_file_preset(arg_scope
, flags
, arg_root
, names
, arg_preset_mode
, &changes
, &n_changes
);
6941 } else if (streq(verb
, "mask"))
6942 r
= unit_file_mask(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6943 else if (streq(verb
, "unmask"))
6944 r
= unit_file_unmask(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6945 else if (streq(verb
, "revert"))
6946 r
= unit_file_revert(arg_scope
, arg_root
, names
, &changes
, &n_changes
);
6948 assert_not_reached("Unknown verb");
6950 unit_file_dump_changes(r
, verb
, changes
, n_changes
, arg_quiet
);
6955 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
, *m
= NULL
;
6956 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6957 bool expect_carries_install_info
= false;
6958 bool send_runtime
= true, send_force
= true, send_preset_mode
= false;
6962 if (STR_IN_SET(verb
, "mask", "unmask")) {
6964 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
6966 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
6970 STRV_FOREACH(name
, names
) {
6971 r
= unit_exists(&lp
, *name
);
6975 log_notice("Unit %s does not exist, proceeding anyway.", *name
);
6979 r
= acquire_bus(BUS_MANAGER
, &bus
);
6983 polkit_agent_open_maybe();
6985 if (streq(verb
, "enable")) {
6986 method
= "EnableUnitFiles";
6987 expect_carries_install_info
= true;
6988 } else if (streq(verb
, "disable")) {
6989 method
= "DisableUnitFiles";
6991 } else if (streq(verb
, "reenable")) {
6992 method
= "ReenableUnitFiles";
6993 expect_carries_install_info
= true;
6994 } else if (streq(verb
, "link"))
6995 method
= "LinkUnitFiles";
6996 else if (streq(verb
, "preset")) {
6998 if (arg_preset_mode
!= UNIT_FILE_PRESET_FULL
) {
6999 method
= "PresetUnitFilesWithMode";
7000 send_preset_mode
= true;
7002 method
= "PresetUnitFiles";
7004 expect_carries_install_info
= true;
7005 ignore_carries_install_info
= true;
7006 } else if (streq(verb
, "mask"))
7007 method
= "MaskUnitFiles";
7008 else if (streq(verb
, "unmask")) {
7009 method
= "UnmaskUnitFiles";
7011 } else if (streq(verb
, "revert")) {
7012 method
= "RevertUnitFiles";
7013 send_runtime
= send_force
= false;
7015 assert_not_reached("Unknown verb");
7017 r
= sd_bus_message_new_method_call(
7020 "org.freedesktop.systemd1",
7021 "/org/freedesktop/systemd1",
7022 "org.freedesktop.systemd1.Manager",
7025 return bus_log_create_error(r
);
7027 r
= sd_bus_message_append_strv(m
, names
);
7029 return bus_log_create_error(r
);
7031 if (send_preset_mode
) {
7032 r
= sd_bus_message_append(m
, "s", unit_file_preset_mode_to_string(arg_preset_mode
));
7034 return bus_log_create_error(r
);
7038 r
= sd_bus_message_append(m
, "b", arg_runtime
);
7040 return bus_log_create_error(r
);
7044 r
= sd_bus_message_append(m
, "b", arg_force
);
7046 return bus_log_create_error(r
);
7049 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
7051 return log_error_errno(r
, "Failed to %s unit: %s", verb
, bus_error_message(&error
, r
));
7053 if (expect_carries_install_info
) {
7054 r
= sd_bus_message_read(reply
, "b", &carries_install_info
);
7056 return bus_log_parse_error(r
);
7059 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
7063 /* Try to reload if enabled */
7065 r
= daemon_reload(argc
, argv
, userdata
);
7070 if (carries_install_info
== 0 && !ignore_carries_install_info
)
7071 log_notice("The unit files have no installation config (WantedBy=, RequiredBy=, Also=,\n"
7072 "Alias= settings in the [Install] section, and DefaultInstance= for template\n"
7073 "units). This means they are not meant to be enabled using systemctl.\n"
7074 " \n" /* trick: the space is needed so that the line does not get stripped from output */
7075 "Possible reasons for having this kind of units are:\n"
7076 "%1$s A unit may be statically enabled by being symlinked from another unit's\n"
7077 " .wants/ or .requires/ directory.\n"
7078 "%1$s A unit's purpose may be to act as a helper for some other unit which has\n"
7079 " a requirement dependency on it.\n"
7080 "%1$s A unit may be started when needed via activation (socket, path, timer,\n"
7081 " D-Bus, udev, scripted systemctl call, ...).\n"
7082 "%1$s In case of template units, the unit is meant to be enabled with some\n"
7083 " instance name specified.",
7084 special_glyph(SPECIAL_GLYPH_BULLET
));
7086 if (arg_now
&& STR_IN_SET(argv
[0], "enable", "disable", "mask")) {
7090 r
= acquire_bus(BUS_MANAGER
, &bus
);
7094 len
= strv_length(names
);
7096 char *new_args
[len
+ 2];
7098 new_args
[0] = (char*) (streq(argv
[0], "enable") ? "start" : "stop");
7099 for (i
= 0; i
< len
; i
++)
7100 new_args
[i
+ 1] = basename(names
[i
]);
7101 new_args
[i
+ 1] = NULL
;
7103 r
= start_unit(len
+ 1, new_args
, userdata
);
7108 unit_file_changes_free(changes
, n_changes
);
7113 static int add_dependency(int argc
, char *argv
[], void *userdata
) {
7114 _cleanup_strv_free_
char **names
= NULL
;
7115 _cleanup_free_
char *target
= NULL
;
7116 const char *verb
= argv
[0];
7117 UnitFileChange
*changes
= NULL
;
7118 size_t n_changes
= 0;
7125 r
= unit_name_mangle_with_suffix(argv
[1], "as target",
7126 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
7127 ".target", &target
);
7129 return log_error_errno(r
, "Failed to mangle unit name: %m");
7131 r
= mangle_names("as dependency", strv_skip(argv
, 2), &names
);
7135 if (streq(verb
, "add-wants"))
7137 else if (streq(verb
, "add-requires"))
7138 dep
= UNIT_REQUIRES
;
7140 assert_not_reached("Unknown verb");
7142 if (install_client_side()) {
7143 r
= unit_file_add_dependency(arg_scope
, args_to_flags(), arg_root
, names
, target
, dep
, &changes
, &n_changes
);
7144 unit_file_dump_changes(r
, "add dependency on", changes
, n_changes
, arg_quiet
);
7149 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
, *m
= NULL
;
7150 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7153 r
= acquire_bus(BUS_MANAGER
, &bus
);
7157 polkit_agent_open_maybe();
7159 r
= sd_bus_message_new_method_call(
7162 "org.freedesktop.systemd1",
7163 "/org/freedesktop/systemd1",
7164 "org.freedesktop.systemd1.Manager",
7165 "AddDependencyUnitFiles");
7167 return bus_log_create_error(r
);
7169 r
= sd_bus_message_append_strv(m
, names
);
7171 return bus_log_create_error(r
);
7173 r
= sd_bus_message_append(m
, "ssbb", target
, unit_dependency_to_string(dep
), arg_runtime
, arg_force
);
7175 return bus_log_create_error(r
);
7177 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
7179 return log_error_errno(r
, "Failed to add dependency: %s", bus_error_message(&error
, r
));
7181 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
7185 if (arg_no_reload
) {
7190 r
= daemon_reload(argc
, argv
, userdata
);
7194 unit_file_changes_free(changes
, n_changes
);
7199 static int preset_all(int argc
, char *argv
[], void *userdata
) {
7200 UnitFileChange
*changes
= NULL
;
7201 size_t n_changes
= 0;
7204 if (install_client_side()) {
7205 r
= unit_file_preset_all(arg_scope
, args_to_flags(), arg_root
, arg_preset_mode
, &changes
, &n_changes
);
7206 unit_file_dump_changes(r
, "preset", changes
, n_changes
, arg_quiet
);
7211 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7212 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7215 r
= acquire_bus(BUS_MANAGER
, &bus
);
7219 polkit_agent_open_maybe();
7221 r
= sd_bus_call_method(
7223 "org.freedesktop.systemd1",
7224 "/org/freedesktop/systemd1",
7225 "org.freedesktop.systemd1.Manager",
7226 "PresetAllUnitFiles",
7230 unit_file_preset_mode_to_string(arg_preset_mode
),
7234 return log_error_errno(r
, "Failed to preset all units: %s", bus_error_message(&error
, r
));
7236 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
7240 if (arg_no_reload
) {
7245 r
= daemon_reload(argc
, argv
, userdata
);
7249 unit_file_changes_free(changes
, n_changes
);
7254 static int show_installation_targets_client_side(const char *name
) {
7255 UnitFileChange
*changes
= NULL
;
7256 size_t n_changes
= 0, i
;
7257 UnitFileFlags flags
;
7261 p
= STRV_MAKE(name
);
7262 flags
= UNIT_FILE_DRY_RUN
|
7263 (arg_runtime
? UNIT_FILE_RUNTIME
: 0);
7265 r
= unit_file_disable(UNIT_FILE_SYSTEM
, flags
, NULL
, p
, &changes
, &n_changes
);
7267 return log_error_errno(r
, "Failed to get file links for %s: %m", name
);
7269 for (i
= 0; i
< n_changes
; i
++)
7270 if (changes
[i
].type
== UNIT_FILE_UNLINK
)
7271 printf(" %s\n", changes
[i
].path
);
7276 static int show_installation_targets(sd_bus
*bus
, const char *name
) {
7277 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7278 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7282 r
= sd_bus_call_method(
7284 "org.freedesktop.systemd1",
7285 "/org/freedesktop/systemd1",
7286 "org.freedesktop.systemd1.Manager",
7290 "sb", name
, arg_runtime
);
7292 return log_error_errno(r
, "Failed to get unit file links for %s: %s", name
, bus_error_message(&error
, r
));
7294 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "s");
7296 return bus_log_parse_error(r
);
7298 while ((r
= sd_bus_message_read(reply
, "s", &link
)) > 0)
7299 printf(" %s\n", link
);
7302 return bus_log_parse_error(r
);
7304 r
= sd_bus_message_exit_container(reply
);
7306 return bus_log_parse_error(r
);
7311 static int unit_is_enabled(int argc
, char *argv
[], void *userdata
) {
7312 _cleanup_strv_free_
char **names
= NULL
;
7317 r
= mangle_names("to check", strv_skip(argv
, 1), &names
);
7321 r
= enable_sysv_units(argv
[0], names
);
7327 if (install_client_side()) {
7328 STRV_FOREACH(name
, names
) {
7329 UnitFileState state
;
7331 r
= unit_file_get_state(arg_scope
, arg_root
, *name
, &state
);
7333 return log_error_errno(r
, "Failed to get unit file state for %s: %m", *name
);
7337 UNIT_FILE_ENABLED_RUNTIME
,
7340 UNIT_FILE_GENERATED
))
7344 puts(unit_file_state_to_string(state
));
7346 r
= show_installation_targets_client_side(*name
);
7355 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7358 r
= acquire_bus(BUS_MANAGER
, &bus
);
7362 STRV_FOREACH(name
, names
) {
7363 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7366 r
= sd_bus_call_method(
7368 "org.freedesktop.systemd1",
7369 "/org/freedesktop/systemd1",
7370 "org.freedesktop.systemd1.Manager",
7376 return log_error_errno(r
, "Failed to get unit file state for %s: %s", *name
, bus_error_message(&error
, r
));
7378 r
= sd_bus_message_read(reply
, "s", &s
);
7380 return bus_log_parse_error(r
);
7382 if (STR_IN_SET(s
, "enabled", "enabled-runtime", "static", "indirect", "generated"))
7388 r
= show_installation_targets(bus
, *name
);
7396 return enabled
? EXIT_SUCCESS
: EXIT_FAILURE
;
7399 static int match_startup_finished(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
7400 char **state
= userdata
;
7405 r
= sd_bus_get_property_string(
7406 sd_bus_message_get_bus(m
),
7407 "org.freedesktop.systemd1",
7408 "/org/freedesktop/systemd1",
7409 "org.freedesktop.systemd1.Manager",
7414 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m
)), r
);
7418 static int is_system_running(int argc
, char *argv
[], void *userdata
) {
7419 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7420 _cleanup_(sd_bus_slot_unrefp
) sd_bus_slot
*slot_startup_finished
= NULL
;
7421 _cleanup_(sd_event_unrefp
) sd_event
* event
= NULL
;
7422 _cleanup_free_
char *state
= NULL
;
7426 if (running_in_chroot() > 0 || (arg_transport
== BUS_TRANSPORT_LOCAL
&& !sd_booted())) {
7429 return EXIT_FAILURE
;
7432 r
= acquire_bus(BUS_MANAGER
, &bus
);
7437 r
= sd_event_default(&event
);
7439 r
= sd_bus_attach_event(bus
, event
, 0);
7441 r
= sd_bus_match_signal_async(
7443 &slot_startup_finished
,
7444 "org.freedesktop.systemd1",
7445 "/org/freedesktop/systemd1",
7446 "org.freedesktop.systemd1.Manager",
7448 match_startup_finished
, NULL
, &state
);
7450 log_warning_errno(r
, "Failed to request match for StartupFinished: %m");
7455 r
= sd_bus_get_property_string(
7457 "org.freedesktop.systemd1",
7458 "/org/freedesktop/systemd1",
7459 "org.freedesktop.systemd1.Manager",
7464 log_warning_errno(r
, "Failed to query system state: %s", bus_error_message(&error
, r
));
7468 return EXIT_FAILURE
;
7471 if (arg_wait
&& STR_IN_SET(state
, "initializing", "starting")) {
7472 r
= sd_event_loop(event
);
7474 log_warning_errno(r
, "Failed to get property from event loop: %m");
7477 return EXIT_FAILURE
;
7484 return streq(state
, "running") ? EXIT_SUCCESS
: EXIT_FAILURE
;
7487 static int create_edit_temp_file(const char *new_path
, const char *original_path
, char **ret_tmp_fn
) {
7488 _cleanup_free_
char *t
= NULL
;
7492 assert(original_path
);
7495 r
= tempfn_random(new_path
, NULL
, &t
);
7497 return log_error_errno(r
, "Failed to determine temporary filename for \"%s\": %m", new_path
);
7499 r
= mkdir_parents(new_path
, 0755);
7501 return log_error_errno(r
, "Failed to create directories for \"%s\": %m", new_path
);
7503 r
= copy_file(original_path
, t
, 0, 0644, 0, 0, COPY_REFLINK
);
7508 return log_error_errno(r
, "Failed to create temporary file \"%s\": %m", t
);
7511 return log_error_errno(r
, "Failed to create temporary file for \"%s\": %m", new_path
);
7513 *ret_tmp_fn
= TAKE_PTR(t
);
7518 static int get_file_to_edit(
7519 const LookupPaths
*paths
,
7523 _cleanup_free_
char *path
= NULL
, *run
= NULL
;
7528 path
= path_join(paths
->persistent_config
, name
);
7533 run
= path_join(paths
->runtime_config
, name
);
7539 if (access(path
, F_OK
) >= 0)
7540 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
7541 "Refusing to create \"%s\" because it would be overridden by \"%s\" anyway.",
7544 *ret_path
= TAKE_PTR(run
);
7546 *ret_path
= TAKE_PTR(path
);
7551 static int unit_file_create_new(
7552 const LookupPaths
*paths
,
7553 const char *unit_name
,
7555 char **ret_new_path
,
7556 char **ret_tmp_path
) {
7558 _cleanup_free_
char *new_path
= NULL
, *tmp_path
= NULL
;
7563 assert(ret_new_path
);
7564 assert(ret_tmp_path
);
7566 ending
= strjoina(unit_name
, suffix
);
7567 r
= get_file_to_edit(paths
, ending
, &new_path
);
7571 r
= create_edit_temp_file(new_path
, new_path
, &tmp_path
);
7575 *ret_new_path
= TAKE_PTR(new_path
);
7576 *ret_tmp_path
= TAKE_PTR(tmp_path
);
7581 static int unit_file_create_copy(
7582 const LookupPaths
*paths
,
7583 const char *unit_name
,
7584 const char *fragment_path
,
7585 char **ret_new_path
,
7586 char **ret_tmp_path
) {
7588 _cleanup_free_
char *new_path
= NULL
, *tmp_path
= NULL
;
7591 assert(fragment_path
);
7593 assert(ret_new_path
);
7594 assert(ret_tmp_path
);
7596 r
= get_file_to_edit(paths
, unit_name
, &new_path
);
7600 if (!path_equal(fragment_path
, new_path
) && access(new_path
, F_OK
) >= 0) {
7603 r
= ask_char(&response
, "yn", "\"%s\" already exists. Overwrite with \"%s\"? [(y)es, (n)o] ", new_path
, fragment_path
);
7606 if (response
!= 'y')
7607 return log_warning_errno(SYNTHETIC_ERRNO(EKEYREJECTED
), "%s skipped.", unit_name
);
7610 r
= create_edit_temp_file(new_path
, fragment_path
, &tmp_path
);
7614 *ret_new_path
= TAKE_PTR(new_path
);
7615 *ret_tmp_path
= TAKE_PTR(tmp_path
);
7620 static int run_editor(char **paths
) {
7625 r
= safe_fork("(editor)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
|FORK_WAIT
, NULL
);
7629 char **editor_args
= NULL
, **tmp_path
, **original_path
;
7630 size_t n_editor_args
= 0, i
= 1, argc
;
7631 const char **args
, *editor
, *p
;
7633 argc
= strv_length(paths
)/2 + 1;
7635 /* SYSTEMD_EDITOR takes precedence over EDITOR which takes precedence over VISUAL
7636 * If neither SYSTEMD_EDITOR nor EDITOR nor VISUAL are present,
7637 * we try to execute well known editors
7639 editor
= getenv("SYSTEMD_EDITOR");
7641 editor
= getenv("EDITOR");
7643 editor
= getenv("VISUAL");
7645 if (!isempty(editor
)) {
7646 editor_args
= strv_split(editor
, WHITESPACE
);
7649 _exit(EXIT_FAILURE
);
7651 n_editor_args
= strv_length(editor_args
);
7652 argc
+= n_editor_args
- 1;
7655 args
= newa(const char*, argc
+ 1);
7657 if (n_editor_args
> 0) {
7658 args
[0] = editor_args
[0];
7659 for (; i
< n_editor_args
; i
++)
7660 args
[i
] = editor_args
[i
];
7663 STRV_FOREACH_PAIR(original_path
, tmp_path
, paths
)
7664 args
[i
++] = *tmp_path
;
7667 if (n_editor_args
> 0)
7668 execvp(args
[0], (char* const*) args
);
7670 FOREACH_STRING(p
, "editor", "nano", "vim", "vi") {
7672 execvp(p
, (char* const*) args
);
7673 /* We do not fail if the editor doesn't exist
7674 * because we want to try each one of them before
7677 if (errno
!= ENOENT
) {
7678 log_error_errno(errno
, "Failed to execute %s: %m", editor
);
7679 _exit(EXIT_FAILURE
);
7683 log_error("Cannot edit unit(s), no editor available. Please set either $SYSTEMD_EDITOR, $EDITOR or $VISUAL.");
7684 _exit(EXIT_FAILURE
);
7690 static int find_paths_to_edit(sd_bus
*bus
, char **names
, char ***paths
) {
7691 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
7698 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
7702 STRV_FOREACH(name
, names
) {
7703 _cleanup_free_
char *path
= NULL
, *new_path
= NULL
, *tmp_path
= NULL
, *tmp_name
= NULL
;
7704 const char *unit_name
;
7706 r
= unit_find_paths(bus
, *name
, &lp
, false, &path
, NULL
);
7707 if (r
== -EKEYREJECTED
) {
7708 /* If loading of the unit failed server side complete, then the server won't tell us the unit
7709 * file path. In that case, find the file client side. */
7710 log_debug_errno(r
, "Unit '%s' was not loaded correctly, retrying client-side.", *name
);
7711 r
= unit_find_paths(bus
, *name
, &lp
, true, &path
, NULL
);
7714 return log_error_errno(r
, "Unit '%s' masked, cannot edit.", *name
);
7722 log_info("Run 'systemctl edit%s --force --full %s' to create a new unit.",
7723 arg_scope
== UNIT_FILE_GLOBAL
? " --global" :
7724 arg_scope
== UNIT_FILE_USER
? " --user" : "",
7729 /* Create a new unit from scratch */
7731 r
= unit_file_create_new(&lp
, unit_name
,
7732 arg_full
? NULL
: ".d/override.conf",
7733 &new_path
, &tmp_path
);
7737 unit_name
= basename(path
);
7738 /* We follow unit aliases, but we need to propagate the instance */
7739 if (unit_name_is_valid(*name
, UNIT_NAME_INSTANCE
) &&
7740 unit_name_is_valid(unit_name
, UNIT_NAME_TEMPLATE
)) {
7741 _cleanup_free_
char *instance
= NULL
;
7743 r
= unit_name_to_instance(*name
, &instance
);
7747 r
= unit_name_replace_instance(unit_name
, instance
, &tmp_name
);
7751 unit_name
= tmp_name
;
7755 r
= unit_file_create_copy(&lp
, unit_name
, path
, &new_path
, &tmp_path
);
7757 r
= unit_file_create_new(&lp
, unit_name
, ".d/override.conf", &new_path
, &tmp_path
);
7762 r
= strv_push_pair(paths
, new_path
, tmp_path
);
7766 new_path
= tmp_path
= NULL
;
7772 static int edit(int argc
, char *argv
[], void *userdata
) {
7773 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
7774 _cleanup_strv_free_
char **names
= NULL
;
7775 _cleanup_strv_free_
char **paths
= NULL
;
7776 char **original
, **tmp
;
7781 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit units if not on a tty.");
7783 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
7784 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit units remotely.");
7786 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
7788 return log_error_errno(r
, "Failed to determine unit paths: %m");
7790 r
= acquire_bus(BUS_MANAGER
, &bus
);
7794 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
7796 return log_error_errno(r
, "Failed to expand names: %m");
7798 STRV_FOREACH(tmp
, names
) {
7799 r
= unit_is_masked(bus
, &lp
, *tmp
);
7803 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit %s: unit is masked.", *tmp
);
7806 r
= find_paths_to_edit(bus
, names
, &paths
);
7810 if (strv_isempty(paths
))
7813 r
= run_editor(paths
);
7817 STRV_FOREACH_PAIR(original
, tmp
, paths
) {
7818 /* If the temporary file is empty we ignore it.
7819 * This allows the user to cancel the modification.
7821 if (null_or_empty_path(*tmp
)) {
7822 log_warning("Editing \"%s\" canceled: temporary file is empty.", *original
);
7826 r
= rename(*tmp
, *original
);
7828 r
= log_error_errno(errno
, "Failed to rename \"%s\" to \"%s\": %m", *tmp
, *original
);
7835 if (!arg_no_reload
&& !install_client_side())
7836 r
= daemon_reload(argc
, argv
, userdata
);
7839 STRV_FOREACH_PAIR(original
, tmp
, paths
) {
7840 (void) unlink(*tmp
);
7842 /* Removing empty dropin dirs */
7844 _cleanup_free_
char *dir
;
7846 dir
= dirname_malloc(*original
);
7850 /* no need to check if the dir is empty, rmdir
7851 * does nothing if it is not the case.
7860 static int systemctl_help(void) {
7861 _cleanup_free_
char *link
= NULL
;
7864 (void) pager_open(arg_pager_flags
);
7866 r
= terminal_urlify_man("systemctl", "1", &link
);
7870 printf("%1$s [OPTIONS...] COMMAND ...\n\n"
7871 "%5$sQuery or send control commands to the system manager.%6$s\n"
7872 "\n%3$sUnit Commands:%4$s\n"
7873 " list-units [PATTERN...] List units currently in memory\n"
7874 " list-sockets [PATTERN...] List socket units currently in memory,\n"
7875 " ordered by address\n"
7876 " list-timers [PATTERN...] List timer units currently in memory,\n"
7877 " ordered by next elapse\n"
7878 " start UNIT... Start (activate) one or more units\n"
7879 " stop UNIT... Stop (deactivate) one or more units\n"
7880 " reload UNIT... Reload one or more units\n"
7881 " restart UNIT... Start or restart one or more units\n"
7882 " try-restart UNIT... Restart one or more units if active\n"
7883 " reload-or-restart UNIT... Reload one or more units if possible,\n"
7884 " otherwise start or restart\n"
7885 " try-reload-or-restart UNIT... If active, reload one or more units,\n"
7886 " if supported, otherwise restart\n"
7887 " isolate UNIT Start one unit and stop all others\n"
7888 " kill UNIT... Send signal to processes of a unit\n"
7889 " clean UNIT... Clean runtime, cache, state, logs or\n"
7890 " configuration of unit\n"
7891 " is-active PATTERN... Check whether units are active\n"
7892 " is-failed PATTERN... Check whether units are failed\n"
7893 " status [PATTERN...|PID...] Show runtime status of one or more units\n"
7894 " show [PATTERN...|JOB...] Show properties of one or more\n"
7895 " units/jobs or the manager\n"
7896 " cat PATTERN... Show files and drop-ins of specified units\n"
7897 " set-property UNIT PROPERTY=VALUE... Sets one or more properties of a unit\n"
7898 " help PATTERN...|PID... Show manual for one or more units\n"
7899 " reset-failed [PATTERN...] Reset failed state for all, one, or more\n"
7901 " list-dependencies [UNIT...] Recursively show units which are required\n"
7902 " or wanted by the units or by which those\n"
7903 " units are required or wanted"
7904 "\n%3$sUnit File Commands:%4$s\n"
7905 " list-unit-files [PATTERN...] List installed unit files\n"
7906 " enable [UNIT...|PATH...] Enable one or more unit files\n"
7907 " disable UNIT... Disable one or more unit files\n"
7908 " reenable UNIT... Reenable one or more unit files\n"
7909 " preset UNIT... Enable/disable one or more unit files\n"
7910 " based on preset configuration\n"
7911 " preset-all Enable/disable all unit files based on\n"
7912 " preset configuration\n"
7913 " is-enabled UNIT... Check whether unit files are enabled\n"
7914 " mask UNIT... Mask one or more units\n"
7915 " unmask UNIT... Unmask one or more units\n"
7916 " link PATH... Link one or more units files into\n"
7917 " the search path\n"
7918 " revert UNIT... Revert one or more unit files to vendor\n"
7920 " add-wants TARGET UNIT... Add 'Wants' dependency for the target\n"
7921 " on specified one or more units\n"
7922 " add-requires TARGET UNIT... Add 'Requires' dependency for the target\n"
7923 " on specified one or more units\n"
7924 " edit UNIT... Edit one or more unit files\n"
7925 " get-default Get the name of the default target\n"
7926 " set-default TARGET Set the default target\n"
7927 "\n%3$sMachine Commands:%4$s\n"
7928 " list-machines [PATTERN...] List local containers and host\n"
7929 "\n%3$sJob Commands:%4$s\n"
7930 " list-jobs [PATTERN...] List jobs\n"
7931 " cancel [JOB...] Cancel all, one, or more jobs\n"
7932 "\n%3$sEnvironment Commands:%4$s\n"
7933 " show-environment Dump environment\n"
7934 " set-environment VARIABLE=VALUE... Set one or more environment variables\n"
7935 " unset-environment VARIABLE... Unset one or more environment variables\n"
7936 " import-environment [VARIABLE...] Import all or some environment variables\n"
7937 "\n%3$sManager State Commands:%4$s\n"
7938 " daemon-reload Reload systemd manager configuration\n"
7939 " daemon-reexec Reexecute systemd manager\n"
7940 " log-level [LEVEL] Get/set logging threshold for manager\n"
7941 " log-target [TARGET] Get/set logging target for manager\n"
7942 " service-watchdogs [BOOL] Get/set service watchdog state\n"
7943 "\n%3$sSystem Commands:%4$s\n"
7944 " is-system-running Check whether system is fully running\n"
7945 " default Enter system default mode\n"
7946 " rescue Enter system rescue mode\n"
7947 " emergency Enter system emergency mode\n"
7948 " halt Shut down and halt the system\n"
7949 " poweroff Shut down and power-off the system\n"
7950 " reboot [ARG] Shut down and reboot the system\n"
7951 " kexec Shut down and reboot the system with kexec\n"
7952 " exit [EXIT_CODE] Request user instance or container exit\n"
7953 " switch-root ROOT [INIT] Change to a different root file system\n"
7954 " suspend Suspend the system\n"
7955 " hibernate Hibernate the system\n"
7956 " hybrid-sleep Hibernate and suspend the system\n"
7957 " suspend-then-hibernate Suspend the system, wake after a period of\n"
7958 " time, and hibernate"
7959 "\n%3$sOptions:%4$s\n"
7960 " -h --help Show this help\n"
7961 " --version Show package version\n"
7962 " --system Connect to system manager\n"
7963 " --user Connect to user service manager\n"
7964 " -H --host=[USER@]HOST Operate on remote host\n"
7965 " -M --machine=CONTAINER Operate on a local container\n"
7966 " -t --type=TYPE List units of a particular type\n"
7967 " --state=STATE List units with particular LOAD or SUB or ACTIVE state\n"
7968 " --failed Shorcut for --state=failed\n"
7969 " -p --property=NAME Show only properties by this name\n"
7970 " -P NAME Equivalent to --value --property=NAME\n"
7971 " -a --all Show all properties/all units currently in memory,\n"
7972 " including dead/empty ones. To list all units installed\n"
7973 " on the system, use 'list-unit-files' instead.\n"
7974 " -l --full Don't ellipsize unit names on output\n"
7975 " -r --recursive Show unit list of host and local containers\n"
7976 " --reverse Show reverse dependencies with 'list-dependencies'\n"
7977 " --with-dependencies Show unit dependencies with 'status', 'cat',\n"
7978 " 'list-units', and 'list-unit-files'.\n"
7979 " --job-mode=MODE Specify how to deal with already queued jobs, when\n"
7980 " queueing a new job\n"
7981 " -T --show-transaction When enqueuing a unit job, show full transaction\n"
7982 " --show-types When showing sockets, explicitly show their type\n"
7983 " --value When showing properties, only print the value\n"
7984 " -i --ignore-inhibitors When shutting down or sleeping, ignore inhibitors\n"
7985 " --kill-who=WHO Whom to send signal to\n"
7986 " -s --signal=SIGNAL Which signal to send\n"
7987 " --what=RESOURCES Which types of resources to remove\n"
7988 " --now Start or stop unit after enabling or disabling it\n"
7989 " --dry-run Only print what would be done\n"
7990 " Currently supported by verbs: halt, poweroff, reboot,\n"
7991 " kexec, suspend, hibernate, suspend-then-hibernate,\n"
7992 " hybrid-sleep, default, rescue, emergency, and exit.\n"
7993 " -q --quiet Suppress output\n"
7994 " --wait For (re)start, wait until service stopped again\n"
7995 " For is-system-running, wait until startup is completed\n"
7996 " --no-block Do not wait until operation finished\n"
7997 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7998 " --no-reload Don't reload daemon after en-/dis-abling unit files\n"
7999 " --no-legend Do not print a legend (column headers and hints)\n"
8000 " --no-pager Do not pipe output into a pager\n"
8001 " --no-ask-password Do not ask for system passwords\n"
8002 " --global Enable/disable/mask unit files globally\n"
8003 " --runtime Enable/disable/mask unit files temporarily until next\n"
8005 " -f --force When enabling unit files, override existing symlinks\n"
8006 " When shutting down, execute action immediately\n"
8007 " --preset-mode= Apply only enable, only disable, or all presets\n"
8008 " --root=PATH Enable/disable/mask unit files in the specified root\n"
8010 " -n --lines=INTEGER Number of journal entries to show\n"
8011 " -o --output=STRING Change journal output mode (short, short-precise,\n"
8012 " short-iso, short-iso-precise, short-full,\n"
8013 " short-monotonic, short-unix,\n"
8014 " verbose, export, json, json-pretty, json-sse, cat)\n"
8015 " --firmware-setup Tell the firmware to show the setup menu on next boot\n"
8016 " --boot-loader-menu=TIME\n"
8017 " Boot into boot loader menu on next boot\n"
8018 " --boot-loader-entry=NAME\n"
8019 " Boot into a specific boot loader entry on next boot\n"
8020 " --plain Print unit dependencies as a list instead of a tree\n"
8021 "\nSee the %2$s for details.\n"
8022 , program_invocation_short_name
8024 , ansi_underline(), ansi_normal()
8025 , ansi_highlight(), ansi_normal()
8031 static int halt_help(void) {
8032 _cleanup_free_
char *link
= NULL
;
8035 r
= terminal_urlify_man("halt", "8", &link
);
8039 printf("%s [OPTIONS...]%s\n"
8040 "\n%s%s the system.%s\n"
8042 " --help Show this help\n"
8043 " --halt Halt the machine\n"
8044 " -p --poweroff Switch off the machine\n"
8045 " --reboot Reboot the machine\n"
8046 " -f --force Force immediate halt/power-off/reboot\n"
8047 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
8048 " -d --no-wtmp Don't write wtmp record\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 , arg_action
== ACTION_REBOOT
? " [ARG]" : ""
8054 , arg_action
== ACTION_REBOOT
? "Reboot" :
8055 arg_action
== ACTION_POWEROFF
? "Power off" :
8064 static int shutdown_help(void) {
8065 _cleanup_free_
char *link
= NULL
;
8068 r
= terminal_urlify_man("shutdown", "8", &link
);
8072 printf("%s [OPTIONS...] [TIME] [WALL...]\n"
8073 "\n%sShut down the system.%s\n"
8075 " --help Show this help\n"
8076 " -H --halt Halt the machine\n"
8077 " -P --poweroff Power-off the machine\n"
8078 " -r --reboot Reboot the machine\n"
8079 " -h Equivalent to --poweroff, overridden by --halt\n"
8080 " -k Don't halt/power-off/reboot, just send warnings\n"
8081 " --no-wall Don't send wall message before halt/power-off/reboot\n"
8082 " -c Cancel a pending shutdown\n"
8083 "\nSee the %s for details.\n"
8084 , program_invocation_short_name
8085 , ansi_highlight(), ansi_normal()
8092 static int telinit_help(void) {
8093 _cleanup_free_
char *link
= NULL
;
8096 r
= terminal_urlify_man("telinit", "8", &link
);
8100 printf("%s [OPTIONS...] COMMAND\n\n"
8101 "%sSend control commands to the init daemon.%s\n"
8103 " 0 Power-off the machine\n"
8104 " 6 Reboot the machine\n"
8105 " 2, 3, 4, 5 Start runlevelX.target unit\n"
8106 " 1, s, S Enter rescue mode\n"
8107 " q, Q Reload init daemon configuration\n"
8108 " u, U Reexecute init daemon\n"
8110 " --help Show this help\n"
8111 " --no-wall Don't send wall message before halt/power-off/reboot\n"
8112 "\nSee the %s for details.\n"
8113 , program_invocation_short_name
8114 , ansi_highlight(), ansi_normal()
8121 static int runlevel_help(void) {
8122 _cleanup_free_
char *link
= NULL
;
8125 r
= terminal_urlify_man("runlevel", "8", &link
);
8129 printf("%s [OPTIONS...]\n"
8130 "\n%sPrints the previous and current runlevel of the init system.%s\n"
8132 " --help Show this help\n"
8133 "\nSee the %s for details.\n"
8134 , program_invocation_short_name
8135 , ansi_highlight(), ansi_normal()
8142 static void help_types(void) {
8144 puts("Available unit types:");
8146 DUMP_STRING_TABLE(unit_type
, UnitType
, _UNIT_TYPE_MAX
);
8149 static void help_states(void) {
8151 puts("Available unit load states:");
8152 DUMP_STRING_TABLE(unit_load_state
, UnitLoadState
, _UNIT_LOAD_STATE_MAX
);
8155 puts("\nAvailable unit active states:");
8156 DUMP_STRING_TABLE(unit_active_state
, UnitActiveState
, _UNIT_ACTIVE_STATE_MAX
);
8159 puts("\nAvailable unit file states:");
8160 DUMP_STRING_TABLE(unit_file_state
, UnitFileState
, _UNIT_FILE_STATE_MAX
);
8163 puts("\nAvailable automount unit substates:");
8164 DUMP_STRING_TABLE(automount_state
, AutomountState
, _AUTOMOUNT_STATE_MAX
);
8167 puts("\nAvailable device unit substates:");
8168 DUMP_STRING_TABLE(device_state
, DeviceState
, _DEVICE_STATE_MAX
);
8171 puts("\nAvailable mount unit substates:");
8172 DUMP_STRING_TABLE(mount_state
, MountState
, _MOUNT_STATE_MAX
);
8175 puts("\nAvailable path unit substates:");
8176 DUMP_STRING_TABLE(path_state
, PathState
, _PATH_STATE_MAX
);
8179 puts("\nAvailable scope unit substates:");
8180 DUMP_STRING_TABLE(scope_state
, ScopeState
, _SCOPE_STATE_MAX
);
8183 puts("\nAvailable service unit substates:");
8184 DUMP_STRING_TABLE(service_state
, ServiceState
, _SERVICE_STATE_MAX
);
8187 puts("\nAvailable slice unit substates:");
8188 DUMP_STRING_TABLE(slice_state
, SliceState
, _SLICE_STATE_MAX
);
8191 puts("\nAvailable socket unit substates:");
8192 DUMP_STRING_TABLE(socket_state
, SocketState
, _SOCKET_STATE_MAX
);
8195 puts("\nAvailable swap unit substates:");
8196 DUMP_STRING_TABLE(swap_state
, SwapState
, _SWAP_STATE_MAX
);
8199 puts("\nAvailable target unit substates:");
8200 DUMP_STRING_TABLE(target_state
, TargetState
, _TARGET_STATE_MAX
);
8203 puts("\nAvailable timer unit substates:");
8204 DUMP_STRING_TABLE(timer_state
, TimerState
, _TIMER_STATE_MAX
);
8207 static int help_boot_loader_entry(void) {
8208 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
8209 _cleanup_strv_free_
char **l
= NULL
;
8214 r
= acquire_bus(BUS_FULL
, &bus
);
8218 r
= sd_bus_get_property_strv(
8220 "org.freedesktop.login1",
8221 "/org/freedesktop/login1",
8222 "org.freedesktop.login1.Manager",
8223 "BootLoaderEntries",
8227 return log_error_errno(r
, "Failed to enumerate boot loader entries: %s", bus_error_message(&error
, r
));
8229 if (strv_isempty(l
))
8230 return log_error_errno(SYNTHETIC_ERRNO(ENODATA
), "No boot loader entries discovered.");
8238 static int systemctl_parse_argv(int argc
, char *argv
[]) {
8247 ARG_IGNORE_DEPENDENCIES
,
8260 ARG_NO_ASK_PASSWORD
,
8268 ARG_BOOT_LOADER_MENU
,
8269 ARG_BOOT_LOADER_ENTRY
,
8272 ARG_WITH_DEPENDENCIES
,
8277 static const struct option options
[] = {
8278 { "help", no_argument
, NULL
, 'h' },
8279 { "version", no_argument
, NULL
, ARG_VERSION
},
8280 { "type", required_argument
, NULL
, 't' },
8281 { "property", required_argument
, NULL
, 'p' },
8282 { "all", no_argument
, NULL
, 'a' },
8283 { "reverse", no_argument
, NULL
, ARG_REVERSE
},
8284 { "after", no_argument
, NULL
, ARG_AFTER
},
8285 { "before", no_argument
, NULL
, ARG_BEFORE
},
8286 { "show-types", no_argument
, NULL
, ARG_SHOW_TYPES
},
8287 { "failed", no_argument
, NULL
, ARG_FAILED
}, /* compatibility only */
8288 { "full", no_argument
, NULL
, 'l' },
8289 { "job-mode", required_argument
, NULL
, ARG_JOB_MODE
},
8290 { "fail", no_argument
, NULL
, ARG_FAIL
}, /* compatibility only */
8291 { "irreversible", no_argument
, NULL
, ARG_IRREVERSIBLE
}, /* compatibility only */
8292 { "ignore-dependencies", no_argument
, NULL
, ARG_IGNORE_DEPENDENCIES
}, /* compatibility only */
8293 { "ignore-inhibitors", no_argument
, NULL
, 'i' },
8294 { "value", no_argument
, NULL
, ARG_VALUE
},
8295 { "user", no_argument
, NULL
, ARG_USER
},
8296 { "system", no_argument
, NULL
, ARG_SYSTEM
},
8297 { "global", no_argument
, NULL
, ARG_GLOBAL
},
8298 { "wait", no_argument
, NULL
, ARG_WAIT
},
8299 { "no-block", no_argument
, NULL
, ARG_NO_BLOCK
},
8300 { "no-legend", no_argument
, NULL
, ARG_NO_LEGEND
},
8301 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
8302 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8303 { "dry-run", no_argument
, NULL
, ARG_DRY_RUN
},
8304 { "quiet", no_argument
, NULL
, 'q' },
8305 { "root", required_argument
, NULL
, ARG_ROOT
},
8306 { "force", no_argument
, NULL
, 'f' },
8307 { "no-reload", no_argument
, NULL
, ARG_NO_RELOAD
},
8308 { "kill-who", required_argument
, NULL
, ARG_KILL_WHO
},
8309 { "signal", required_argument
, NULL
, 's' },
8310 { "no-ask-password", no_argument
, NULL
, ARG_NO_ASK_PASSWORD
},
8311 { "host", required_argument
, NULL
, 'H' },
8312 { "machine", required_argument
, NULL
, 'M' },
8313 { "runtime", no_argument
, NULL
, ARG_RUNTIME
},
8314 { "lines", required_argument
, NULL
, 'n' },
8315 { "output", required_argument
, NULL
, 'o' },
8316 { "plain", no_argument
, NULL
, ARG_PLAIN
},
8317 { "state", required_argument
, NULL
, ARG_STATE
},
8318 { "recursive", no_argument
, NULL
, 'r' },
8319 { "with-dependencies", no_argument
, NULL
, ARG_WITH_DEPENDENCIES
},
8320 { "preset-mode", required_argument
, NULL
, ARG_PRESET_MODE
},
8321 { "firmware-setup", no_argument
, NULL
, ARG_FIRMWARE_SETUP
},
8322 { "boot-loader-menu", required_argument
, NULL
, ARG_BOOT_LOADER_MENU
},
8323 { "boot-loader-entry", required_argument
, NULL
, ARG_BOOT_LOADER_ENTRY
},
8324 { "now", no_argument
, NULL
, ARG_NOW
},
8325 { "message", required_argument
, NULL
, ARG_MESSAGE
},
8326 { "show-transaction", no_argument
, NULL
, 'T' },
8327 { "what", required_argument
, NULL
, ARG_WHAT
},
8336 /* we default to allowing interactive authorization only in systemctl (not in the legacy commands) */
8337 arg_ask_password
= true;
8339 while ((c
= getopt_long(argc
, argv
, "ht:p:P:alqfs:H:M:n:o:iTr.::", options
, NULL
)) >= 0)
8344 return systemctl_help();
8352 if (isempty(optarg
))
8353 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8354 "--type= requires arguments.");
8356 for (p
= optarg
;;) {
8357 _cleanup_free_
char *type
= NULL
;
8359 r
= extract_first_word(&p
, &type
, ",", 0);
8361 return log_error_errno(r
, "Failed to parse type: %s", optarg
);
8365 if (streq(type
, "help")) {
8370 if (unit_type_from_string(type
) >= 0) {
8371 if (strv_consume(&arg_types
, TAKE_PTR(type
)) < 0)
8376 /* It's much nicer to use --state= for
8377 * load states, but let's support this
8378 * in --types= too for compatibility
8379 * with old versions */
8380 if (unit_load_state_from_string(type
) >= 0) {
8381 if (strv_consume(&arg_states
, TAKE_PTR(type
)) < 0)
8386 log_error("Unknown unit type or load state '%s'.", type
);
8387 return log_info_errno(SYNTHETIC_ERRNO(EINVAL
),
8388 "Use -t help to see a list of allowed values.");
8399 /* Make sure that if the empty property list was specified, we won't show any
8401 if (isempty(optarg
) && !arg_properties
) {
8402 arg_properties
= new0(char*, 1);
8403 if (!arg_properties
)
8408 for (p
= optarg
;;) {
8409 _cleanup_free_
char *prop
= NULL
;
8411 r
= extract_first_word(&p
, &prop
, ",", 0);
8413 return log_error_errno(r
, "Failed to parse property: %s", optarg
);
8417 if (strv_consume(&arg_properties
, TAKE_PTR(prop
)) < 0)
8422 /* If the user asked for a particular property, show it, even if it is empty. */
8432 arg_dependency
= DEPENDENCY_REVERSE
;
8436 arg_dependency
= DEPENDENCY_AFTER
;
8437 arg_jobs_after
= true;
8441 arg_dependency
= DEPENDENCY_BEFORE
;
8442 arg_jobs_before
= true;
8445 case ARG_SHOW_TYPES
:
8446 arg_show_types
= true;
8454 arg_job_mode
= optarg
;
8458 arg_job_mode
= "fail";
8461 case ARG_IRREVERSIBLE
:
8462 arg_job_mode
= "replace-irreversibly";
8465 case ARG_IGNORE_DEPENDENCIES
:
8466 arg_job_mode
= "ignore-dependencies";
8470 arg_scope
= UNIT_FILE_USER
;
8474 arg_scope
= UNIT_FILE_SYSTEM
;
8478 arg_scope
= UNIT_FILE_GLOBAL
;
8486 arg_no_block
= true;
8490 arg_no_legend
= true;
8494 arg_pager_flags
|= PAGER_DISABLE
;
8502 r
= parse_path_argument_and_warn(optarg
, false, &arg_root
);
8512 if (strv_extend(&arg_states
, "failed") < 0)
8530 arg_no_reload
= true;
8534 arg_kill_who
= optarg
;
8538 if (streq(optarg
, "help")) {
8539 DUMP_STRING_TABLE(signal
, int, _NSIG
);
8543 arg_signal
= signal_from_string(optarg
);
8545 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8546 "Failed to parse signal string %s.",
8550 case ARG_NO_ASK_PASSWORD
:
8551 arg_ask_password
= false;
8555 arg_transport
= BUS_TRANSPORT_REMOTE
;
8560 arg_transport
= BUS_TRANSPORT_MACHINE
;
8569 if (safe_atou(optarg
, &arg_lines
) < 0)
8570 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8571 "Failed to parse lines '%s'",
8576 if (streq(optarg
, "help")) {
8577 DUMP_STRING_TABLE(output_mode
, OutputMode
, _OUTPUT_MODE_MAX
);
8581 arg_output
= output_mode_from_string(optarg
);
8583 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8584 "Unknown output '%s'.",
8589 arg_ignore_inhibitors
= true;
8596 case ARG_FIRMWARE_SETUP
:
8597 arg_firmware_setup
= true;
8600 case ARG_BOOT_LOADER_MENU
:
8602 r
= parse_sec(optarg
, &arg_boot_loader_menu
);
8604 return log_error_errno(r
, "Failed to parse --boot-loader-menu= argument '%s': %m", optarg
);
8608 case ARG_BOOT_LOADER_ENTRY
:
8610 if (streq(optarg
, "help")) { /* Yes, this means, "help" is not a valid boot loader entry name we can deal with */
8611 r
= help_boot_loader_entry();
8618 arg_boot_loader_entry
= empty_to_null(optarg
);
8624 if (isempty(optarg
))
8625 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8626 "--state= requires arguments.");
8628 for (p
= optarg
;;) {
8629 _cleanup_free_
char *s
= NULL
;
8631 r
= extract_first_word(&p
, &s
, ",", 0);
8633 return log_error_errno(r
, "Failed to parse state: %s", optarg
);
8637 if (streq(s
, "help")) {
8642 if (strv_consume(&arg_states
, TAKE_PTR(s
)) < 0)
8650 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
8651 "--recursive requires root privileges.");
8653 arg_recursive
= true;
8656 case ARG_PRESET_MODE
:
8657 if (streq(optarg
, "help")) {
8658 DUMP_STRING_TABLE(unit_file_preset_mode
, UnitFilePresetMode
, _UNIT_FILE_PRESET_MAX
);
8662 arg_preset_mode
= unit_file_preset_mode_from_string(optarg
);
8663 if (arg_preset_mode
< 0)
8664 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8665 "Failed to parse preset mode: %s.", optarg
);
8674 if (strv_extend(&arg_wall
, optarg
) < 0)
8679 arg_show_transaction
= true;
8682 case ARG_WITH_DEPENDENCIES
:
8683 arg_with_dependencies
= true;
8689 if (isempty(optarg
))
8690 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "--what= requires arguments.");
8692 for (p
= optarg
;;) {
8693 _cleanup_free_
char *k
= NULL
;
8695 r
= extract_first_word(&p
, &k
, ",", 0);
8697 return log_error_errno(r
, "Failed to parse directory type: %s", optarg
);
8701 if (streq(k
, "help")) {
8710 r
= strv_consume(&arg_clean_what
, TAKE_PTR(k
));
8719 /* Output an error mimicking getopt, and print a hint afterwards */
8720 log_error("%s: invalid option -- '.'", program_invocation_name
);
8721 log_notice("Hint: to specify units starting with a dash, use \"--\":\n"
8722 " %s [OPTIONS...] COMMAND -- -.%s ...",
8723 program_invocation_name
, optarg
?: "mount");
8730 assert_not_reached("Unhandled option");
8733 if (arg_transport
!= BUS_TRANSPORT_LOCAL
&& arg_scope
!= UNIT_FILE_SYSTEM
)
8734 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8735 "Cannot access user instance remotely.");
8737 if (arg_wait
&& arg_no_block
)
8738 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8739 "--wait may not be combined with --no-block.");
8744 static int halt_parse_argv(int argc
, char *argv
[]) {
8752 static const struct option options
[] = {
8753 { "help", no_argument
, NULL
, ARG_HELP
},
8754 { "halt", no_argument
, NULL
, ARG_HALT
},
8755 { "poweroff", no_argument
, NULL
, 'p' },
8756 { "reboot", no_argument
, NULL
, ARG_REBOOT
},
8757 { "force", no_argument
, NULL
, 'f' },
8758 { "wtmp-only", no_argument
, NULL
, 'w' },
8759 { "no-wtmp", no_argument
, NULL
, 'd' },
8760 { "no-sync", no_argument
, NULL
, 'n' },
8761 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8770 if (utmp_get_runlevel(&runlevel
, NULL
) >= 0)
8771 if (IN_SET(runlevel
, '0', '6'))
8774 while ((c
= getopt_long(argc
, argv
, "pfwdnih", options
, NULL
)) >= 0)
8781 arg_action
= ACTION_HALT
;
8785 if (arg_action
!= ACTION_REBOOT
)
8786 arg_action
= ACTION_POWEROFF
;
8790 arg_action
= ACTION_REBOOT
;
8815 /* Compatibility nops */
8822 assert_not_reached("Unhandled option");
8825 if (arg_action
== ACTION_REBOOT
&& (argc
== optind
|| argc
== optind
+ 1)) {
8826 r
= update_reboot_parameter_and_warn(argc
== optind
+ 1 ? argv
[optind
] : NULL
, false);
8829 } else if (optind
< argc
)
8830 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8831 "Too many arguments.");
8836 static int shutdown_parse_argv(int argc
, char *argv
[]) {
8842 static const struct option options
[] = {
8843 { "help", no_argument
, NULL
, ARG_HELP
},
8844 { "halt", no_argument
, NULL
, 'H' },
8845 { "poweroff", no_argument
, NULL
, 'P' },
8846 { "reboot", no_argument
, NULL
, 'r' },
8847 { "kexec", no_argument
, NULL
, 'K' }, /* not documented extension */
8848 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8858 while ((c
= getopt_long(argc
, argv
, "HPrhkKat:fFc", options
, NULL
)) >= 0)
8862 return shutdown_help();
8865 arg_action
= ACTION_HALT
;
8869 arg_action
= ACTION_POWEROFF
;
8874 arg_action
= ACTION_KEXEC
;
8876 arg_action
= ACTION_REBOOT
;
8880 arg_action
= ACTION_KEXEC
;
8884 if (arg_action
!= ACTION_HALT
)
8885 arg_action
= ACTION_POWEROFF
;
8897 case 't': /* Note that we also ignore any passed argument to -t, not just the -t itself */
8900 /* Compatibility nops */
8904 arg_action
= ACTION_CANCEL_SHUTDOWN
;
8911 assert_not_reached("Unhandled option");
8914 if (argc
> optind
&& arg_action
!= ACTION_CANCEL_SHUTDOWN
) {
8915 r
= parse_shutdown_time_spec(argv
[optind
], &arg_when
);
8917 log_error("Failed to parse time specification: %s", argv
[optind
]);
8921 arg_when
= now(CLOCK_REALTIME
) + USEC_PER_MINUTE
;
8923 if (argc
> optind
&& arg_action
== ACTION_CANCEL_SHUTDOWN
)
8924 /* No time argument for shutdown cancel */
8925 wall
= argv
+ optind
;
8926 else if (argc
> optind
+ 1)
8927 /* We skip the time argument */
8928 wall
= argv
+ optind
+ 1;
8931 arg_wall
= strv_copy(wall
);
8941 static int telinit_parse_argv(int argc
, char *argv
[]) {
8947 static const struct option options
[] = {
8948 { "help", no_argument
, NULL
, ARG_HELP
},
8949 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8953 static const struct {
8957 { '0', ACTION_POWEROFF
},
8958 { '6', ACTION_REBOOT
},
8959 { '1', ACTION_RESCUE
},
8960 { '2', ACTION_RUNLEVEL2
},
8961 { '3', ACTION_RUNLEVEL3
},
8962 { '4', ACTION_RUNLEVEL4
},
8963 { '5', ACTION_RUNLEVEL5
},
8964 { 's', ACTION_RESCUE
},
8965 { 'S', ACTION_RESCUE
},
8966 { 'q', ACTION_RELOAD
},
8967 { 'Q', ACTION_RELOAD
},
8968 { 'u', ACTION_REEXEC
},
8969 { 'U', ACTION_REEXEC
}
8978 while ((c
= getopt_long(argc
, argv
, "", options
, NULL
)) >= 0)
8982 return telinit_help();
8992 assert_not_reached("Unhandled option");
8996 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8997 "%s: required argument missing.",
8998 program_invocation_short_name
);
9000 if (optind
+ 1 < argc
)
9001 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
9002 "Too many arguments.");
9004 if (strlen(argv
[optind
]) != 1)
9005 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
9006 "Expected single character argument.");
9008 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
9009 if (table
[i
].from
== argv
[optind
][0])
9012 if (i
>= ELEMENTSOF(table
))
9013 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
9014 "Unknown command '%s'.", argv
[optind
]);
9016 arg_action
= table
[i
].to
;
9023 static int runlevel_parse_argv(int argc
, char *argv
[]) {
9028 static const struct option options
[] = {
9029 { "help", no_argument
, NULL
, ARG_HELP
},
9038 while ((c
= getopt_long(argc
, argv
, "", options
, NULL
)) >= 0)
9042 return runlevel_help();
9048 assert_not_reached("Unhandled option");
9052 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
9053 "Too many arguments.");
9058 static int parse_argv(int argc
, char *argv
[]) {
9062 if (program_invocation_short_name
) {
9064 if (strstr(program_invocation_short_name
, "halt")) {
9065 arg_action
= ACTION_HALT
;
9066 return halt_parse_argv(argc
, argv
);
9068 } else if (strstr(program_invocation_short_name
, "poweroff")) {
9069 arg_action
= ACTION_POWEROFF
;
9070 return halt_parse_argv(argc
, argv
);
9072 } else if (strstr(program_invocation_short_name
, "reboot")) {
9074 arg_action
= ACTION_KEXEC
;
9076 arg_action
= ACTION_REBOOT
;
9077 return halt_parse_argv(argc
, argv
);
9079 } else if (strstr(program_invocation_short_name
, "shutdown")) {
9080 arg_action
= ACTION_POWEROFF
;
9081 return shutdown_parse_argv(argc
, argv
);
9083 } else if (strstr(program_invocation_short_name
, "init")) {
9085 /* Matches invocations as "init" as well as "telinit", which are synonymous when run as PID !=
9088 * On SysV "telinit" was the official command to communicate with PID 1, but "init" would
9089 * redirect itself to "telinit" if called with PID != 1. We follow the same logic here still,
9090 * though we add one level of indirection, as we implement "telinit" in "systemctl". Hence, for
9091 * us if you invoke "init" you get "systemd", but it will execve() "systemctl" immediately with
9092 * argv[] unmodified if PID is != 1. If you invoke "telinit" you directly get "systemctl". In
9093 * both cases we shall do the same thing, which is why we do strstr(p_i_s_n, "init") here, as a
9094 * quick way to match both.
9096 * Also see redirect_telinit() in src/core/main.c. */
9098 if (sd_booted() > 0) {
9099 arg_action
= _ACTION_INVALID
;
9100 return telinit_parse_argv(argc
, argv
);
9102 /* Hmm, so some other init system is running, we need to forward this request to
9103 * it. For now we simply guess that it is Upstart. */
9105 (void) rlimit_nofile_safe();
9106 execv(TELINIT
, argv
);
9108 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
9109 "Couldn't find an alternative telinit implementation to spawn.");
9112 } else if (strstr(program_invocation_short_name
, "runlevel")) {
9113 arg_action
= ACTION_RUNLEVEL
;
9114 return runlevel_parse_argv(argc
, argv
);
9118 arg_action
= ACTION_SYSTEMCTL
;
9119 return systemctl_parse_argv(argc
, argv
);
9122 #if HAVE_SYSV_COMPAT
9123 _pure_
static int action_to_runlevel(void) {
9124 static const char table
[_ACTION_MAX
] = {
9125 [ACTION_HALT
] = '0',
9126 [ACTION_POWEROFF
] = '0',
9127 [ACTION_REBOOT
] = '6',
9128 [ACTION_RUNLEVEL2
] = '2',
9129 [ACTION_RUNLEVEL3
] = '3',
9130 [ACTION_RUNLEVEL4
] = '4',
9131 [ACTION_RUNLEVEL5
] = '5',
9132 [ACTION_RESCUE
] = '1'
9135 assert(arg_action
>= 0 && arg_action
< _ACTION_MAX
);
9136 return table
[arg_action
];
9140 static int systemctl_main(int argc
, char *argv
[]) {
9141 static const Verb verbs
[] = {
9142 { "list-units", VERB_ANY
, VERB_ANY
, VERB_DEFAULT
|VERB_ONLINE_ONLY
, list_units
},
9143 { "list-unit-files", VERB_ANY
, VERB_ANY
, 0, list_unit_files
},
9144 { "list-sockets", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_sockets
},
9145 { "list-timers", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_timers
},
9146 { "list-jobs", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_jobs
},
9147 { "list-machines", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_machines
},
9148 { "clear-jobs", VERB_ANY
, 1, VERB_ONLINE_ONLY
, trivial_method
},
9149 { "cancel", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, cancel_job
},
9150 { "start", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9151 { "stop", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9152 { "condstop", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with ALTLinux */
9153 { "reload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9154 { "restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9155 { "try-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9156 { "reload-or-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9157 { "reload-or-try-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with old systemctl <= 228 */
9158 { "try-reload-or-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9159 { "force-reload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with SysV */
9160 { "condreload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with ALTLinux */
9161 { "condrestart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with RH */
9162 { "isolate", 2, 2, VERB_ONLINE_ONLY
, start_unit
},
9163 { "kill", 2, VERB_ANY
, VERB_ONLINE_ONLY
, kill_unit
},
9164 { "clean", 2, VERB_ANY
, VERB_ONLINE_ONLY
, clean_unit
},
9165 { "is-active", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_active
},
9166 { "check", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_active
}, /* deprecated alias of is-active */
9167 { "is-failed", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_failed
},
9168 { "show", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
9169 { "cat", 2, VERB_ANY
, VERB_ONLINE_ONLY
, cat
},
9170 { "status", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
9171 { "help", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
9172 { "daemon-reload", VERB_ANY
, 1, VERB_ONLINE_ONLY
, daemon_reload
},
9173 { "daemon-reexec", VERB_ANY
, 1, VERB_ONLINE_ONLY
, daemon_reload
},
9174 { "log-level", VERB_ANY
, 2, 0, log_level
},
9175 { "log-target", VERB_ANY
, 2, 0, log_target
},
9176 { "service-watchdogs", VERB_ANY
, 2, 0, service_watchdogs
},
9177 { "show-environment", VERB_ANY
, 1, VERB_ONLINE_ONLY
, show_environment
},
9178 { "set-environment", 2, VERB_ANY
, VERB_ONLINE_ONLY
, set_environment
},
9179 { "unset-environment", 2, VERB_ANY
, VERB_ONLINE_ONLY
, set_environment
},
9180 { "import-environment", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, import_environment
},
9181 { "halt", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9182 { "poweroff", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9183 { "reboot", VERB_ANY
, 2, VERB_ONLINE_ONLY
, start_system_special
},
9184 { "kexec", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9185 { "suspend", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9186 { "hibernate", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9187 { "hybrid-sleep", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9188 { "suspend-then-hibernate",VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9189 { "default", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_special
},
9190 { "rescue", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9191 { "emergency", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9192 { "exit", VERB_ANY
, 2, VERB_ONLINE_ONLY
, start_special
},
9193 { "reset-failed", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, reset_failed
},
9194 { "enable", 2, VERB_ANY
, 0, enable_unit
},
9195 { "disable", 2, VERB_ANY
, 0, enable_unit
},
9196 { "is-enabled", 2, VERB_ANY
, 0, unit_is_enabled
},
9197 { "reenable", 2, VERB_ANY
, 0, enable_unit
},
9198 { "preset", 2, VERB_ANY
, 0, enable_unit
},
9199 { "preset-all", VERB_ANY
, 1, 0, preset_all
},
9200 { "mask", 2, VERB_ANY
, 0, enable_unit
},
9201 { "unmask", 2, VERB_ANY
, 0, enable_unit
},
9202 { "link", 2, VERB_ANY
, 0, enable_unit
},
9203 { "revert", 2, VERB_ANY
, 0, enable_unit
},
9204 { "switch-root", 2, VERB_ANY
, VERB_ONLINE_ONLY
, switch_root
},
9205 { "list-dependencies", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_dependencies
},
9206 { "set-default", 2, 2, 0, set_default
},
9207 { "get-default", VERB_ANY
, 1, 0, get_default
},
9208 { "set-property", 3, VERB_ANY
, VERB_ONLINE_ONLY
, set_property
},
9209 { "is-system-running", VERB_ANY
, 1, 0, is_system_running
},
9210 { "add-wants", 3, VERB_ANY
, 0, add_dependency
},
9211 { "add-requires", 3, VERB_ANY
, 0, add_dependency
},
9212 { "edit", 2, VERB_ANY
, VERB_ONLINE_ONLY
, edit
},
9216 return dispatch_verb(argc
, argv
, verbs
, NULL
);
9219 static int reload_with_fallback(void) {
9220 /* First, try systemd via D-Bus. */
9221 if (daemon_reload(0, NULL
, NULL
) >= 0)
9224 /* Nothing else worked, so let's try signals */
9225 assert(IN_SET(arg_action
, ACTION_RELOAD
, ACTION_REEXEC
));
9227 if (kill(1, arg_action
== ACTION_RELOAD
? SIGHUP
: SIGTERM
) < 0)
9228 return log_error_errno(errno
, "kill() failed: %m");
9233 static int start_with_fallback(void) {
9234 /* First, try systemd via D-Bus. */
9235 if (start_unit(0, NULL
, NULL
) == 0)
9238 #if HAVE_SYSV_COMPAT
9239 /* Nothing else worked, so let's try /dev/initctl */
9240 if (talk_initctl(action_to_runlevel()) > 0)
9244 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
9245 "Failed to talk to init daemon.");
9248 static int halt_now(enum action a
) {
9249 /* The kernel will automatically flush ATA disks and suchlike on reboot(), but the file systems need to be
9250 * synced explicitly in advance. */
9251 if (!arg_no_sync
&& !arg_dry_run
)
9254 /* Make sure C-A-D is handled by the kernel from this point on... */
9256 (void) reboot(RB_ENABLE_CAD
);
9262 log_info("Halting.");
9265 (void) reboot(RB_HALT_SYSTEM
);
9268 case ACTION_POWEROFF
:
9270 log_info("Powering off.");
9273 (void) reboot(RB_POWER_OFF
);
9278 return reboot_with_parameter(REBOOT_FALLBACK
|
9279 (arg_quiet
? 0 : REBOOT_LOG
) |
9280 (arg_dry_run
? REBOOT_DRY_RUN
: 0));
9283 assert_not_reached("Unknown action.");
9287 static int logind_schedule_shutdown(void) {
9290 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
9291 char date
[FORMAT_TIMESTAMP_MAX
];
9296 r
= acquire_bus(BUS_FULL
, &bus
);
9300 switch (arg_action
) {
9304 case ACTION_POWEROFF
:
9305 action
= "poweroff";
9320 action
= strjoina("dry-", action
);
9322 (void) logind_set_wall_message();
9324 r
= sd_bus_call_method(
9326 "org.freedesktop.login1",
9327 "/org/freedesktop/login1",
9328 "org.freedesktop.login1.Manager",
9336 return log_warning_errno(r
, "Failed to call ScheduleShutdown in logind, proceeding with immediate shutdown: %s", bus_error_message(&error
, r
));
9339 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.", format_timestamp(date
, sizeof(date
), arg_when
));
9342 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
9343 "Cannot schedule shutdown without logind support, proceeding with immediate shutdown.");
9347 static int halt_main(void) {
9350 r
= logind_check_inhibitors(arg_action
);
9354 /* Delayed shutdown requested, and was successful */
9355 if (arg_when
> 0 && logind_schedule_shutdown() == 0)
9357 /* no delay, or logind failed or is not at all available */
9359 if (geteuid() != 0) {
9360 if (arg_dry_run
|| arg_force
> 0) {
9361 (void) must_be_root();
9365 /* Try logind if we are a normal user and no special
9366 * mode applies. Maybe polkit allows us to shutdown
9368 if (IN_SET(arg_action
, ACTION_POWEROFF
, ACTION_REBOOT
, ACTION_HALT
)) {
9369 r
= logind_reboot(arg_action
);
9372 if (IN_SET(r
, -EOPNOTSUPP
, -EINPROGRESS
))
9373 /* requested operation is not
9374 * supported on the local system or
9375 * already in progress */
9377 /* on all other errors, try low-level operation */
9381 /* In order to minimize the difference between operation with and
9382 * without logind, we explicitly enable non-blocking mode for this,
9383 * as logind's shutdown operations are always non-blocking. */
9384 arg_no_block
= true;
9386 if (!arg_dry_run
&& !arg_force
)
9387 return start_with_fallback();
9389 assert(geteuid() == 0);
9392 if (sd_booted() > 0)
9393 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
9395 r
= utmp_put_shutdown();
9397 log_warning_errno(r
, "Failed to write utmp record: %m");
9404 r
= halt_now(arg_action
);
9405 return log_error_errno(r
, "Failed to reboot: %m");
9408 static int runlevel_main(void) {
9409 int r
, runlevel
, previous
;
9411 r
= utmp_get_runlevel(&runlevel
, &previous
);
9418 previous
<= 0 ? 'N' : previous
,
9419 runlevel
<= 0 ? 'N' : runlevel
);
9424 static int logind_cancel_shutdown(void) {
9426 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
9430 r
= acquire_bus(BUS_FULL
, &bus
);
9434 (void) logind_set_wall_message();
9436 r
= sd_bus_call_method(
9438 "org.freedesktop.login1",
9439 "/org/freedesktop/login1",
9440 "org.freedesktop.login1.Manager",
9441 "CancelScheduledShutdown",
9445 return log_warning_errno(r
, "Failed to talk to logind, shutdown hasn't been cancelled: %s", bus_error_message(&error
, r
));
9449 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
9450 "Not compiled with logind support, cannot cancel scheduled shutdowns.");
9454 static int run(int argc
, char *argv
[]) {
9457 setlocale(LC_ALL
, "");
9458 log_parse_environment();
9461 /* The journal merging logic potentially needs a lot of fds. */
9462 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE
);
9466 /* Explicitly not on_tty() to avoid setting cached value.
9467 * This becomes relevant for piping output which might be
9469 original_stdout_is_tty
= isatty(STDOUT_FILENO
);
9471 r
= parse_argv(argc
, argv
);
9475 if (arg_action
!= ACTION_SYSTEMCTL
&& running_in_chroot() > 0) {
9477 log_info("Running in chroot, ignoring request.");
9482 /* systemctl_main() will print an error message for the bus
9483 * connection, but only if it needs to */
9485 switch (arg_action
) {
9487 case ACTION_SYSTEMCTL
:
9488 r
= systemctl_main(argc
, argv
);
9491 /* Legacy command aliases set arg_action. They provide some fallbacks,
9492 * e.g. to tell sysvinit to reboot after you have installed systemd
9496 case ACTION_POWEROFF
:
9502 case ACTION_RUNLEVEL2
:
9503 case ACTION_RUNLEVEL3
:
9504 case ACTION_RUNLEVEL4
:
9505 case ACTION_RUNLEVEL5
:
9507 r
= start_with_fallback();
9512 r
= reload_with_fallback();
9515 case ACTION_CANCEL_SHUTDOWN
:
9516 r
= logind_cancel_shutdown();
9519 case ACTION_RUNLEVEL
:
9520 r
= runlevel_main();
9524 case ACTION_SUSPEND
:
9525 case ACTION_HIBERNATE
:
9526 case ACTION_HYBRID_SLEEP
:
9527 case ACTION_SUSPEND_THEN_HIBERNATE
:
9528 case ACTION_EMERGENCY
:
9529 case ACTION_DEFAULT
:
9530 /* systemctl verbs with no equivalent in the legacy commands.
9531 * These cannot appear in arg_action. Fall through. */
9533 case _ACTION_INVALID
:
9535 assert_not_reached("Unknown action");
9541 /* Note that we return r here, not 0, so that we can implement the LSB-like return codes */
9545 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);