1 /* SPDX-License-Identifier: LGPL-2.1+ */
10 #include <sys/prctl.h>
11 #include <sys/reboot.h>
15 #include "sd-daemon.h"
19 #include "alloc-util.h"
21 #include "bus-common-errors.h"
22 #include "bus-error.h"
23 #include "bus-message.h"
24 #include "bus-unit-procs.h"
25 #include "bus-unit-util.h"
27 #include "bus-wait-for-jobs.h"
28 #include "bus-wait-for-units.h"
29 #include "cgroup-show.h"
30 #include "cgroup-util.h"
32 #include "cpu-set-util.h"
33 #include "dirent-util.h"
35 #include "efi-loader.h"
39 #include "exec-util.h"
40 #include "exit-status.h"
42 #include "format-table.h"
43 #include "format-util.h"
45 #include "glob-util.h"
46 #include "hexdecoct.h"
47 #include "hostname-util.h"
48 #include "in-addr-util.h"
52 #include "journal-util.h"
54 #include "locale-util.h"
56 #include "logs-show.h"
58 #include "main-func.h"
59 #include "memory-util.h"
61 #include "numa-util.h"
63 #include "parse-util.h"
64 #include "path-lookup.h"
65 #include "path-util.h"
66 #include "pretty-print.h"
67 #include "proc-cmdline.h"
68 #include "process-util.h"
69 #include "reboot-util.h"
70 #include "rlimit-util.h"
73 #include "signal-util.h"
74 #include "socket-util.h"
75 #include "sort-util.h"
76 #include "spawn-ask-password-agent.h"
77 #include "spawn-polkit-agent.h"
79 #include "stat-util.h"
80 #include "string-table.h"
82 #include "sysv-compat.h"
83 #include "terminal-util.h"
84 #include "tmpfile-util.h"
86 #include "unit-file.h"
87 #include "unit-name.h"
88 #include "user-util.h"
90 #include "utmp-wtmp.h"
94 static char **arg_types
= NULL
;
95 static char **arg_states
= NULL
;
96 static char **arg_properties
= NULL
;
97 static bool arg_all
= false;
98 static enum dependency
{
104 } arg_dependency
= DEPENDENCY_FORWARD
;
105 static const char *arg_job_mode
= "replace";
106 static UnitFileScope arg_scope
= UNIT_FILE_SYSTEM
;
107 static bool arg_wait
= false;
108 static bool arg_no_block
= false;
109 static bool arg_no_legend
= false;
110 static PagerFlags arg_pager_flags
= 0;
111 static bool arg_no_wtmp
= false;
112 static bool arg_no_sync
= false;
113 static bool arg_no_wall
= false;
114 static bool arg_no_reload
= false;
115 static bool arg_value
= false;
116 static bool arg_show_types
= false;
117 static bool arg_ignore_inhibitors
= false;
118 static bool arg_dry_run
= false;
119 static bool arg_quiet
= false;
120 static bool arg_full
= false;
121 static bool arg_recursive
= false;
122 static bool arg_with_dependencies
= false;
123 static bool arg_show_transaction
= false;
124 static int arg_force
= 0;
125 static bool arg_ask_password
= false;
126 static bool arg_runtime
= false;
127 static UnitFilePresetMode arg_preset_mode
= UNIT_FILE_PRESET_FULL
;
128 static char **arg_wall
= NULL
;
129 static const char *arg_kill_who
= NULL
;
130 static int arg_signal
= SIGTERM
;
131 static char *arg_root
= NULL
;
132 static usec_t arg_when
= 0;
143 ACTION_SUSPEND_THEN_HIBERNATE
,
154 ACTION_CANCEL_SHUTDOWN
,
157 } arg_action
= ACTION_SYSTEMCTL
;
158 static BusTransport arg_transport
= BUS_TRANSPORT_LOCAL
;
159 static const char *arg_host
= NULL
;
160 static unsigned arg_lines
= 10;
161 static OutputMode arg_output
= OUTPUT_SHORT
;
162 static bool arg_plain
= false;
163 static bool arg_firmware_setup
= false;
164 static usec_t arg_boot_loader_menu
= USEC_INFINITY
;
165 static const char *arg_boot_loader_entry
= NULL
;
166 static bool arg_now
= false;
167 static bool arg_jobs_before
= false;
168 static bool arg_jobs_after
= false;
169 static char **arg_clean_what
= NULL
;
171 /* This is a global cache that will be constructed on first use. */
172 static Hashmap
*cached_id_map
= NULL
;
173 static Hashmap
*cached_name_map
= NULL
;
175 STATIC_DESTRUCTOR_REGISTER(arg_wall
, strv_freep
);
176 STATIC_DESTRUCTOR_REGISTER(arg_root
, freep
);
177 STATIC_DESTRUCTOR_REGISTER(arg_types
, strv_freep
);
178 STATIC_DESTRUCTOR_REGISTER(arg_states
, strv_freep
);
179 STATIC_DESTRUCTOR_REGISTER(arg_properties
, strv_freep
);
180 STATIC_DESTRUCTOR_REGISTER(arg_clean_what
, strv_freep
);
181 STATIC_DESTRUCTOR_REGISTER(cached_id_map
, hashmap_freep
);
182 STATIC_DESTRUCTOR_REGISTER(cached_name_map
, hashmap_freep
);
184 static int daemon_reload(int argc
, char *argv
[], void* userdata
);
185 static int trivial_method(int argc
, char *argv
[], void *userdata
);
186 static int halt_now(enum action a
);
187 static int get_state_one_unit(sd_bus
*bus
, const char *name
, UnitActiveState
*active_state
);
189 static bool original_stdout_is_tty
;
191 typedef enum BusFocus
{
192 BUS_FULL
, /* The full bus indicated via --system or --user */
193 BUS_MANAGER
, /* The manager itself, possibly directly, possibly via the bus */
197 static sd_bus
*buses
[_BUS_FOCUS_MAX
] = {};
199 static UnitFileFlags
args_to_flags(void) {
200 return (arg_runtime
? UNIT_FILE_RUNTIME
: 0) |
201 (arg_force
? UNIT_FILE_FORCE
: 0);
204 static int acquire_bus(BusFocus focus
, sd_bus
**ret
) {
207 assert(focus
< _BUS_FOCUS_MAX
);
210 /* We only go directly to the manager, if we are using a local transport */
211 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
214 if (getenv_bool("SYSTEMCTL_FORCE_BUS") > 0)
220 user
= arg_scope
!= UNIT_FILE_SYSTEM
;
222 if (focus
== BUS_MANAGER
)
223 r
= bus_connect_transport_systemd(arg_transport
, arg_host
, user
, &buses
[focus
]);
225 r
= bus_connect_transport(arg_transport
, arg_host
, user
, &buses
[focus
]);
227 return log_error_errno(r
, "Failed to connect to bus: %m");
229 (void) sd_bus_set_allow_interactive_authorization(buses
[focus
], arg_ask_password
);
236 static void release_busses(void) {
239 for (w
= 0; w
< _BUS_FOCUS_MAX
; w
++)
240 buses
[w
] = sd_bus_flush_close_unref(buses
[w
]);
243 static void ask_password_agent_open_maybe(void) {
244 /* Open the password agent as a child process if necessary */
249 if (arg_scope
!= UNIT_FILE_SYSTEM
)
252 ask_password_agent_open_if_enabled(arg_transport
, arg_ask_password
);
255 static void polkit_agent_open_maybe(void) {
256 /* Open the polkit agent as a child process if necessary */
258 if (arg_scope
!= UNIT_FILE_SYSTEM
)
261 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
264 static OutputFlags
get_output_flags(void) {
266 arg_all
* OUTPUT_SHOW_ALL
|
267 (arg_full
|| !on_tty() || pager_have()) * OUTPUT_FULL_WIDTH
|
268 colors_enabled() * OUTPUT_COLOR
|
269 !arg_quiet
* OUTPUT_WARN_CUTOFF
;
272 static int translate_bus_error_to_exit_status(int r
, const sd_bus_error
*error
) {
275 if (!sd_bus_error_is_set(error
))
278 if (sd_bus_error_has_name(error
, SD_BUS_ERROR_ACCESS_DENIED
) ||
279 sd_bus_error_has_name(error
, BUS_ERROR_ONLY_BY_DEPENDENCY
) ||
280 sd_bus_error_has_name(error
, BUS_ERROR_NO_ISOLATION
) ||
281 sd_bus_error_has_name(error
, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE
))
282 return EXIT_NOPERMISSION
;
284 if (sd_bus_error_has_name(error
, BUS_ERROR_NO_SUCH_UNIT
))
285 return EXIT_NOTINSTALLED
;
287 if (sd_bus_error_has_name(error
, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE
) ||
288 sd_bus_error_has_name(error
, SD_BUS_ERROR_NOT_SUPPORTED
))
289 return EXIT_NOTIMPLEMENTED
;
291 if (sd_bus_error_has_name(error
, BUS_ERROR_LOAD_FAILED
))
292 return EXIT_NOTCONFIGURED
;
300 static bool install_client_side(void) {
301 /* Decides when to execute enable/disable/... operations
302 * client-side rather than server-side. */
304 if (running_in_chroot_or_offline())
307 if (sd_booted() <= 0)
310 if (!isempty(arg_root
))
313 if (arg_scope
== UNIT_FILE_GLOBAL
)
316 /* Unsupported environment variable, mostly for debugging purposes */
317 if (getenv_bool("SYSTEMCTL_INSTALL_CLIENT_SIDE") > 0)
323 static int compare_unit_info(const UnitInfo
*a
, const UnitInfo
*b
) {
327 /* First, order by machine */
328 if (!a
->machine
&& b
->machine
)
330 if (a
->machine
&& !b
->machine
)
332 if (a
->machine
&& b
->machine
) {
333 r
= strcasecmp(a
->machine
, b
->machine
);
338 /* Second, order by unit type */
339 d1
= strrchr(a
->id
, '.');
340 d2
= strrchr(b
->id
, '.');
342 r
= strcasecmp(d1
, d2
);
347 /* Third, order by name */
348 return strcasecmp(a
->id
, b
->id
);
351 static const char* unit_type_suffix(const char *name
) {
354 dot
= strrchr(name
, '.');
361 static bool output_show_unit(const UnitInfo
*u
, char **patterns
) {
364 if (!strv_fnmatch_or_empty(patterns
, u
->id
, FNM_NOESCAPE
))
367 if (arg_types
&& !strv_find(arg_types
, unit_type_suffix(u
->id
)))
373 /* Note that '--all' is not purely a state filter, but also a
374 * filter that hides units that "follow" other units (which is
375 * used for device units that appear under different names). */
376 if (!isempty(u
->following
))
379 if (!strv_isempty(arg_states
))
382 /* By default show all units except the ones in inactive
383 * state and with no pending job */
387 if (streq(u
->active_state
, "inactive"))
393 static int output_table(Table
*table
) {
398 if (OUTPUT_MODE_IS_JSON(arg_output
))
399 r
= table_print_json(table
, NULL
, output_mode_to_json_format_flags(arg_output
) | JSON_FORMAT_COLOR_AUTO
);
401 r
= table_print(table
, NULL
);
403 return log_error_errno(r
, "Failed to show table: %m");
408 static int output_units_list(const UnitInfo
*unit_infos
, unsigned c
) {
409 _cleanup_(table_unrefp
) Table
*table
= NULL
;
414 table
= table_new("", "unit", "load", "active", "sub", "job", "description");
418 table_set_header(table
, !arg_no_legend
);
420 /* Hide the 'glyph' column when --plain is requested */
421 r
= table_hide_column_from_display(table
, 0);
423 return log_error_errno(r
, "Failed to hide column: %m");
426 table_set_width(table
, 0);
428 (void) table_set_empty_string(table
, "-");
430 for (u
= unit_infos
; unit_infos
&& u
< unit_infos
+ c
; u
++) {
431 _cleanup_free_
char *j
= NULL
;
432 const char *on_underline
= "", *on_loaded
= "", *on_active
= "";
433 const char *on_circle
= "", *id
;
434 bool circle
= false, underline
= false;
436 if (u
+ 1 < unit_infos
+ c
&&
437 !streq(unit_type_suffix(u
->id
), unit_type_suffix((u
+ 1)->id
))) {
438 on_underline
= ansi_underline();
442 if (STR_IN_SET(u
->load_state
, "error", "not-found", "bad-setting", "masked") && !arg_plain
) {
443 on_circle
= ansi_highlight_yellow();
445 on_loaded
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
446 } else if (streq(u
->active_state
, "failed") && !arg_plain
) {
447 on_circle
= ansi_highlight_red();
449 on_active
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
451 on_active
= on_underline
;
452 on_loaded
= on_underline
;
456 j
= strjoin(u
->machine
, ":", u
->id
);
464 r
= table_add_many(table
,
465 TABLE_STRING
, circle
? special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
) : " ",
466 TABLE_SET_COLOR
, on_circle
,
468 TABLE_SET_COLOR
, on_active
,
469 TABLE_STRING
, u
->load_state
,
470 TABLE_SET_COLOR
, on_loaded
,
471 TABLE_STRING
, u
->active_state
,
472 TABLE_SET_COLOR
, on_active
,
473 TABLE_STRING
, u
->sub_state
,
474 TABLE_SET_COLOR
, on_active
,
475 TABLE_STRING
, u
->job_id
? u
->job_type
: "",
476 TABLE_SET_COLOR
, u
->job_id
? on_underline
: "",
477 TABLE_STRING
, u
->description
,
478 TABLE_SET_COLOR
, on_underline
);
480 return table_log_add_error(r
);
486 if (job_count
== 0) {
487 /* There's no data in the JOB column, so let's hide it */
488 r
= table_hide_column_from_display(table
, 5);
490 return log_error_errno(r
, "Failed to hide column: %m");
493 r
= output_table(table
);
497 if (!arg_no_legend
) {
498 const char *on
, *off
;
499 size_t records
= table_get_rows(table
) - 1;
503 "LOAD = Reflects whether the unit definition was properly loaded.\n"
504 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
505 "SUB = The low-level unit activation state, values depend on unit type.");
506 puts(job_count
? "JOB = Pending job for the unit.\n" : "");
507 on
= ansi_highlight();
510 on
= ansi_highlight_red();
514 if (arg_all
|| strv_contains(arg_states
, "inactive"))
515 printf("%s%zu loaded units listed.%s\n"
516 "To show all installed unit files use 'systemctl list-unit-files'.\n",
518 else if (!arg_states
)
519 printf("%s%zu loaded units listed.%s Pass --all to see loaded but inactive units, too.\n"
520 "To show all installed unit files use 'systemctl list-unit-files'.\n",
523 printf("%zu loaded units listed.\n", records
);
529 static int get_unit_list(
533 UnitInfo
**unit_infos
,
535 sd_bus_message
**_reply
) {
537 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
538 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
539 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
543 bool fallback
= false;
549 r
= sd_bus_message_new_method_call(
552 "org.freedesktop.systemd1",
553 "/org/freedesktop/systemd1",
554 "org.freedesktop.systemd1.Manager",
555 "ListUnitsByPatterns");
557 return bus_log_create_error(r
);
559 r
= sd_bus_message_append_strv(m
, arg_states
);
561 return bus_log_create_error(r
);
563 r
= sd_bus_message_append_strv(m
, patterns
);
565 return bus_log_create_error(r
);
567 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
568 if (r
< 0 && (sd_bus_error_has_name(&error
, SD_BUS_ERROR_UNKNOWN_METHOD
) ||
569 sd_bus_error_has_name(&error
, SD_BUS_ERROR_ACCESS_DENIED
))) {
570 /* Fallback to legacy ListUnitsFiltered method */
572 log_debug_errno(r
, "Failed to list units: %s Falling back to ListUnitsFiltered method.", bus_error_message(&error
, r
));
573 m
= sd_bus_message_unref(m
);
574 sd_bus_error_free(&error
);
576 r
= sd_bus_message_new_method_call(
579 "org.freedesktop.systemd1",
580 "/org/freedesktop/systemd1",
581 "org.freedesktop.systemd1.Manager",
582 "ListUnitsFiltered");
584 return bus_log_create_error(r
);
586 r
= sd_bus_message_append_strv(m
, arg_states
);
588 return bus_log_create_error(r
);
590 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
593 return log_error_errno(r
, "Failed to list units: %s", bus_error_message(&error
, r
));
595 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssssouso)");
597 return bus_log_parse_error(r
);
599 while ((r
= bus_parse_unit_info(reply
, &u
)) > 0) {
602 if (!output_show_unit(&u
, fallback
? patterns
: NULL
))
605 if (!GREEDY_REALLOC(*unit_infos
, size
, c
+1))
608 (*unit_infos
)[c
++] = u
;
611 return bus_log_parse_error(r
);
613 r
= sd_bus_message_exit_container(reply
);
615 return bus_log_parse_error(r
);
617 *_reply
= TAKE_PTR(reply
);
622 static void message_set_freep(Set
**set
) {
623 set_free_with_destructor(*set
, sd_bus_message_unref
);
626 static int get_unit_list_recursive(
629 UnitInfo
**_unit_infos
,
633 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
634 _cleanup_(message_set_freep
) Set
*replies
;
635 sd_bus_message
*reply
;
643 replies
= set_new(NULL
);
647 c
= get_unit_list(bus
, NULL
, patterns
, &unit_infos
, 0, &reply
);
651 r
= set_put(replies
, reply
);
653 sd_bus_message_unref(reply
);
658 _cleanup_strv_free_
char **machines
= NULL
;
661 r
= sd_get_machine_names(&machines
);
663 return log_error_errno(r
, "Failed to get machine names: %m");
665 STRV_FOREACH(i
, machines
) {
666 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*container
= NULL
;
669 r
= sd_bus_open_system_machine(&container
, *i
);
671 log_warning_errno(r
, "Failed to connect to container %s, ignoring: %m", *i
);
675 k
= get_unit_list(container
, *i
, patterns
, &unit_infos
, c
, &reply
);
681 r
= set_put(replies
, reply
);
683 sd_bus_message_unref(reply
);
688 *_machines
= TAKE_PTR(machines
);
692 *_unit_infos
= TAKE_PTR(unit_infos
);
693 *_replies
= TAKE_PTR(replies
);
698 static int expand_names(sd_bus
*bus
, char **names
, const char* suffix
, char ***ret
, bool *ret_expanded
) {
699 _cleanup_strv_free_
char **mangled
= NULL
, **globs
= NULL
;
706 STRV_FOREACH(name
, names
) {
708 UnitNameMangle options
= UNIT_NAME_MANGLE_GLOB
| (arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
);
710 r
= unit_name_mangle_with_suffix(*name
, NULL
, options
, suffix
?: ".service", &t
);
712 return log_error_errno(r
, "Failed to mangle name: %m");
714 if (string_is_glob(t
))
715 r
= strv_consume(&globs
, t
);
717 r
= strv_consume(&mangled
, t
);
722 /* Query the manager only if any of the names are a glob, since
723 * this is fairly expensive */
724 bool expanded
= !strv_isempty(globs
);
726 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
727 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
730 r
= get_unit_list(bus
, NULL
, globs
, &unit_infos
, 0, &reply
);
734 n
= strv_length(mangled
);
737 for (i
= 0; i
< r
; i
++) {
738 if (!GREEDY_REALLOC(mangled
, allocated
, n
+2))
741 mangled
[n
] = strdup(unit_infos
[i
].id
);
750 *ret_expanded
= expanded
;
752 *ret
= TAKE_PTR(mangled
);
756 static int list_dependencies_get_dependencies(sd_bus
*bus
, const char *name
, char ***ret
) {
757 _cleanup_strv_free_
char **deps
= NULL
;
759 static const struct bus_properties_map map
[_DEPENDENCY_MAX
][6] = {
760 [DEPENDENCY_FORWARD
] = {
761 { "Requires", "as", NULL
, 0 },
762 { "Requisite", "as", NULL
, 0 },
763 { "Wants", "as", NULL
, 0 },
764 { "ConsistsOf", "as", NULL
, 0 },
765 { "BindsTo", "as", NULL
, 0 },
768 [DEPENDENCY_REVERSE
] = {
769 { "RequiredBy", "as", NULL
, 0 },
770 { "RequisiteOf", "as", NULL
, 0 },
771 { "WantedBy", "as", NULL
, 0 },
772 { "PartOf", "as", NULL
, 0 },
773 { "BoundBy", "as", NULL
, 0 },
776 [DEPENDENCY_AFTER
] = {
777 { "After", "as", NULL
, 0 },
780 [DEPENDENCY_BEFORE
] = {
781 { "Before", "as", NULL
, 0 },
786 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
787 _cleanup_free_
char *dbus_path
= NULL
;
794 dbus_path
= unit_dbus_path_from_name(name
);
798 r
= bus_map_all_properties(bus
,
799 "org.freedesktop.systemd1",
807 return log_error_errno(r
, "Failed to get properties of %s: %s", name
, bus_error_message(&error
, r
));
809 strv_uniq(deps
); /* Sometimes a unit might have multiple deps on the other unit,
810 * but we still want to show it just once. */
811 *ret
= TAKE_PTR(deps
);
816 static int append_unit_dependencies(sd_bus
*bus
, char **names
, char ***ret
) {
817 _cleanup_strv_free_
char **with_deps
= NULL
;
823 STRV_FOREACH(name
, names
) {
824 _cleanup_strv_free_
char **deps
= NULL
;
826 if (strv_extend(&with_deps
, *name
) < 0)
829 (void) list_dependencies_get_dependencies(bus
, *name
, &deps
);
831 if (strv_extend_strv(&with_deps
, deps
, true) < 0)
835 *ret
= TAKE_PTR(with_deps
);
840 static int maybe_extend_with_unit_dependencies(sd_bus
*bus
, char ***list
) {
844 if (arg_with_dependencies
) {
846 _cleanup_strv_free_
char **list_with_deps
= NULL
;
848 r
= append_unit_dependencies(bus
, *list
, &list_with_deps
);
850 return log_error_errno(r
, "Failed to append unit dependencies: %m");
853 *list
= TAKE_PTR(list_with_deps
);
859 static int list_units(int argc
, char *argv
[], void *userdata
) {
860 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
861 _cleanup_(message_set_freep
) Set
*replies
= NULL
;
862 _cleanup_strv_free_
char **machines
= NULL
;
866 r
= acquire_bus(BUS_MANAGER
, &bus
);
870 (void) pager_open(arg_pager_flags
);
872 if (arg_with_dependencies
) {
873 _cleanup_strv_free_
char **names
= NULL
;
875 r
= append_unit_dependencies(bus
, strv_skip(argv
, 1), &names
);
879 r
= get_unit_list_recursive(bus
, names
, &unit_infos
, &replies
, &machines
);
883 r
= get_unit_list_recursive(bus
, strv_skip(argv
, 1), &unit_infos
, &replies
, &machines
);
888 typesafe_qsort(unit_infos
, r
, compare_unit_info
);
889 return output_units_list(unit_infos
, r
);
892 static int get_triggered_units(
897 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
904 r
= sd_bus_get_property_strv(
906 "org.freedesktop.systemd1",
908 "org.freedesktop.systemd1.Unit",
913 return log_error_errno(r
, "Failed to determine triggers: %s", bus_error_message(&error
, r
));
918 static int get_listening(
920 const char* unit_path
,
923 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
924 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
925 const char *type
, *path
;
928 r
= sd_bus_get_property(
930 "org.freedesktop.systemd1",
932 "org.freedesktop.systemd1.Socket",
938 return log_error_errno(r
, "Failed to get list of listening sockets: %s", bus_error_message(&error
, r
));
940 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ss)");
942 return bus_log_parse_error(r
);
944 while ((r
= sd_bus_message_read(reply
, "(ss)", &type
, &path
)) > 0) {
946 r
= strv_extend(listening
, type
);
950 r
= strv_extend(listening
, path
);
957 return bus_log_parse_error(r
);
959 r
= sd_bus_message_exit_container(reply
);
961 return bus_log_parse_error(r
);
973 /* Note: triggered is a list here, although it almost certainly
974 * will always be one unit. Nevertheless, dbus API allows for multiple
975 * values, so let's follow that. */
978 /* The strv above is shared. free is set only in the first one. */
982 static int socket_info_compare(const struct socket_info
*a
, const struct socket_info
*b
) {
988 if (!a
->machine
&& b
->machine
)
990 if (a
->machine
&& !b
->machine
)
992 if (a
->machine
&& b
->machine
) {
993 r
= strcasecmp(a
->machine
, b
->machine
);
998 r
= strcmp(a
->path
, b
->path
);
1000 r
= strcmp(a
->type
, b
->type
);
1005 static int output_sockets_list(struct socket_info
*socket_infos
, unsigned cs
) {
1006 _cleanup_(table_unrefp
) Table
*table
= NULL
;
1007 struct socket_info
*s
;
1008 const char *on
, *off
;
1011 table
= table_new("listen", "type", "unit", "activates");
1015 if (!arg_show_types
) {
1016 /* Hide the second (TYPE) column */
1017 r
= table_set_display(table
, (size_t) 0, (size_t) 2, (size_t) 3, (size_t) -1);
1019 return log_error_errno(r
, "Failed to set columns to display: %m");
1022 table_set_header(table
, !arg_no_legend
);
1024 table_set_width(table
, 0);
1026 (void) table_set_empty_string(table
, "-");
1029 for (s
= socket_infos
; s
< socket_infos
+ cs
; s
++) {
1030 _cleanup_free_
char *j
= NULL
, *activates
= NULL
;
1034 j
= strjoin(s
->machine
, ":", s
->path
);
1041 activates
= strv_join(s
->triggered
, ", ");
1045 r
= table_add_many(table
,
1047 TABLE_STRING
, s
->type
,
1048 TABLE_STRING
, s
->id
,
1049 TABLE_STRING
, activates
);
1051 return table_log_add_error(r
);
1054 on
= ansi_highlight();
1055 off
= ansi_normal();
1057 on
= ansi_highlight_red();
1058 off
= ansi_normal();
1061 r
= output_table(table
);
1065 if (!arg_no_legend
) {
1066 printf("\n%s%u sockets listed.%s\n", on
, cs
, off
);
1068 printf("Pass --all to see loaded but inactive sockets, too.\n");
1074 static int list_sockets(int argc
, char *argv
[], void *userdata
) {
1075 _cleanup_(message_set_freep
) Set
*replies
= NULL
;
1076 _cleanup_strv_free_
char **machines
= NULL
;
1077 _cleanup_strv_free_
char **sockets_with_suffix
= NULL
;
1078 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
1079 _cleanup_free_
struct socket_info
*socket_infos
= NULL
;
1081 struct socket_info
*s
;
1087 r
= acquire_bus(BUS_MANAGER
, &bus
);
1091 (void) pager_open(arg_pager_flags
);
1093 r
= expand_names(bus
, strv_skip(argv
, 1), ".socket", &sockets_with_suffix
, NULL
);
1097 if (argc
== 1 || sockets_with_suffix
) {
1098 n
= get_unit_list_recursive(bus
, sockets_with_suffix
, &unit_infos
, &replies
, &machines
);
1102 for (u
= unit_infos
; u
< unit_infos
+ n
; u
++) {
1103 _cleanup_strv_free_
char **listening
= NULL
, **triggered
= NULL
;
1106 if (!endswith(u
->id
, ".socket"))
1109 r
= get_triggered_units(bus
, u
->unit_path
, &triggered
);
1113 c
= get_listening(bus
, u
->unit_path
, &listening
);
1119 if (!GREEDY_REALLOC(socket_infos
, size
, cs
+ c
)) {
1124 for (i
= 0; i
< c
; i
++)
1125 socket_infos
[cs
+ i
] = (struct socket_info
) {
1126 .machine
= u
->machine
,
1128 .type
= listening
[i
*2],
1129 .path
= listening
[i
*2 + 1],
1130 .triggered
= triggered
,
1131 .own_triggered
= i
==0,
1134 /* from this point on we will cleanup those socket_infos */
1137 listening
= triggered
= NULL
; /* avoid cleanup */
1140 typesafe_qsort(socket_infos
, cs
, socket_info_compare
);
1143 output_sockets_list(socket_infos
, cs
);
1146 assert(cs
== 0 || socket_infos
);
1147 for (s
= socket_infos
; s
< socket_infos
+ cs
; s
++) {
1150 if (s
->own_triggered
)
1151 strv_free(s
->triggered
);
1157 static int get_next_elapse(
1160 dual_timestamp
*next
) {
1162 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1170 r
= sd_bus_get_property_trivial(
1172 "org.freedesktop.systemd1",
1174 "org.freedesktop.systemd1.Timer",
1175 "NextElapseUSecMonotonic",
1180 return log_error_errno(r
, "Failed to get next elapse time: %s", bus_error_message(&error
, r
));
1182 r
= sd_bus_get_property_trivial(
1184 "org.freedesktop.systemd1",
1186 "org.freedesktop.systemd1.Timer",
1187 "NextElapseUSecRealtime",
1192 return log_error_errno(r
, "Failed to get next elapse time: %s", bus_error_message(&error
, r
));
1198 static int get_last_trigger(
1203 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1210 r
= sd_bus_get_property_trivial(
1212 "org.freedesktop.systemd1",
1214 "org.freedesktop.systemd1.Timer",
1220 return log_error_errno(r
, "Failed to get last trigger time: %s", bus_error_message(&error
, r
));
1226 const char* machine
;
1229 usec_t last_trigger
;
1233 static int timer_info_compare(const struct timer_info
*a
, const struct timer_info
*b
) {
1239 if (!a
->machine
&& b
->machine
)
1241 if (a
->machine
&& !b
->machine
)
1243 if (a
->machine
&& b
->machine
) {
1244 r
= strcasecmp(a
->machine
, b
->machine
);
1249 r
= CMP(a
->next_elapse
, b
->next_elapse
);
1253 return strcmp(a
->id
, b
->id
);
1256 static int output_timers_list(struct timer_info
*timer_infos
, unsigned n
) {
1257 _cleanup_(table_unrefp
) Table
*table
= NULL
;
1258 struct timer_info
*t
;
1259 const char *on
, *off
;
1262 assert(timer_infos
|| n
== 0);
1264 table
= table_new("next", "left", "last", "passed", "unit", "activates");
1268 table_set_header(table
, !arg_no_legend
);
1270 table_set_width(table
, 0);
1272 (void) table_set_empty_string(table
, "-");
1275 for (t
= timer_infos
; t
< timer_infos
+ n
; t
++) {
1276 _cleanup_free_
char *j
= NULL
, *activates
= NULL
;
1280 j
= strjoin(t
->machine
, ":", t
->id
);
1287 activates
= strv_join(t
->triggered
, ", ");
1291 r
= table_add_many(table
,
1292 TABLE_TIMESTAMP
, t
->next_elapse
,
1293 TABLE_TIMESTAMP_RELATIVE
, t
->next_elapse
,
1294 TABLE_TIMESTAMP
, t
->last_trigger
,
1295 TABLE_TIMESTAMP_RELATIVE
, t
->last_trigger
,
1297 TABLE_STRING
, activates
);
1299 return table_log_add_error(r
);
1302 on
= ansi_highlight();
1303 off
= ansi_normal();
1305 on
= ansi_highlight_red();
1306 off
= ansi_normal();
1309 r
= output_table(table
);
1313 if (!arg_no_legend
) {
1314 printf("\n%s%u timers listed.%s\n", on
, n
, off
);
1316 printf("Pass --all to see loaded but inactive timers, too.\n");
1322 static usec_t
calc_next_elapse(dual_timestamp
*nw
, dual_timestamp
*next
) {
1328 if (timestamp_is_set(next
->monotonic
)) {
1331 if (next
->monotonic
> nw
->monotonic
)
1332 converted
= nw
->realtime
+ (next
->monotonic
- nw
->monotonic
);
1334 converted
= nw
->realtime
- (nw
->monotonic
- next
->monotonic
);
1336 if (timestamp_is_set(next
->realtime
))
1337 next_elapse
= MIN(converted
, next
->realtime
);
1339 next_elapse
= converted
;
1342 next_elapse
= next
->realtime
;
1347 static int list_timers(int argc
, char *argv
[], void *userdata
) {
1348 _cleanup_(message_set_freep
) Set
*replies
= NULL
;
1349 _cleanup_strv_free_
char **machines
= NULL
;
1350 _cleanup_strv_free_
char **timers_with_suffix
= NULL
;
1351 _cleanup_free_
struct timer_info
*timer_infos
= NULL
;
1352 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
1353 struct timer_info
*t
;
1361 r
= acquire_bus(BUS_MANAGER
, &bus
);
1365 (void) pager_open(arg_pager_flags
);
1367 r
= expand_names(bus
, strv_skip(argv
, 1), ".timer", &timers_with_suffix
, NULL
);
1371 if (argc
== 1 || timers_with_suffix
) {
1372 n
= get_unit_list_recursive(bus
, timers_with_suffix
, &unit_infos
, &replies
, &machines
);
1376 dual_timestamp_get(&nw
);
1378 for (u
= unit_infos
; u
< unit_infos
+ n
; u
++) {
1379 _cleanup_strv_free_
char **triggered
= NULL
;
1380 dual_timestamp next
= DUAL_TIMESTAMP_NULL
;
1383 if (!endswith(u
->id
, ".timer"))
1386 r
= get_triggered_units(bus
, u
->unit_path
, &triggered
);
1390 r
= get_next_elapse(bus
, u
->unit_path
, &next
);
1394 get_last_trigger(bus
, u
->unit_path
, &last
);
1396 if (!GREEDY_REALLOC(timer_infos
, size
, c
+1)) {
1401 m
= calc_next_elapse(&nw
, &next
);
1403 timer_infos
[c
++] = (struct timer_info
) {
1404 .machine
= u
->machine
,
1407 .last_trigger
= last
,
1408 .triggered
= TAKE_PTR(triggered
),
1412 typesafe_qsort(timer_infos
, c
, timer_info_compare
);
1415 output_timers_list(timer_infos
, c
);
1418 for (t
= timer_infos
; t
< timer_infos
+ c
; t
++)
1419 strv_free(t
->triggered
);
1424 static int compare_unit_file_list(const UnitFileList
*a
, const UnitFileList
*b
) {
1425 const char *d1
, *d2
;
1427 d1
= strrchr(a
->path
, '.');
1428 d2
= strrchr(b
->path
, '.');
1433 r
= strcasecmp(d1
, d2
);
1438 return strcasecmp(basename(a
->path
), basename(b
->path
));
1441 static bool output_show_unit_file(const UnitFileList
*u
, char **states
, char **patterns
) {
1444 if (!strv_fnmatch_or_empty(patterns
, basename(u
->path
), FNM_NOESCAPE
))
1447 if (!strv_isempty(arg_types
)) {
1450 dot
= strrchr(u
->path
, '.');
1454 if (!strv_find(arg_types
, dot
+1))
1458 if (!strv_isempty(states
) &&
1459 !strv_find(states
, unit_file_state_to_string(u
->state
)))
1465 static bool show_preset_for_state(UnitFileState state
) {
1466 /* Don't show preset state in those unit file states, it'll only confuse users. */
1467 return !IN_SET(state
,
1470 UNIT_FILE_GENERATED
,
1471 UNIT_FILE_TRANSIENT
);
1474 static int output_unit_file_list(const UnitFileList
*units
, unsigned c
) {
1475 _cleanup_(table_unrefp
) Table
*table
= NULL
;
1476 _cleanup_(unit_file_presets_freep
) UnitFilePresets presets
= {};
1479 table
= table_new("unit file", "state", "vendor preset");
1483 table_set_header(table
, !arg_no_legend
);
1485 table_set_width(table
, 0);
1487 (void) table_set_empty_string(table
, "-");
1489 for (const UnitFileList
*u
= units
; u
< units
+ c
; u
++) {
1490 const char *on_underline
= NULL
, *on_unit_color
= NULL
, *id
;
1493 underline
= u
+ 1 < units
+ c
&&
1494 !streq(unit_type_suffix(u
->path
), unit_type_suffix((u
+ 1)->path
));
1497 on_underline
= ansi_underline();
1499 if (IN_SET(u
->state
,
1501 UNIT_FILE_MASKED_RUNTIME
,
1504 on_unit_color
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
1505 else if (IN_SET(u
->state
,
1508 on_unit_color
= underline
? ansi_highlight_green_underline() : ansi_highlight_green();
1510 on_unit_color
= on_underline
;
1512 id
= basename(u
->path
);
1514 r
= table_add_many(table
,
1516 TABLE_SET_COLOR
, strempty(on_underline
),
1517 TABLE_STRING
, unit_file_state_to_string(u
->state
),
1518 TABLE_SET_COLOR
, strempty(on_unit_color
));
1520 return table_log_add_error(r
);
1522 if (show_preset_for_state(u
->state
)) {
1523 const char *unit_preset_str
, *on_preset_color
;
1525 r
= unit_file_query_preset(arg_scope
, arg_root
, id
, &presets
);
1527 unit_preset_str
= "n/a";
1528 on_preset_color
= underline
? on_underline
: ansi_normal();
1529 } else if (r
== 0) {
1530 unit_preset_str
= "disabled";
1531 on_preset_color
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
1533 unit_preset_str
= "enabled";
1534 on_preset_color
= underline
? ansi_highlight_green_underline() : ansi_highlight_green();
1537 r
= table_add_many(table
,
1538 TABLE_STRING
, unit_preset_str
,
1539 TABLE_SET_COLOR
, strempty(on_preset_color
));
1541 r
= table_add_many(table
, TABLE_EMPTY
);
1544 return table_log_add_error(r
);
1547 r
= output_table(table
);
1552 printf("\n%u unit files listed.\n", c
);
1557 static int list_unit_files(int argc
, char *argv
[], void *userdata
) {
1558 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1559 _cleanup_free_ UnitFileList
*units
= NULL
;
1566 bool fallback
= false;
1568 if (install_client_side()) {
1574 h
= hashmap_new(&string_hash_ops
);
1578 r
= unit_file_get_list(arg_scope
, arg_root
, h
, arg_states
, strv_skip(argv
, 1));
1580 unit_file_list_free(h
);
1581 return log_error_errno(r
, "Failed to get unit file list: %m");
1584 n_units
= hashmap_size(h
);
1586 units
= new(UnitFileList
, n_units
?: 1); /* avoid malloc(0) */
1588 unit_file_list_free(h
);
1592 HASHMAP_FOREACH(u
, h
, i
) {
1593 if (!output_show_unit_file(u
, NULL
, NULL
))
1600 assert(c
<= n_units
);
1605 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
1606 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1609 r
= acquire_bus(BUS_MANAGER
, &bus
);
1613 r
= sd_bus_message_new_method_call(
1616 "org.freedesktop.systemd1",
1617 "/org/freedesktop/systemd1",
1618 "org.freedesktop.systemd1.Manager",
1619 "ListUnitFilesByPatterns");
1621 return bus_log_create_error(r
);
1623 r
= sd_bus_message_append_strv(m
, arg_states
);
1625 return bus_log_create_error(r
);
1627 if (arg_with_dependencies
) {
1628 _cleanup_strv_free_
char **names_with_deps
= NULL
;
1630 r
= append_unit_dependencies(bus
, strv_skip(argv
, 1), &names_with_deps
);
1632 return log_error_errno(r
, "Failed to append unit dependencies: %m");
1634 r
= sd_bus_message_append_strv(m
, names_with_deps
);
1636 return bus_log_create_error(r
);
1638 r
= sd_bus_message_append_strv(m
, strv_skip(argv
, 1));
1640 return bus_log_create_error(r
);
1643 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1644 if (r
< 0 && sd_bus_error_has_name(&error
, SD_BUS_ERROR_UNKNOWN_METHOD
)) {
1645 /* Fallback to legacy ListUnitFiles method */
1647 log_debug_errno(r
, "Failed to list unit files: %s Falling back to ListUnitsFiles method.", bus_error_message(&error
, r
));
1648 m
= sd_bus_message_unref(m
);
1649 sd_bus_error_free(&error
);
1651 r
= sd_bus_message_new_method_call(
1654 "org.freedesktop.systemd1",
1655 "/org/freedesktop/systemd1",
1656 "org.freedesktop.systemd1.Manager",
1659 return bus_log_create_error(r
);
1661 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1664 return log_error_errno(r
, "Failed to list unit files: %s", bus_error_message(&error
, r
));
1666 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ss)");
1668 return bus_log_parse_error(r
);
1670 while ((r
= sd_bus_message_read(reply
, "(ss)", &path
, &state
)) > 0) {
1672 if (!GREEDY_REALLOC(units
, size
, c
+ 1))
1675 units
[c
] = (struct UnitFileList
) {
1677 unit_file_state_from_string(state
)
1680 if (output_show_unit_file(&units
[c
],
1681 fallback
? arg_states
: NULL
,
1682 fallback
? strv_skip(argv
, 1) : NULL
))
1687 return bus_log_parse_error(r
);
1689 r
= sd_bus_message_exit_container(reply
);
1691 return bus_log_parse_error(r
);
1694 (void) pager_open(arg_pager_flags
);
1696 typesafe_qsort(units
, c
, compare_unit_file_list
);
1697 r
= output_unit_file_list(units
, c
);
1701 if (install_client_side())
1702 for (unit
= units
; unit
< units
+ c
; unit
++)
1711 static int list_dependencies_print(const char *name
, int level
, unsigned branches
, bool last
) {
1712 _cleanup_free_
char *n
= NULL
;
1713 size_t max_len
= MAX(columns(),20u);
1719 for (i
= level
- 1; i
>= 0; i
--) {
1721 if (len
> max_len
- 3 && !arg_full
) {
1722 printf("%s...\n",max_len
% 2 ? "" : " ");
1725 printf("%s", special_glyph(branches
& (1 << i
) ? SPECIAL_GLYPH_TREE_VERTICAL
: SPECIAL_GLYPH_TREE_SPACE
));
1729 if (len
> max_len
- 3 && !arg_full
) {
1730 printf("%s...\n",max_len
% 2 ? "" : " ");
1734 printf("%s", special_glyph(last
? SPECIAL_GLYPH_TREE_RIGHT
: SPECIAL_GLYPH_TREE_BRANCH
));
1738 printf("%s\n", name
);
1742 n
= ellipsize(name
, max_len
-len
, 100);
1750 static int list_dependencies_compare(char * const *a
, char * const *b
) {
1751 if (unit_name_to_type(*a
) == UNIT_TARGET
&& unit_name_to_type(*b
) != UNIT_TARGET
)
1753 if (unit_name_to_type(*a
) != UNIT_TARGET
&& unit_name_to_type(*b
) == UNIT_TARGET
)
1756 return strcasecmp(*a
, *b
);
1759 static int list_dependencies_one(
1764 unsigned branches
) {
1766 _cleanup_strv_free_
char **deps
= NULL
;
1774 r
= strv_extend(units
, name
);
1778 r
= list_dependencies_get_dependencies(bus
, name
, &deps
);
1782 typesafe_qsort(deps
, strv_length(deps
), list_dependencies_compare
);
1784 STRV_FOREACH(c
, deps
) {
1785 if (strv_contains(*units
, *c
)) {
1788 r
= list_dependencies_print("...", level
+ 1, (branches
<< 1) | (c
[1] == NULL
? 0 : 1), 1);
1798 UnitActiveState active_state
= _UNIT_ACTIVE_STATE_INVALID
;
1801 (void) get_state_one_unit(bus
, *c
, &active_state
);
1803 switch (active_state
) {
1805 case UNIT_RELOADING
:
1806 case UNIT_ACTIVATING
:
1807 on
= ansi_highlight_green();
1811 case UNIT_DEACTIVATING
:
1816 on
= ansi_highlight_red();
1820 printf("%s%s%s ", on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), ansi_normal());
1823 r
= list_dependencies_print(*c
, level
, branches
, c
[1] == NULL
);
1827 if (arg_all
|| unit_name_to_type(*c
) == UNIT_TARGET
) {
1828 r
= list_dependencies_one(bus
, *c
, level
+ 1, units
, (branches
<< 1) | (c
[1] == NULL
? 0 : 1));
1835 strv_remove(*units
, name
);
1840 static int list_dependencies(int argc
, char *argv
[], void *userdata
) {
1841 _cleanup_strv_free_
char **units
= NULL
, **done
= NULL
;
1842 char **u
, **patterns
;
1846 r
= acquire_bus(BUS_MANAGER
, &bus
);
1850 patterns
= strv_skip(argv
, 1);
1851 if (strv_isempty(patterns
)) {
1852 units
= strv_new(SPECIAL_DEFAULT_TARGET
);
1856 r
= expand_names(bus
, patterns
, NULL
, &units
, NULL
);
1858 return log_error_errno(r
, "Failed to expand names: %m");
1861 (void) pager_open(arg_pager_flags
);
1863 STRV_FOREACH(u
, units
) {
1868 r
= list_dependencies_one(bus
, *u
, 0, &done
, 0);
1876 struct machine_info
{
1880 char *control_group
;
1881 uint32_t n_failed_units
;
1886 static const struct bus_properties_map machine_info_property_map
[] = {
1887 { "SystemState", "s", NULL
, offsetof(struct machine_info
, state
) },
1888 { "NJobs", "u", NULL
, offsetof(struct machine_info
, n_jobs
) },
1889 { "NFailedUnits", "u", NULL
, offsetof(struct machine_info
, n_failed_units
) },
1890 { "ControlGroup", "s", NULL
, offsetof(struct machine_info
, control_group
) },
1891 { "UserspaceTimestamp", "t", NULL
, offsetof(struct machine_info
, timestamp
) },
1895 static void machine_info_clear(struct machine_info
*info
) {
1900 free(info
->control_group
);
1904 static void free_machines_list(struct machine_info
*machine_infos
, int n
) {
1910 for (i
= 0; i
< n
; i
++)
1911 machine_info_clear(&machine_infos
[i
]);
1913 free(machine_infos
);
1916 static int compare_machine_info(const struct machine_info
*a
, const struct machine_info
*b
) {
1919 r
= CMP(b
->is_host
, a
->is_host
);
1923 return strcasecmp(a
->name
, b
->name
);
1926 static int get_machine_properties(sd_bus
*bus
, struct machine_info
*mi
) {
1927 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*container
= NULL
;
1933 r
= sd_bus_open_system_machine(&container
, mi
->name
);
1940 r
= bus_map_all_properties(
1942 "org.freedesktop.systemd1",
1943 "/org/freedesktop/systemd1",
1944 machine_info_property_map
,
1955 static bool output_show_machine(const char *name
, char **patterns
) {
1956 return strv_fnmatch_or_empty(patterns
, name
, FNM_NOESCAPE
);
1959 static int get_machine_list(
1961 struct machine_info
**_machine_infos
,
1964 struct machine_info
*machine_infos
= NULL
;
1965 _cleanup_strv_free_
char **m
= NULL
;
1966 _cleanup_free_
char *hn
= NULL
;
1971 hn
= gethostname_malloc();
1975 if (output_show_machine(hn
, patterns
)) {
1976 if (!GREEDY_REALLOC0(machine_infos
, sz
, c
+1))
1979 machine_infos
[c
].is_host
= true;
1980 machine_infos
[c
].name
= TAKE_PTR(hn
);
1982 (void) get_machine_properties(bus
, &machine_infos
[c
]);
1986 r
= sd_get_machine_names(&m
);
1988 return log_error_errno(r
, "Failed to get machine list: %m");
1990 STRV_FOREACH(i
, m
) {
1991 _cleanup_free_
char *class = NULL
;
1993 if (!output_show_machine(*i
, patterns
))
1996 sd_machine_get_class(*i
, &class);
1997 if (!streq_ptr(class, "container"))
2000 if (!GREEDY_REALLOC0(machine_infos
, sz
, c
+1)) {
2001 free_machines_list(machine_infos
, c
);
2005 machine_infos
[c
].is_host
= false;
2006 machine_infos
[c
].name
= strdup(*i
);
2007 if (!machine_infos
[c
].name
) {
2008 free_machines_list(machine_infos
, c
);
2012 (void) get_machine_properties(NULL
, &machine_infos
[c
]);
2016 *_machine_infos
= machine_infos
;
2020 static int output_machines_list(struct machine_info
*machine_infos
, unsigned n
) {
2021 _cleanup_(table_unrefp
) Table
*table
= NULL
;
2022 struct machine_info
*m
;
2023 bool state_missing
= false;
2026 assert(machine_infos
|| n
== 0);
2028 table
= table_new("", "name", "state", "failed", "jobs");
2032 table_set_header(table
, !arg_no_legend
);
2034 /* Hide the 'glyph' column when --plain is requested */
2035 r
= table_hide_column_from_display(table
, 0);
2037 return log_error_errno(r
, "Failed to hide column: %m");
2040 table_set_width(table
, 0);
2042 (void) table_set_empty_string(table
, "-");
2044 for (m
= machine_infos
; m
< machine_infos
+ n
; m
++) {
2045 _cleanup_free_
char *mname
= NULL
;
2046 const char *on_state
= "", *on_failed
= "";
2047 bool circle
= false;
2049 if (streq_ptr(m
->state
, "degraded")) {
2050 on_state
= ansi_highlight_red();
2052 } else if (!streq_ptr(m
->state
, "running")) {
2053 on_state
= ansi_highlight_yellow();
2057 if (m
->n_failed_units
> 0)
2058 on_failed
= ansi_highlight_red();
2063 state_missing
= true;
2066 mname
= strjoin(strna(m
->name
), " (host)");
2068 r
= table_add_many(table
,
2069 TABLE_STRING
, circle
? special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
) : " ",
2070 TABLE_SET_COLOR
, on_state
,
2071 TABLE_STRING
, m
->is_host
? mname
: strna(m
->name
),
2072 TABLE_STRING
, strna(m
->state
),
2073 TABLE_SET_COLOR
, on_state
,
2074 TABLE_UINT32
, m
->n_failed_units
,
2075 TABLE_SET_COLOR
, on_failed
,
2076 TABLE_UINT32
, m
->n_jobs
);
2078 return table_log_add_error(r
);
2081 r
= output_table(table
);
2085 if (!arg_no_legend
) {
2087 if (state_missing
&& geteuid() != 0)
2088 printf("Notice: some information only available to privileged users was not shown.\n");
2089 printf("%u machines listed.\n", n
);
2095 static int list_machines(int argc
, char *argv
[], void *userdata
) {
2096 struct machine_info
*machine_infos
= NULL
;
2100 r
= acquire_bus(BUS_MANAGER
, &bus
);
2104 r
= get_machine_list(bus
, &machine_infos
, strv_skip(argv
, 1));
2108 (void) pager_open(arg_pager_flags
);
2110 typesafe_qsort(machine_infos
, r
, compare_machine_info
);
2111 rc
= output_machines_list(machine_infos
, r
);
2112 free_machines_list(machine_infos
, r
);
2117 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
2120 if (streq(key
, "systemd.unit")) {
2121 if (proc_cmdline_value_missing(key
, value
))
2123 if (!unit_name_is_valid(value
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
2124 return log_warning("Unit name specified on %s= is not valid, ignoring: %s", key
, value
);
2126 return free_and_strdup_warn(ret
, key
);
2128 } else if (!value
) {
2129 if (runlevel_to_target(key
))
2130 return free_and_strdup_warn(ret
, key
);
2136 static void emit_cmdline_warning(void) {
2137 if (arg_quiet
|| arg_root
)
2138 /* don't bother checking the commandline if we're operating on a container */
2141 _cleanup_free_
char *override
= NULL
;
2144 r
= proc_cmdline_parse(parse_proc_cmdline_item
, &override
, 0);
2146 log_debug_errno(r
, "Failed to parse kernel command line, ignoring: %m");
2148 log_notice("Note: found \"%s\" on the kernel commandline, which overrides the default unit.",
2152 static int determine_default(char **ret_name
) {
2155 if (install_client_side()) {
2156 r
= unit_file_get_default(arg_scope
, arg_root
, ret_name
);
2158 return log_error_errno(r
, "Failed to get default target: %m");
2163 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2164 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2167 r
= acquire_bus(BUS_MANAGER
, &bus
);
2171 r
= sd_bus_call_method(
2173 "org.freedesktop.systemd1",
2174 "/org/freedesktop/systemd1",
2175 "org.freedesktop.systemd1.Manager",
2181 return log_error_errno(r
, "Failed to get default target: %s", bus_error_message(&error
, r
));
2183 r
= sd_bus_message_read(reply
, "s", &name
);
2185 return bus_log_parse_error(r
);
2187 return free_and_strdup_warn(ret_name
, name
);
2191 static int get_default(int argc
, char *argv
[], void *userdata
) {
2192 _cleanup_free_
char *name
= NULL
;
2195 r
= determine_default(&name
);
2199 printf("%s\n", name
);
2201 emit_cmdline_warning();
2206 static int set_default(int argc
, char *argv
[], void *userdata
) {
2207 _cleanup_free_
char *unit
= NULL
;
2208 UnitFileChange
*changes
= NULL
;
2209 size_t n_changes
= 0;
2215 r
= unit_name_mangle_with_suffix(argv
[1], "set-default",
2216 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
2219 return log_error_errno(r
, "Failed to mangle unit name: %m");
2221 if (install_client_side()) {
2222 r
= unit_file_set_default(arg_scope
, UNIT_FILE_FORCE
, arg_root
, unit
, &changes
, &n_changes
);
2223 unit_file_dump_changes(r
, "set default", changes
, n_changes
, arg_quiet
);
2228 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2229 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2232 polkit_agent_open_maybe();
2234 r
= acquire_bus(BUS_MANAGER
, &bus
);
2238 r
= sd_bus_call_method(
2240 "org.freedesktop.systemd1",
2241 "/org/freedesktop/systemd1",
2242 "org.freedesktop.systemd1.Manager",
2248 return log_error_errno(r
, "Failed to set default target: %s", bus_error_message(&error
, r
));
2250 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
2254 /* Try to reload if enabled */
2256 r
= daemon_reload(argc
, argv
, userdata
);
2261 emit_cmdline_warning();
2264 _cleanup_free_
char *final
= NULL
;
2266 r
= determine_default(&final
);
2270 if (!streq(final
, unit
))
2271 log_notice("Note: \"%s\" is the default unit (possibly a runtime override).", final
);
2275 unit_file_changes_free(changes
, n_changes
);
2280 static int output_waiting_jobs(sd_bus
*bus
, Table
*table
, uint32_t id
, const char *method
, const char *prefix
) {
2281 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2282 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2283 const char *name
, *type
;
2289 r
= sd_bus_call_method(
2291 "org.freedesktop.systemd1",
2292 "/org/freedesktop/systemd1",
2293 "org.freedesktop.systemd1.Manager",
2299 return log_debug_errno(r
, "Failed to get waiting jobs for job %" PRIu32
, id
);
2301 r
= sd_bus_message_enter_container(reply
, 'a', "(usssoo)");
2303 return bus_log_parse_error(r
);
2305 while ((r
= sd_bus_message_read(reply
, "(usssoo)", &other_id
, &name
, &type
, NULL
, NULL
, NULL
)) > 0) {
2306 _cleanup_free_
char *row
= NULL
;
2309 if (asprintf(&row
, "%s %u (%s/%s)", prefix
, other_id
, name
, type
) < 0)
2312 rc
= table_add_many(table
,
2313 TABLE_STRING
, special_glyph(SPECIAL_GLYPH_TREE_RIGHT
),
2318 return table_log_add_error(r
);
2322 return bus_log_parse_error(r
);
2324 r
= sd_bus_message_exit_container(reply
);
2326 return bus_log_parse_error(r
);
2333 const char *name
, *type
, *state
;
2336 static int output_jobs_list(sd_bus
*bus
, const struct job_info
* jobs
, unsigned n
, bool skipped
) {
2337 _cleanup_(table_unrefp
) Table
*table
= NULL
;
2338 const struct job_info
*j
;
2339 const char *on
, *off
;
2342 assert(n
== 0 || jobs
);
2345 if (!arg_no_legend
) {
2346 on
= ansi_highlight_green();
2347 off
= ansi_normal();
2349 printf("%sNo jobs %s.%s\n", on
, skipped
? "listed" : "running", off
);
2354 (void) pager_open(arg_pager_flags
);
2356 table
= table_new("job", "unit", "type", "state");
2360 table_set_header(table
, !arg_no_legend
);
2362 table_set_width(table
, 0);
2364 (void) table_set_empty_string(table
, "-");
2366 for (j
= jobs
; j
< jobs
+ n
; j
++) {
2367 if (streq(j
->state
, "running"))
2368 on
= ansi_highlight();
2373 r
= table_add_many(table
,
2375 TABLE_STRING
, j
->name
,
2376 TABLE_SET_COLOR
, on
,
2377 TABLE_STRING
, j
->type
,
2378 TABLE_STRING
, j
->state
,
2379 TABLE_SET_COLOR
, on
);
2381 return table_log_add_error(r
);
2384 output_waiting_jobs(bus
, table
, j
->id
, "GetJobAfter", "\twaiting for job");
2385 if (arg_jobs_before
)
2386 output_waiting_jobs(bus
, table
, j
->id
, "GetJobBefore", "\tblocking job");
2389 r
= table_print(table
, NULL
);
2391 return log_error_errno(r
, "Failed to print the table: %m");
2393 if (!arg_no_legend
) {
2394 on
= ansi_highlight();
2395 off
= ansi_normal();
2397 printf("\n%s%u jobs listed%s.\n", on
, n
, off
);
2403 static bool output_show_job(struct job_info
*job
, char **patterns
) {
2404 return strv_fnmatch_or_empty(patterns
, job
->name
, FNM_NOESCAPE
);
2407 static int list_jobs(int argc
, char *argv
[], void *userdata
) {
2408 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2409 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2410 _cleanup_free_
struct job_info
*jobs
= NULL
;
2411 const char *name
, *type
, *state
;
2412 bool skipped
= false;
2419 r
= acquire_bus(BUS_MANAGER
, &bus
);
2423 r
= sd_bus_call_method(
2425 "org.freedesktop.systemd1",
2426 "/org/freedesktop/systemd1",
2427 "org.freedesktop.systemd1.Manager",
2433 return log_error_errno(r
, "Failed to list jobs: %s", bus_error_message(&error
, r
));
2435 r
= sd_bus_message_enter_container(reply
, 'a', "(usssoo)");
2437 return bus_log_parse_error(r
);
2439 while ((r
= sd_bus_message_read(reply
, "(usssoo)", &id
, &name
, &type
, &state
, NULL
, NULL
)) > 0) {
2440 struct job_info job
= { id
, name
, type
, state
};
2442 if (!output_show_job(&job
, strv_skip(argv
, 1))) {
2447 if (!GREEDY_REALLOC(jobs
, size
, c
+ 1))
2453 return bus_log_parse_error(r
);
2455 r
= sd_bus_message_exit_container(reply
);
2457 return bus_log_parse_error(r
);
2459 (void) pager_open(arg_pager_flags
);
2461 return output_jobs_list(bus
, jobs
, c
, skipped
);
2464 static int cancel_job(int argc
, char *argv
[], void *userdata
) {
2470 return trivial_method(argc
, argv
, userdata
);
2472 r
= acquire_bus(BUS_MANAGER
, &bus
);
2476 polkit_agent_open_maybe();
2478 STRV_FOREACH(name
, strv_skip(argv
, 1)) {
2479 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2483 q
= safe_atou32(*name
, &id
);
2485 return log_error_errno(q
, "Failed to parse job id \"%s\": %m", *name
);
2487 q
= sd_bus_call_method(
2489 "org.freedesktop.systemd1",
2490 "/org/freedesktop/systemd1",
2491 "org.freedesktop.systemd1.Manager",
2497 log_error_errno(q
, "Failed to cancel job %"PRIu32
": %s", id
, bus_error_message(&error
, q
));
2506 static int need_daemon_reload(sd_bus
*bus
, const char *unit
) {
2507 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2511 /* We ignore all errors here, since this is used to show a
2514 /* We don't use unit_dbus_path_from_name() directly since we
2515 * don't want to load the unit if it isn't loaded. */
2517 r
= sd_bus_call_method(
2519 "org.freedesktop.systemd1",
2520 "/org/freedesktop/systemd1",
2521 "org.freedesktop.systemd1.Manager",
2529 r
= sd_bus_message_read(reply
, "o", &path
);
2533 r
= sd_bus_get_property_trivial(
2535 "org.freedesktop.systemd1",
2537 "org.freedesktop.systemd1.Unit",
2547 static void warn_unit_file_changed(const char *name
) {
2550 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.",
2551 ansi_highlight_red(),
2554 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user");
2557 static int unit_file_find_path(LookupPaths
*lp
, const char *unit_name
, char **ret_unit_path
) {
2563 STRV_FOREACH(p
, lp
->search_path
) {
2564 _cleanup_free_
char *path
= NULL
, *lpath
= NULL
;
2567 path
= path_join(*p
, unit_name
);
2571 r
= chase_symlinks(path
, arg_root
, 0, &lpath
, NULL
);
2577 return log_error_errno(r
, "Failed to access path \"%s\": %m", path
);
2580 *ret_unit_path
= TAKE_PTR(lpath
);
2586 *ret_unit_path
= NULL
;
2591 static int unit_find_template_path(
2592 const char *unit_name
,
2594 char **ret_fragment_path
,
2595 char **ret_template
) {
2597 _cleanup_free_
char *t
= NULL
, *f
= NULL
;
2600 /* Returns 1 if a fragment was found, 0 if not found, negative on error. */
2602 r
= unit_file_find_path(lp
, unit_name
, &f
);
2606 if (ret_fragment_path
)
2607 *ret_fragment_path
= TAKE_PTR(f
);
2609 *ret_template
= NULL
;
2610 return r
; /* found a real unit */
2613 r
= unit_name_template(unit_name
, &t
);
2615 if (ret_fragment_path
)
2616 *ret_fragment_path
= NULL
;
2618 *ret_template
= NULL
;
2620 return 0; /* not a template, does not exist */
2623 return log_error_errno(r
, "Failed to determine template name: %m");
2625 r
= unit_file_find_path(lp
, t
, ret_fragment_path
);
2630 *ret_template
= r
> 0 ? TAKE_PTR(t
) : NULL
;
2635 static int unit_find_paths(
2637 const char *unit_name
,
2639 bool force_client_side
,
2640 char **ret_fragment_path
,
2641 char ***ret_dropin_paths
) {
2643 _cleanup_strv_free_
char **dropins
= NULL
;
2644 _cleanup_free_
char *path
= NULL
;
2648 * Finds where the unit is defined on disk. Returns 0 if the unit is not found. Returns 1 if it is
2650 * - the path to the unit in *ret_frament_path, if it exists on disk,
2651 * - and a strv of existing drop-ins in *ret_dropin_paths, if the arg is not NULL and any dropins
2654 * Returns -ERFKILL if the unit is masked, and -EKEYREJECTED if the unit file could not be loaded for
2655 * some reason (the latter only applies if we are going through the service manager).
2659 assert(ret_fragment_path
);
2662 /* Go via the bus to acquire the path, unless we are explicitly told not to, or when the unit name is a template */
2663 if (!force_client_side
&&
2664 !install_client_side() &&
2665 !unit_name_is_valid(unit_name
, UNIT_NAME_TEMPLATE
)) {
2666 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2667 _cleanup_free_
char *load_state
= NULL
, *dbus_path
= NULL
;
2669 dbus_path
= unit_dbus_path_from_name(unit_name
);
2673 r
= sd_bus_get_property_string(
2675 "org.freedesktop.systemd1",
2677 "org.freedesktop.systemd1.Unit",
2682 return log_error_errno(r
, "Failed to get LoadState: %s", bus_error_message(&error
, r
));
2684 if (streq(load_state
, "masked"))
2686 if (streq(load_state
, "not-found")) {
2690 if (!STR_IN_SET(load_state
, "loaded", "bad-setting"))
2691 return -EKEYREJECTED
;
2693 r
= sd_bus_get_property_string(
2695 "org.freedesktop.systemd1",
2697 "org.freedesktop.systemd1.Unit",
2702 return log_error_errno(r
, "Failed to get FragmentPath: %s", bus_error_message(&error
, r
));
2704 if (ret_dropin_paths
) {
2705 r
= sd_bus_get_property_strv(
2707 "org.freedesktop.systemd1",
2709 "org.freedesktop.systemd1.Unit",
2714 return log_error_errno(r
, "Failed to get DropInPaths: %s", bus_error_message(&error
, r
));
2718 _cleanup_set_free_free_ Set
*names
= NULL
;
2720 if (!cached_name_map
) {
2721 r
= unit_file_build_name_map(lp
, NULL
, &cached_id_map
, &cached_name_map
, NULL
);
2726 r
= unit_file_find_fragment(cached_id_map
, cached_name_map
, unit_name
, &_path
, &names
);
2731 path
= strdup(_path
);
2736 if (ret_dropin_paths
) {
2737 r
= unit_file_find_dropin_paths(arg_root
, lp
->search_path
, NULL
,
2745 if (isempty(path
)) {
2746 *ret_fragment_path
= NULL
;
2749 *ret_fragment_path
= TAKE_PTR(path
);
2753 if (ret_dropin_paths
) {
2754 if (!strv_isempty(dropins
)) {
2755 *ret_dropin_paths
= TAKE_PTR(dropins
);
2758 *ret_dropin_paths
= NULL
;
2762 if (r
== 0 && !arg_force
)
2763 log_error("No files found for %s.", unit_name
);
2768 static int get_state_one_unit(sd_bus
*bus
, const char *name
, UnitActiveState
*active_state
) {
2769 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2770 _cleanup_free_
char *buf
= NULL
, *dbus_path
= NULL
;
2771 UnitActiveState state
;
2775 assert(active_state
);
2777 dbus_path
= unit_dbus_path_from_name(name
);
2781 r
= sd_bus_get_property_string(
2783 "org.freedesktop.systemd1",
2785 "org.freedesktop.systemd1.Unit",
2790 return log_error_errno(r
, "Failed to retrieve unit state: %s", bus_error_message(&error
, r
));
2792 state
= unit_active_state_from_string(buf
);
2794 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid unit state '%s' for: %s", buf
, name
);
2796 *active_state
= state
;
2800 static int unit_is_masked(sd_bus
*bus
, LookupPaths
*lp
, const char *name
) {
2801 _cleanup_free_
char *load_state
= NULL
;
2804 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
2805 _cleanup_free_
char *path
= NULL
;
2807 /* A template cannot be loaded, but it can be still masked, so
2808 * we need to use a different method. */
2810 r
= unit_file_find_path(lp
, name
, &path
);
2815 return null_or_empty_path(path
);
2818 r
= unit_load_state(bus
, name
, &load_state
);
2822 return streq(load_state
, "masked");
2825 static int check_triggering_units(sd_bus
*bus
, const char *name
) {
2826 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2827 _cleanup_free_
char *n
= NULL
, *dbus_path
= NULL
, *load_state
= NULL
;
2828 _cleanup_strv_free_
char **triggered_by
= NULL
;
2829 bool print_warning_label
= true;
2830 UnitActiveState active_state
;
2834 r
= unit_name_mangle(name
, 0, &n
);
2836 return log_error_errno(r
, "Failed to mangle unit name: %m");
2838 r
= unit_load_state(bus
, name
, &load_state
);
2842 if (streq(load_state
, "masked"))
2845 dbus_path
= unit_dbus_path_from_name(n
);
2849 r
= sd_bus_get_property_strv(
2851 "org.freedesktop.systemd1",
2853 "org.freedesktop.systemd1.Unit",
2858 return log_error_errno(r
, "Failed to get triggered by array of %s: %s", n
, bus_error_message(&error
, r
));
2860 STRV_FOREACH(i
, triggered_by
) {
2861 r
= get_state_one_unit(bus
, *i
, &active_state
);
2865 if (!IN_SET(active_state
, UNIT_ACTIVE
, UNIT_RELOADING
))
2868 if (print_warning_label
) {
2869 log_warning("Warning: Stopping %s, but it can still be activated by:", n
);
2870 print_warning_label
= false;
2873 log_warning(" %s", *i
);
2879 static const struct {
2880 const char *verb
; /* systemctl verb */
2881 const char *method
; /* Name of the specific D-Bus method */
2882 const char *job_type
; /* Job type when passing to the generic EnqueueUnitJob() method */
2883 } unit_actions
[] = {
2884 { "start", "StartUnit", "start" },
2885 { "stop", "StopUnit", "stop" },
2886 { "condstop", "StopUnit", "stop" }, /* legacy alias */
2887 { "reload", "ReloadUnit", "reload" },
2888 { "restart", "RestartUnit", "restart" },
2889 { "try-restart", "TryRestartUnit", "try-restart" },
2890 { "condrestart", "TryRestartUnit", "try-restart" }, /* legacy alias */
2891 { "reload-or-restart", "ReloadOrRestartUnit", "reload-or-restart" },
2892 { "try-reload-or-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" },
2893 { "reload-or-try-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2894 { "condreload", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2895 { "force-reload", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2898 static const char *verb_to_method(const char *verb
) {
2901 for (i
= 0; i
< ELEMENTSOF(unit_actions
); i
++)
2902 if (streq_ptr(unit_actions
[i
].verb
, verb
))
2903 return unit_actions
[i
].method
;
2908 static const char *verb_to_job_type(const char *verb
) {
2911 for (i
= 0; i
< ELEMENTSOF(unit_actions
); i
++)
2912 if (streq_ptr(unit_actions
[i
].verb
, verb
))
2913 return unit_actions
[i
].job_type
;
2918 static int start_unit_one(
2920 const char *method
, /* When using classic per-job bus methods */
2921 const char *job_type
, /* When using new-style EnqueueUnitJob() */
2924 sd_bus_error
*error
,
2926 BusWaitForUnits
*wu
) {
2928 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2938 log_debug("%s dbus call org.freedesktop.systemd1.Manager %s(%s, %s)",
2939 arg_dry_run
? "Would execute" : "Executing",
2940 method
, name
, mode
);
2945 if (arg_show_transaction
) {
2946 _cleanup_(sd_bus_error_free
) sd_bus_error enqueue_error
= SD_BUS_ERROR_NULL
;
2948 /* Use the new, fancy EnqueueUnitJob() API if the user wants us to print the transaction */
2949 r
= sd_bus_call_method(
2951 "org.freedesktop.systemd1",
2952 "/org/freedesktop/systemd1",
2953 "org.freedesktop.systemd1.Manager",
2958 name
, job_type
, mode
);
2960 if (!sd_bus_error_has_name(&enqueue_error
, SD_BUS_ERROR_UNKNOWN_METHOD
)) {
2961 (void) sd_bus_error_move(error
, &enqueue_error
);
2965 /* Hmm, the API is not yet available. Let's use the classic API instead (see below). */
2966 log_notice("--show-transaction not supported by this service manager, proceeding without.");
2971 r
= sd_bus_message_read(reply
, "uosos", &id
, &path
, &u
, NULL
, &jt
);
2973 return bus_log_parse_error(r
);
2975 log_info("Enqueued anchor job %" PRIu32
" %s/%s.", id
, u
, jt
);
2977 r
= sd_bus_message_enter_container(reply
, 'a', "(uosos)");
2979 return bus_log_parse_error(r
);
2981 r
= sd_bus_message_read(reply
, "(uosos)", &id
, NULL
, &u
, NULL
, &jt
);
2983 return bus_log_parse_error(r
);
2987 log_info("Enqueued auxiliary job %" PRIu32
" %s/%s.", id
, u
, jt
);
2990 r
= sd_bus_message_exit_container(reply
);
2992 return bus_log_parse_error(r
);
2999 r
= sd_bus_call_method(
3001 "org.freedesktop.systemd1",
3002 "/org/freedesktop/systemd1",
3003 "org.freedesktop.systemd1.Manager",
3011 r
= sd_bus_message_read(reply
, "o", &path
);
3013 return bus_log_parse_error(r
);
3016 if (need_daemon_reload(bus
, name
) > 0)
3017 warn_unit_file_changed(name
);
3020 log_debug("Adding %s to the set", path
);
3021 r
= bus_wait_for_jobs_add(w
, path
);
3023 return log_error_errno(r
, "Failed to watch job for %s: %m", name
);
3027 r
= bus_wait_for_units_add_unit(wu
, name
, BUS_WAIT_FOR_INACTIVE
|BUS_WAIT_NO_JOB
, NULL
, NULL
);
3029 return log_error_errno(r
, "Failed to watch unit %s: %m", name
);
3035 /* There's always a fallback possible for legacy actions. */
3036 if (arg_action
!= ACTION_SYSTEMCTL
)
3039 log_error_errno(r
, "Failed to %s %s: %s", job_type
, name
, bus_error_message(error
, r
));
3041 if (!sd_bus_error_has_name(error
, BUS_ERROR_NO_SUCH_UNIT
) &&
3042 !sd_bus_error_has_name(error
, BUS_ERROR_UNIT_MASKED
) &&
3043 !sd_bus_error_has_name(error
, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE
))
3044 log_error("See %s logs and 'systemctl%s status%s %s' for details.",
3045 arg_scope
== UNIT_FILE_SYSTEM
? "system" : "user",
3046 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user",
3047 name
[0] == '-' ? " --" : "",
3053 static const struct {
3057 } action_table
[_ACTION_MAX
] = {
3058 [ACTION_HALT
] = { SPECIAL_HALT_TARGET
, "halt", "replace-irreversibly" },
3059 [ACTION_POWEROFF
] = { SPECIAL_POWEROFF_TARGET
, "poweroff", "replace-irreversibly" },
3060 [ACTION_REBOOT
] = { SPECIAL_REBOOT_TARGET
, "reboot", "replace-irreversibly" },
3061 [ACTION_KEXEC
] = { SPECIAL_KEXEC_TARGET
, "kexec", "replace-irreversibly" },
3062 [ACTION_RUNLEVEL2
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
3063 [ACTION_RUNLEVEL3
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
3064 [ACTION_RUNLEVEL4
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
3065 [ACTION_RUNLEVEL5
] = { SPECIAL_GRAPHICAL_TARGET
, NULL
, "isolate" },
3066 [ACTION_RESCUE
] = { SPECIAL_RESCUE_TARGET
, "rescue", "isolate" },
3067 [ACTION_EMERGENCY
] = { SPECIAL_EMERGENCY_TARGET
, "emergency", "isolate" },
3068 [ACTION_DEFAULT
] = { SPECIAL_DEFAULT_TARGET
, "default", "isolate" },
3069 [ACTION_EXIT
] = { SPECIAL_EXIT_TARGET
, "exit", "replace-irreversibly" },
3070 [ACTION_SUSPEND
] = { SPECIAL_SUSPEND_TARGET
, "suspend", "replace-irreversibly" },
3071 [ACTION_HIBERNATE
] = { SPECIAL_HIBERNATE_TARGET
, "hibernate", "replace-irreversibly" },
3072 [ACTION_HYBRID_SLEEP
] = { SPECIAL_HYBRID_SLEEP_TARGET
, "hybrid-sleep", "replace-irreversibly" },
3073 [ACTION_SUSPEND_THEN_HIBERNATE
] = { SPECIAL_SUSPEND_THEN_HIBERNATE_TARGET
, "suspend-then-hibernate", "replace-irreversibly" },
3076 static enum action
verb_to_action(const char *verb
) {
3079 for (i
= 0; i
< _ACTION_MAX
; i
++)
3080 if (streq_ptr(action_table
[i
].verb
, verb
))
3083 return _ACTION_INVALID
;
3086 static const char** make_extra_args(const char *extra_args
[static 4]) {
3091 if (arg_scope
!= UNIT_FILE_SYSTEM
)
3092 extra_args
[n
++] = "--user";
3094 if (arg_transport
== BUS_TRANSPORT_REMOTE
) {
3095 extra_args
[n
++] = "-H";
3096 extra_args
[n
++] = arg_host
;
3097 } else if (arg_transport
== BUS_TRANSPORT_MACHINE
) {
3098 extra_args
[n
++] = "-M";
3099 extra_args
[n
++] = arg_host
;
3101 assert(arg_transport
== BUS_TRANSPORT_LOCAL
);
3103 extra_args
[n
] = NULL
;
3107 static int start_unit(int argc
, char *argv
[], void *userdata
) {
3108 _cleanup_(bus_wait_for_units_freep
) BusWaitForUnits
*wu
= NULL
;
3109 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
3110 const char *method
, *job_type
, *mode
, *one_name
, *suffix
= NULL
;
3111 _cleanup_free_
char **stopped_units
= NULL
; /* Do not use _cleanup_strv_free_ */
3112 _cleanup_strv_free_
char **names
= NULL
;
3113 int r
, ret
= EXIT_SUCCESS
;
3117 if (arg_wait
&& !STR_IN_SET(argv
[0], "start", "restart"))
3118 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3119 "--wait may only be used with the 'start' or 'restart' commands.");
3121 /* we cannot do sender tracking on the private bus, so we need the full
3122 * one for RefUnit to implement --wait */
3123 r
= acquire_bus(arg_wait
? BUS_FULL
: BUS_MANAGER
, &bus
);
3127 ask_password_agent_open_maybe();
3128 polkit_agent_open_maybe();
3130 if (arg_action
== ACTION_SYSTEMCTL
) {
3133 action
= verb_to_action(argv
[0]);
3135 if (action
!= _ACTION_INVALID
) {
3136 /* A command in style "systemctl reboot", "systemctl poweroff", … */
3137 method
= "StartUnit";
3139 mode
= action_table
[action
].mode
;
3140 one_name
= action_table
[action
].target
;
3142 if (streq(argv
[0], "isolate")) {
3143 /* A "systemctl isolate <unit1> <unit2> …" command */
3144 method
= "StartUnit";
3149 /* A command in style of "systemctl start <unit1> <unit2> …", "sysemctl stop <unit1> <unit2> …" and so on */
3150 method
= verb_to_method(argv
[0]);
3151 job_type
= verb_to_job_type(argv
[0]);
3152 mode
= arg_job_mode
;
3157 /* A SysV legacy command such as "halt", "reboot", "poweroff", … */
3158 assert(arg_action
>= 0 && arg_action
< _ACTION_MAX
);
3159 assert(action_table
[arg_action
].target
);
3160 assert(action_table
[arg_action
].mode
);
3162 method
= "StartUnit";
3164 mode
= action_table
[arg_action
].mode
;
3165 one_name
= action_table
[arg_action
].target
;
3169 names
= strv_new(one_name
);
3175 r
= expand_names(bus
, strv_skip(argv
, 1), suffix
, &names
, &expanded
);
3177 return log_error_errno(r
, "Failed to expand names: %m");
3179 if (!arg_all
&& expanded
&& streq(job_type
, "start") && !arg_quiet
) {
3180 log_warning("Warning: %ssystemctl start called with a glob pattern.%s",
3181 ansi_highlight_red(),
3183 log_notice("Hint: unit globs expand to loaded units, so start will usually have no effect.\n"
3184 " Passing --all will also load units which are pulled in by other units.\n"
3185 " See systemctl(1) for more details.");
3189 if (!arg_no_block
) {
3190 r
= bus_wait_for_jobs_new(bus
, &w
);
3192 return log_error_errno(r
, "Could not watch jobs: %m");
3196 r
= sd_bus_call_method_async(
3199 "org.freedesktop.systemd1",
3200 "/org/freedesktop/systemd1",
3201 "org.freedesktop.systemd1.Manager",
3206 return log_error_errno(r
, "Failed to enable subscription: %m");
3208 r
= bus_wait_for_units_new(bus
, &wu
);
3210 return log_error_errno(r
, "Failed to allocate unit watch context: %m");
3213 STRV_FOREACH(name
, names
) {
3214 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3216 r
= start_unit_one(bus
, method
, job_type
, *name
, mode
, &error
, w
, wu
);
3217 if (ret
== EXIT_SUCCESS
&& r
< 0)
3218 ret
= translate_bus_error_to_exit_status(r
, &error
);
3220 if (r
>= 0 && streq(method
, "StopUnit")) {
3221 r
= strv_push(&stopped_units
, *name
);
3227 if (!arg_no_block
) {
3228 const char* extra_args
[4];
3230 r
= bus_wait_for_jobs(w
, arg_quiet
, make_extra_args(extra_args
));
3234 /* When stopping units, warn if they can still be triggered by
3235 * another active unit (socket, path, timer) */
3237 STRV_FOREACH(name
, stopped_units
)
3238 (void) check_triggering_units(bus
, *name
);
3242 r
= bus_wait_for_units_run(wu
);
3244 return log_error_errno(r
, "Failed to wait for units: %m");
3245 if (r
== BUS_WAIT_FAILURE
&& ret
== EXIT_SUCCESS
)
3253 static int logind_set_wall_message(void) {
3254 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3256 _cleanup_free_
char *m
= NULL
;
3259 r
= acquire_bus(BUS_FULL
, &bus
);
3263 m
= strv_join(arg_wall
, " ");
3267 log_debug("%s wall message \"%s\".", arg_dry_run
? "Would set" : "Setting", m
);
3271 r
= sd_bus_call_method(
3273 "org.freedesktop.login1",
3274 "/org/freedesktop/login1",
3275 "org.freedesktop.login1.Manager",
3284 return log_warning_errno(r
, "Failed to set wall message, ignoring: %s", bus_error_message(&error
, r
));
3289 /* Ask systemd-logind, which might grant access to unprivileged users through polkit */
3290 static int logind_reboot(enum action a
) {
3292 static const struct {
3294 const char *description
;
3295 } actions
[_ACTION_MAX
] = {
3296 [ACTION_POWEROFF
] = { "PowerOff", "power off system" },
3297 [ACTION_REBOOT
] = { "Reboot", "reboot system" },
3298 [ACTION_HALT
] = { "Halt", "halt system" },
3299 [ACTION_SUSPEND
] = { "Suspend", "suspend system" },
3300 [ACTION_HIBERNATE
] = { "Hibernate", "hibernate system" },
3301 [ACTION_HYBRID_SLEEP
] = { "HybridSleep", "put system into hybrid sleep" },
3302 [ACTION_SUSPEND_THEN_HIBERNATE
] = { "SuspendThenHibernate", "suspend system, hibernate later" },
3305 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3309 if (a
< 0 || a
>= _ACTION_MAX
|| !actions
[a
].method
)
3312 r
= acquire_bus(BUS_FULL
, &bus
);
3316 polkit_agent_open_maybe();
3317 (void) logind_set_wall_message();
3319 log_debug("%s org.freedesktop.login1.Manager %s dbus call.", arg_dry_run
? "Would execute" : "Executing", actions
[a
].method
);
3324 r
= sd_bus_call_method(
3326 "org.freedesktop.login1",
3327 "/org/freedesktop/login1",
3328 "org.freedesktop.login1.Manager",
3332 "b", arg_ask_password
);
3334 return log_error_errno(r
, "Failed to %s via logind: %s", actions
[a
].description
, bus_error_message(&error
, r
));
3342 static int logind_check_inhibitors(enum action a
) {
3344 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
3345 _cleanup_strv_free_
char **sessions
= NULL
;
3346 const char *what
, *who
, *why
, *mode
;
3353 if (arg_ignore_inhibitors
|| arg_force
> 0)
3365 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
3368 r
= acquire_bus(BUS_FULL
, &bus
);
3372 r
= sd_bus_call_method(
3374 "org.freedesktop.login1",
3375 "/org/freedesktop/login1",
3376 "org.freedesktop.login1.Manager",
3382 /* If logind is not around, then there are no inhibitors... */
3385 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssuu)");
3387 return bus_log_parse_error(r
);
3389 while ((r
= sd_bus_message_read(reply
, "(ssssuu)", &what
, &who
, &why
, &mode
, &uid
, &pid
)) > 0) {
3390 _cleanup_free_
char *comm
= NULL
, *user
= NULL
;
3391 _cleanup_strv_free_
char **sv
= NULL
;
3393 if (!streq(mode
, "block"))
3396 sv
= strv_split(what
, ":");
3400 if (!pid_is_valid((pid_t
) pid
))
3401 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Invalid PID "PID_FMT
".", (pid_t
) pid
);
3403 if (!strv_contains(sv
,
3408 ACTION_KEXEC
) ? "shutdown" : "sleep"))
3411 get_process_comm(pid
, &comm
);
3412 user
= uid_to_name(uid
);
3414 log_warning("Operation inhibited by \"%s\" (PID "PID_FMT
" \"%s\", user %s), reason is \"%s\".",
3415 who
, (pid_t
) pid
, strna(comm
), strna(user
), why
);
3420 return bus_log_parse_error(r
);
3422 r
= sd_bus_message_exit_container(reply
);
3424 return bus_log_parse_error(r
);
3426 /* Check for current sessions */
3427 sd_get_sessions(&sessions
);
3428 STRV_FOREACH(s
, sessions
) {
3429 _cleanup_free_
char *type
= NULL
, *tty
= NULL
, *seat
= NULL
, *user
= NULL
, *service
= NULL
, *class = NULL
;
3431 if (sd_session_get_uid(*s
, &uid
) < 0 || uid
== getuid())
3434 if (sd_session_get_class(*s
, &class) < 0 || !streq(class, "user"))
3437 if (sd_session_get_type(*s
, &type
) < 0 || !STR_IN_SET(type
, "x11", "wayland", "tty", "mir"))
3440 sd_session_get_tty(*s
, &tty
);
3441 sd_session_get_seat(*s
, &seat
);
3442 sd_session_get_service(*s
, &service
);
3443 user
= uid_to_name(uid
);
3445 log_warning("User %s is logged in on %s.", strna(user
), isempty(tty
) ? (isempty(seat
) ? strna(service
) : seat
) : tty
);
3452 log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'systemctl %s -i'.",
3453 action_table
[a
].verb
);
3461 static int prepare_firmware_setup(void) {
3463 if (!arg_firmware_setup
)
3467 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3471 r
= acquire_bus(BUS_FULL
, &bus
);
3475 r
= sd_bus_call_method(
3477 "org.freedesktop.login1",
3478 "/org/freedesktop/login1",
3479 "org.freedesktop.login1.Manager",
3480 "SetRebootToFirmwareSetup",
3485 return log_error_errno(r
, "Cannot indicate to EFI to boot into setup mode: %s", bus_error_message(&error
, r
));
3489 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3490 "Booting into firmware setup not supported.");
3494 static int prepare_boot_loader_menu(void) {
3496 if (arg_boot_loader_menu
== USEC_INFINITY
)
3500 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3504 r
= acquire_bus(BUS_FULL
, &bus
);
3508 r
= sd_bus_call_method(
3510 "org.freedesktop.login1",
3511 "/org/freedesktop/login1",
3512 "org.freedesktop.login1.Manager",
3513 "SetRebootToBootLoaderMenu",
3516 "t", arg_boot_loader_menu
);
3518 return log_error_errno(r
, "Cannot indicate to boot loader to enter boot loader entry menu: %s", bus_error_message(&error
, r
));
3522 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3523 "Booting into boot loader menu not supported.");
3527 static int prepare_boot_loader_entry(void) {
3529 if (!arg_boot_loader_entry
)
3533 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3537 r
= acquire_bus(BUS_FULL
, &bus
);
3541 r
= sd_bus_call_method(
3543 "org.freedesktop.login1",
3544 "/org/freedesktop/login1",
3545 "org.freedesktop.login1.Manager",
3546 "SetRebootToBootLoaderEntry",
3549 "s", arg_boot_loader_entry
);
3551 return log_error_errno(r
, "Cannot set boot into loader entry '%s': %s", arg_boot_loader_entry
, bus_error_message(&error
, r
));
3555 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3556 "Booting into boot loader entry not supported.");
3560 static int load_kexec_kernel(void) {
3561 _cleanup_(boot_config_free
) BootConfig config
= {};
3562 _cleanup_free_
char *kernel
= NULL
, *initrd
= NULL
, *options
= NULL
;
3567 if (kexec_loaded()) {
3568 log_debug("Kexec kernel already loaded.");
3572 if (access(KEXEC
, X_OK
) < 0)
3573 return log_error_errno(errno
, KEXEC
" is not available: %m");
3575 r
= boot_entries_load_config_auto(NULL
, NULL
, &config
);
3577 /* The call doesn't log about ENOKEY, let's do so here. */
3578 return log_error_errno(r
,
3579 "No kexec kernel loaded and autodetection failed.\n%s",
3581 ? "Cannot automatically load kernel: ESP partition mount point not found."
3582 : "Automatic loading works only on systems booted with EFI.");
3586 e
= boot_config_default_entry(&config
);
3588 return log_error_errno(SYNTHETIC_ERRNO(ENOENT
),
3589 "No boot loader entry suitable as default, refusing to guess.");
3591 log_debug("Found default boot loader entry in file \"%s\"", e
->path
);
3594 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3595 "Boot entry does not refer to Linux kernel, which is not supported currently.");
3596 if (strv_length(e
->initrd
) > 1)
3597 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3598 "Boot entry specifies multiple initrds, which is not supported currently.");
3600 kernel
= path_join(e
->root
, e
->kernel
);
3604 if (!strv_isempty(e
->initrd
)) {
3605 initrd
= path_join(e
->root
, e
->initrd
[0]);
3610 options
= strv_join(e
->options
, " ");
3614 log_full(arg_quiet
? LOG_DEBUG
: LOG_INFO
,
3615 "%s "KEXEC
" --load \"%s\" --append \"%s\"%s%s%s",
3616 arg_dry_run
? "Would run" : "Running",
3619 initrd
? " --initrd \"" : NULL
, strempty(initrd
), initrd
? "\"" : "");
3623 r
= safe_fork("(kexec)", FORK_WAIT
|FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
, &pid
);
3627 const char* const args
[] = {
3630 "--append", options
,
3631 initrd
? "--initrd" : NULL
, initrd
,
3636 execv(args
[0], (char * const *) args
);
3637 _exit(EXIT_FAILURE
);
3643 static int set_exit_code(uint8_t code
) {
3644 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3648 r
= acquire_bus(BUS_MANAGER
, &bus
);
3652 r
= sd_bus_call_method(
3654 "org.freedesktop.systemd1",
3655 "/org/freedesktop/systemd1",
3656 "org.freedesktop.systemd1.Manager",
3662 return log_error_errno(r
, "Failed to set exit code: %s", bus_error_message(&error
, r
));
3667 static int start_special(int argc
, char *argv
[], void *userdata
) {
3670 bool termination_action
; /* an action that terminates the manager,
3671 * can be performed also by signal. */
3675 a
= verb_to_action(argv
[0]);
3677 r
= logind_check_inhibitors(a
);
3681 if (arg_force
>= 2) {
3687 r
= prepare_firmware_setup();
3691 r
= prepare_boot_loader_menu();
3695 r
= prepare_boot_loader_entry();
3699 if (a
== ACTION_REBOOT
&& argc
> 1) {
3700 r
= update_reboot_parameter_and_warn(argv
[1], false);
3704 } else if (a
== ACTION_KEXEC
) {
3705 r
= load_kexec_kernel();
3706 if (r
< 0 && arg_force
>= 1)
3707 log_notice("Failed to load kexec kernel, continuing without.");
3711 } else if (a
== ACTION_EXIT
&& argc
> 1) {
3714 /* If the exit code is not given on the command line,
3715 * don't reset it to zero: just keep it as it might
3716 * have been set previously. */
3718 r
= safe_atou8(argv
[1], &code
);
3720 return log_error_errno(r
, "Invalid exit code.");
3722 r
= set_exit_code(code
);
3727 termination_action
= IN_SET(a
,
3731 if (termination_action
&& arg_force
>= 2)
3734 if (arg_force
>= 1 &&
3735 (termination_action
|| IN_SET(a
, ACTION_KEXEC
, ACTION_EXIT
)))
3736 r
= trivial_method(argc
, argv
, userdata
);
3738 /* First try logind, to allow authentication with polkit */
3745 ACTION_HYBRID_SLEEP
,
3746 ACTION_SUSPEND_THEN_HIBERNATE
)) {
3748 r
= logind_reboot(a
);
3751 if (IN_SET(r
, -EOPNOTSUPP
, -EINPROGRESS
))
3752 /* requested operation is not supported or already in progress */
3755 /* On all other errors, try low-level operation. In order to minimize the difference between
3756 * operation with and without logind, we explicitly enable non-blocking mode for this, as
3757 * logind's shutdown operations are always non-blocking. */
3759 arg_no_block
= true;
3761 } else if (IN_SET(a
, ACTION_EXIT
, ACTION_KEXEC
))
3762 /* Since exit/kexec are so close in behaviour to power-off/reboot, let's also make them
3763 * asynchronous, in order to not confuse the user needlessly with unexpected behaviour. */
3764 arg_no_block
= true;
3766 r
= start_unit(argc
, argv
, userdata
);
3769 if (termination_action
&& arg_force
< 2 &&
3770 IN_SET(r
, -ENOENT
, -ETIMEDOUT
))
3771 log_notice("It is possible to perform action directly, see discussion of --force --force in man:systemctl(1).");
3776 static int start_system_special(int argc
, char *argv
[], void *userdata
) {
3777 /* Like start_special above, but raises an error when running in user mode */
3779 if (arg_scope
!= UNIT_FILE_SYSTEM
)
3780 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3781 "Bad action for %s mode.",
3782 arg_scope
== UNIT_FILE_GLOBAL
? "--global" : "--user");
3784 return start_special(argc
, argv
, userdata
);
3787 static int check_unit_generic(int code
, const UnitActiveState good_states
[], int nb_states
, char **args
) {
3788 _cleanup_strv_free_
char **names
= NULL
;
3789 UnitActiveState active_state
;
3795 r
= acquire_bus(BUS_MANAGER
, &bus
);
3799 r
= expand_names(bus
, args
, NULL
, &names
, NULL
);
3801 return log_error_errno(r
, "Failed to expand names: %m");
3803 STRV_FOREACH(name
, names
) {
3804 r
= get_state_one_unit(bus
, *name
, &active_state
);
3809 puts(unit_active_state_to_string(active_state
));
3811 for (i
= 0; i
< nb_states
; ++i
)
3812 if (good_states
[i
] == active_state
)
3816 /* use the given return code for the case that we won't find
3817 * any unit which matches the list */
3818 return found
? 0 : code
;
3821 static int check_unit_active(int argc
, char *argv
[], void *userdata
) {
3822 static const UnitActiveState states
[] = {
3827 /* According to LSB: 3, "program is not running" */
3828 return check_unit_generic(EXIT_PROGRAM_NOT_RUNNING
, states
, ELEMENTSOF(states
), strv_skip(argv
, 1));
3831 static int check_unit_failed(int argc
, char *argv
[], void *userdata
) {
3832 static const UnitActiveState states
[] = {
3836 return check_unit_generic(EXIT_PROGRAM_DEAD_AND_PID_EXISTS
, states
, ELEMENTSOF(states
), strv_skip(argv
, 1));
3839 static int kill_unit(int argc
, char *argv
[], void *userdata
) {
3840 _cleanup_strv_free_
char **names
= NULL
;
3841 char *kill_who
= NULL
, **name
;
3845 r
= acquire_bus(BUS_MANAGER
, &bus
);
3849 polkit_agent_open_maybe();
3852 arg_kill_who
= "all";
3854 /* --fail was specified */
3855 if (streq(arg_job_mode
, "fail"))
3856 kill_who
= strjoina(arg_kill_who
, "-fail");
3858 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
3860 return log_error_errno(r
, "Failed to expand names: %m");
3862 STRV_FOREACH(name
, names
) {
3863 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3865 q
= sd_bus_call_method(
3867 "org.freedesktop.systemd1",
3868 "/org/freedesktop/systemd1",
3869 "org.freedesktop.systemd1.Manager",
3873 "ssi", *name
, kill_who
? kill_who
: arg_kill_who
, arg_signal
);
3875 log_error_errno(q
, "Failed to kill unit %s: %s", *name
, bus_error_message(&error
, q
));
3884 static int clean_or_freeze_unit(int argc
, char *argv
[], void *userdata
) {
3885 _cleanup_(bus_wait_for_units_freep
) BusWaitForUnits
*w
= NULL
;
3886 _cleanup_strv_free_
char **names
= NULL
;
3887 int r
, ret
= EXIT_SUCCESS
;
3892 r
= acquire_bus(BUS_FULL
, &bus
);
3896 polkit_agent_open_maybe();
3898 if (!arg_clean_what
) {
3899 arg_clean_what
= strv_new("cache", "runtime");
3900 if (!arg_clean_what
)
3904 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
3906 return log_error_errno(r
, "Failed to expand names: %m");
3908 if (!arg_no_block
) {
3909 r
= bus_wait_for_units_new(bus
, &w
);
3911 return log_error_errno(r
, "Failed to allocate unit waiter: %m");
3914 if (streq(argv
[0], "clean"))
3915 method
= "CleanUnit";
3916 else if (streq(argv
[0], "freeze"))
3917 method
= "FreezeUnit";
3918 else if (streq(argv
[0], "thaw"))
3919 method
= "ThawUnit";
3921 STRV_FOREACH(name
, names
) {
3922 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3923 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
3926 /* If we shall wait for the cleaning to complete, let's add a ref on the unit first */
3927 r
= sd_bus_call_method(
3929 "org.freedesktop.systemd1",
3930 "/org/freedesktop/systemd1",
3931 "org.freedesktop.systemd1.Manager",
3937 log_error_errno(r
, "Failed to add reference to unit %s: %s", *name
, bus_error_message(&error
, r
));
3938 if (ret
== EXIT_SUCCESS
)
3944 r
= sd_bus_message_new_method_call(
3947 "org.freedesktop.systemd1",
3948 "/org/freedesktop/systemd1",
3949 "org.freedesktop.systemd1.Manager",
3952 return bus_log_create_error(r
);
3954 r
= sd_bus_message_append(m
, "s", *name
);
3956 return bus_log_create_error(r
);
3958 if (streq(method
, "CleanUnit")) {
3959 r
= sd_bus_message_append_strv(m
, arg_clean_what
);
3961 return bus_log_create_error(r
);
3964 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
3966 log_error_errno(r
, "Failed to %s unit %s: %s", argv
[0], *name
, bus_error_message(&error
, r
));
3967 if (ret
== EXIT_SUCCESS
) {
3974 r
= bus_wait_for_units_add_unit(w
, *name
, BUS_WAIT_REFFED
|BUS_WAIT_FOR_MAINTENANCE_END
, NULL
, NULL
);
3976 return log_error_errno(r
, "Failed to watch unit %s: %m", *name
);
3980 r
= bus_wait_for_units_run(w
);
3982 return log_error_errno(r
, "Failed to wait for units: %m");
3983 if (r
== BUS_WAIT_FAILURE
)
3989 typedef struct ExecStatusInfo
{
3997 usec_t start_timestamp
;
3998 usec_t exit_timestamp
;
4003 ExecCommandFlags flags
;
4005 LIST_FIELDS(struct ExecStatusInfo
, exec
);
4008 static void exec_status_info_free(ExecStatusInfo
*i
) {
4017 static int exec_status_info_deserialize(sd_bus_message
*m
, ExecStatusInfo
*i
, bool is_ex_prop
) {
4018 _cleanup_strv_free_
char **ex_opts
= NULL
;
4019 uint64_t start_timestamp
, exit_timestamp
, start_timestamp_monotonic
, exit_timestamp_monotonic
;
4022 int32_t code
, status
;
4028 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_STRUCT
, is_ex_prop
? "sasasttttuii" : "sasbttttuii");
4030 return bus_log_parse_error(r
);
4034 r
= sd_bus_message_read(m
, "s", &path
);
4036 return bus_log_parse_error(r
);
4038 i
->path
= strdup(path
);
4042 r
= sd_bus_message_read_strv(m
, &i
->argv
);
4044 return bus_log_parse_error(r
);
4046 r
= is_ex_prop
? sd_bus_message_read_strv(m
, &ex_opts
) : sd_bus_message_read(m
, "b", &ignore
);
4048 return bus_log_parse_error(r
);
4050 r
= sd_bus_message_read(m
,
4052 &start_timestamp
, &start_timestamp_monotonic
,
4053 &exit_timestamp
, &exit_timestamp_monotonic
,
4057 return bus_log_parse_error(r
);
4060 r
= exec_command_flags_from_strv(ex_opts
, &i
->flags
);
4062 return log_error_errno(r
, "Failed to convert strv to ExecCommandFlags: %m");
4064 i
->ignore
= FLAGS_SET(i
->flags
, EXEC_COMMAND_IGNORE_FAILURE
);
4068 i
->start_timestamp
= (usec_t
) start_timestamp
;
4069 i
->exit_timestamp
= (usec_t
) exit_timestamp
;
4070 i
->pid
= (pid_t
) pid
;
4074 r
= sd_bus_message_exit_container(m
);
4076 return bus_log_parse_error(r
);
4081 typedef struct UnitCondition
{
4088 LIST_FIELDS(struct UnitCondition
, conditions
);
4091 static void unit_condition_free(UnitCondition
*c
) {
4100 DEFINE_TRIVIAL_CLEANUP_FUNC(UnitCondition
*, unit_condition_free
);
4102 typedef struct UnitStatusInfo
{
4104 const char *load_state
;
4105 const char *active_state
;
4106 const char *freezer_state
;
4107 const char *sub_state
;
4108 const char *unit_file_state
;
4109 const char *unit_file_preset
;
4111 const char *description
;
4112 const char *following
;
4114 char **documentation
;
4116 const char *fragment_path
;
4117 const char *source_path
;
4118 const char *control_group
;
4120 char **dropin_paths
;
4122 char **triggered_by
;
4125 const char *load_error
;
4128 usec_t inactive_exit_timestamp
;
4129 usec_t inactive_exit_timestamp_monotonic
;
4130 usec_t active_enter_timestamp
;
4131 usec_t active_exit_timestamp
;
4132 usec_t inactive_enter_timestamp
;
4134 bool need_daemon_reload
;
4140 const char *status_text
;
4141 const char *pid_file
;
4145 usec_t start_timestamp
;
4146 usec_t exit_timestamp
;
4148 int exit_code
, exit_status
;
4150 const char *log_namespace
;
4152 usec_t condition_timestamp
;
4153 bool condition_result
;
4154 LIST_HEAD(UnitCondition
, conditions
);
4156 usec_t assert_timestamp
;
4158 bool failed_assert_trigger
;
4159 bool failed_assert_negate
;
4160 const char *failed_assert
;
4161 const char *failed_assert_parameter
;
4162 usec_t next_elapse_real
;
4163 usec_t next_elapse_monotonic
;
4166 unsigned n_accepted
;
4167 unsigned n_connections
;
4171 /* Pairs of type, path */
4175 const char *sysfs_path
;
4177 /* Mount, Automount */
4184 uint64_t memory_current
;
4185 uint64_t memory_min
;
4186 uint64_t memory_low
;
4187 uint64_t memory_high
;
4188 uint64_t memory_max
;
4189 uint64_t memory_swap_max
;
4190 uint64_t memory_limit
;
4191 uint64_t cpu_usage_nsec
;
4192 uint64_t tasks_current
;
4194 uint64_t ip_ingress_bytes
;
4195 uint64_t ip_egress_bytes
;
4196 uint64_t io_read_bytes
;
4197 uint64_t io_write_bytes
;
4199 uint64_t default_memory_min
;
4200 uint64_t default_memory_low
;
4202 LIST_HEAD(ExecStatusInfo
, exec
);
4205 static void unit_status_info_free(UnitStatusInfo
*info
) {
4209 strv_free(info
->documentation
);
4210 strv_free(info
->dropin_paths
);
4211 strv_free(info
->triggered_by
);
4212 strv_free(info
->triggers
);
4213 strv_free(info
->listen
);
4215 while ((c
= info
->conditions
)) {
4216 LIST_REMOVE(conditions
, info
->conditions
, c
);
4217 unit_condition_free(c
);
4220 while ((p
= info
->exec
)) {
4221 LIST_REMOVE(exec
, info
->exec
, p
);
4222 exec_status_info_free(p
);
4226 static void format_active_state(const char *active_state
, const char **active_on
, const char **active_off
) {
4227 if (streq_ptr(active_state
, "failed")) {
4228 *active_on
= ansi_highlight_red();
4229 *active_off
= ansi_normal();
4230 } else if (STRPTR_IN_SET(active_state
, "active", "reloading")) {
4231 *active_on
= ansi_highlight_green();
4232 *active_off
= ansi_normal();
4234 *active_on
= *active_off
= "";
4237 static void print_status_info(
4242 char since1
[FORMAT_TIMESTAMP_RELATIVE_MAX
], since2
[FORMAT_TIMESTAMP_MAX
];
4243 const char *s1
, *s2
, *active_on
, *active_off
, *on
, *off
, *ss
, *fs
;
4244 _cleanup_free_
char *formatted_path
= NULL
;
4253 /* This shows pretty information about a unit. See
4254 * print_property() for a low-level property printer */
4256 format_active_state(i
->active_state
, &active_on
, &active_off
);
4258 printf("%s%s%s %s", active_on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), active_off
, strna(i
->id
));
4260 if (i
->description
&& !streq_ptr(i
->id
, i
->description
))
4261 printf(" - %s", i
->description
);
4266 printf(" Follow: unit currently follows state of %s\n", i
->following
);
4268 if (STRPTR_IN_SET(i
->load_state
, "error", "not-found", "bad-setting")) {
4269 on
= ansi_highlight_red();
4270 off
= ansi_normal();
4274 path
= i
->source_path
?: i
->fragment_path
;
4275 if (path
&& terminal_urlify_path(path
, NULL
, &formatted_path
) >= 0)
4276 path
= formatted_path
;
4278 if (!isempty(i
->load_error
))
4279 printf(" Loaded: %s%s%s (Reason: %s)\n",
4280 on
, strna(i
->load_state
), off
, i
->load_error
);
4281 else if (path
&& !isempty(i
->unit_file_state
)) {
4282 bool show_preset
= !isempty(i
->unit_file_preset
) &&
4283 show_preset_for_state(unit_file_state_from_string(i
->unit_file_state
));
4285 printf(" Loaded: %s%s%s (%s; %s%s%s)\n",
4286 on
, strna(i
->load_state
), off
,
4289 show_preset
? "; vendor preset: " : "",
4290 show_preset
? i
->unit_file_preset
: "");
4293 printf(" Loaded: %s%s%s (%s)\n",
4294 on
, strna(i
->load_state
), off
, path
);
4296 printf(" Loaded: %s%s%s\n",
4297 on
, strna(i
->load_state
), off
);
4300 printf(" Transient: yes\n");
4302 if (!strv_isempty(i
->dropin_paths
)) {
4303 _cleanup_free_
char *dir
= NULL
;
4307 STRV_FOREACH(dropin
, i
->dropin_paths
) {
4308 _cleanup_free_
char *dropin_formatted
= NULL
;
4317 dir
= dirname_malloc(*dropin
);
4325 special_glyph(SPECIAL_GLYPH_TREE_RIGHT
));
4328 last
= ! (*(dropin
+ 1) && startswith(*(dropin
+ 1), dir
));
4330 if (terminal_urlify_path(*dropin
, basename(*dropin
), &dropin_formatted
) >= 0)
4331 df
= dropin_formatted
;
4335 printf("%s%s", df
, last
? "\n" : ", ");
4339 ss
= streq_ptr(i
->active_state
, i
->sub_state
) ? NULL
: i
->sub_state
;
4341 printf(" Active: %s%s (%s)%s",
4342 active_on
, strna(i
->active_state
), ss
, active_off
);
4344 printf(" Active: %s%s%s",
4345 active_on
, strna(i
->active_state
), active_off
);
4347 fs
= !isempty(i
->freezer_state
) && !streq(i
->freezer_state
, "running") ? i
->freezer_state
: NULL
;
4349 printf(" %s(%s)%s", ansi_highlight_yellow(), fs
, active_off
);
4351 if (!isempty(i
->result
) && !streq(i
->result
, "success"))
4352 printf(" (Result: %s)", i
->result
);
4354 timestamp
= STRPTR_IN_SET(i
->active_state
, "active", "reloading") ? i
->active_enter_timestamp
:
4355 STRPTR_IN_SET(i
->active_state
, "inactive", "failed") ? i
->inactive_enter_timestamp
:
4356 STRPTR_IN_SET(i
->active_state
, "activating") ? i
->inactive_exit_timestamp
:
4357 i
->active_exit_timestamp
;
4359 s1
= format_timestamp_relative(since1
, sizeof(since1
), timestamp
);
4360 s2
= format_timestamp(since2
, sizeof(since2
), timestamp
);
4363 printf(" since %s; %s\n", s2
, s1
);
4365 printf(" since %s\n", s2
);
4369 STRV_FOREACH(t
, i
->triggered_by
) {
4370 UnitActiveState state
= _UNIT_ACTIVE_STATE_INVALID
;
4372 (void) get_state_one_unit(bus
, *t
, &state
);
4373 format_active_state(unit_active_state_to_string(state
), &on
, &off
);
4375 printf("%s %s%s%s %s\n",
4376 t
== i
->triggered_by
? "TriggeredBy:" : " ",
4377 on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
,
4381 if (endswith(i
->id
, ".timer")) {
4382 char tstamp1
[FORMAT_TIMESTAMP_RELATIVE_MAX
],
4383 tstamp2
[FORMAT_TIMESTAMP_MAX
];
4384 const char *next_rel_time
, *next_time
;
4385 dual_timestamp nw
, next
= {i
->next_elapse_real
,
4386 i
->next_elapse_monotonic
};
4389 printf(" Trigger: ");
4391 dual_timestamp_get(&nw
);
4392 next_elapse
= calc_next_elapse(&nw
, &next
);
4393 next_rel_time
= format_timestamp_relative(tstamp1
, sizeof tstamp1
, next_elapse
);
4394 next_time
= format_timestamp(tstamp2
, sizeof tstamp2
, next_elapse
);
4396 if (next_time
&& next_rel_time
)
4397 printf("%s; %s\n", next_time
, next_rel_time
);
4402 STRV_FOREACH(t
, i
->triggers
) {
4403 UnitActiveState state
= _UNIT_ACTIVE_STATE_INVALID
;
4405 (void) get_state_one_unit(bus
, *t
, &state
);
4406 format_active_state(unit_active_state_to_string(state
), &on
, &off
);
4408 printf("%s %s%s%s %s\n",
4409 t
== i
->triggers
? " Triggers:" : " ",
4410 on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
,
4414 if (!i
->condition_result
&& i
->condition_timestamp
> 0) {
4418 s1
= format_timestamp_relative(since1
, sizeof(since1
), i
->condition_timestamp
);
4419 s2
= format_timestamp(since2
, sizeof(since2
), i
->condition_timestamp
);
4421 printf(" Condition: start %scondition failed%s at %s%s%s\n",
4422 ansi_highlight_yellow(), ansi_normal(),
4423 s2
, s1
? "; " : "", strempty(s1
));
4425 LIST_FOREACH(conditions
, c
, i
->conditions
)
4426 if (c
->tristate
< 0)
4429 LIST_FOREACH(conditions
, c
, i
->conditions
)
4430 if (c
->tristate
< 0)
4431 printf(" %s %s=%s%s%s was not met\n",
4432 --n
? special_glyph(SPECIAL_GLYPH_TREE_BRANCH
) : special_glyph(SPECIAL_GLYPH_TREE_RIGHT
),
4434 c
->trigger
? "|" : "",
4435 c
->negate
? "!" : "",
4439 if (!i
->assert_result
&& i
->assert_timestamp
> 0) {
4440 s1
= format_timestamp_relative(since1
, sizeof(since1
), i
->assert_timestamp
);
4441 s2
= format_timestamp(since2
, sizeof(since2
), i
->assert_timestamp
);
4443 printf(" Assert: start %sassertion failed%s at %s%s%s\n",
4444 ansi_highlight_red(), ansi_normal(),
4445 s2
, s1
? "; " : "", strempty(s1
));
4446 if (i
->failed_assert_trigger
)
4447 printf(" none of the trigger assertions were met\n");
4448 else if (i
->failed_assert
)
4449 printf(" %s=%s%s was not met\n",
4451 i
->failed_assert_negate
? "!" : "",
4452 i
->failed_assert_parameter
);
4456 printf(" Device: %s\n", i
->sysfs_path
);
4458 printf(" Where: %s\n", i
->where
);
4460 printf(" What: %s\n", i
->what
);
4462 STRV_FOREACH(t
, i
->documentation
) {
4463 _cleanup_free_
char *formatted
= NULL
;
4466 if (terminal_urlify(*t
, NULL
, &formatted
) >= 0)
4471 printf(" %*s %s\n", 9, t
== i
->documentation
? "Docs:" : "", q
);
4474 STRV_FOREACH_PAIR(t
, t2
, i
->listen
)
4475 printf(" %*s %s (%s)\n", 9, t
== i
->listen
? "Listen:" : "", *t2
, *t
);
4478 printf(" Accepted: %u; Connected: %u;", i
->n_accepted
, i
->n_connections
);
4480 printf(" Refused: %u", i
->n_refused
);
4484 LIST_FOREACH(exec
, p
, i
->exec
) {
4485 _cleanup_free_
char *argv
= NULL
;
4488 /* Only show exited processes here */
4492 /* Don't print ExecXYZEx= properties here since it will appear as a
4493 * duplicate of the non-Ex= variant. */
4494 if (endswith(p
->name
, "Ex"))
4497 argv
= strv_join(p
->argv
, " ");
4498 printf(" Process: "PID_FMT
" %s=%s ", p
->pid
, p
->name
, strna(argv
));
4500 good
= is_clean_exit(p
->code
, p
->status
, EXIT_CLEAN_DAEMON
, NULL
);
4502 on
= ansi_highlight_red();
4503 off
= ansi_normal();
4507 printf("%s(code=%s, ", on
, sigchld_code_to_string(p
->code
));
4509 if (p
->code
== CLD_EXITED
) {
4512 printf("status=%i", p
->status
);
4514 c
= exit_status_to_string(p
->status
, EXIT_STATUS_LIBC
| EXIT_STATUS_SYSTEMD
);
4519 printf("signal=%s", signal_to_string(p
->status
));
4521 printf(")%s\n", off
);
4523 if (i
->main_pid
== p
->pid
&&
4524 i
->start_timestamp
== p
->start_timestamp
&&
4525 i
->exit_timestamp
== p
->start_timestamp
)
4526 /* Let's not show this twice */
4529 if (p
->pid
== i
->control_pid
)
4533 if (i
->main_pid
> 0 || i
->control_pid
> 0) {
4534 if (i
->main_pid
> 0) {
4535 printf(" Main PID: "PID_FMT
, i
->main_pid
);
4539 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
4540 _cleanup_free_
char *comm
= NULL
;
4542 (void) get_process_comm(i
->main_pid
, &comm
);
4544 printf(" (%s)", comm
);
4547 } else if (i
->exit_code
> 0) {
4548 printf(" (code=%s, ", sigchld_code_to_string(i
->exit_code
));
4550 if (i
->exit_code
== CLD_EXITED
) {
4553 printf("status=%i", i
->exit_status
);
4555 c
= exit_status_to_string(i
->exit_status
,
4556 EXIT_STATUS_LIBC
| EXIT_STATUS_SYSTEMD
);
4561 printf("signal=%s", signal_to_string(i
->exit_status
));
4566 if (i
->control_pid
> 0) {
4567 _cleanup_free_
char *c
= NULL
;
4569 if (i
->main_pid
> 0)
4570 fputs("; Control PID: ", stdout
);
4572 fputs("Cntrl PID: ", stdout
); /* if first in column, abbreviated so it fits alignment */
4574 printf(PID_FMT
, i
->control_pid
);
4576 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
4577 (void) get_process_comm(i
->control_pid
, &c
);
4587 printf(" Status: \"%s\"\n", i
->status_text
);
4588 if (i
->status_errno
> 0)
4589 printf(" Error: %i (%s)\n", i
->status_errno
, strerror_safe(i
->status_errno
));
4591 if (i
->ip_ingress_bytes
!= (uint64_t) -1 && i
->ip_egress_bytes
!= (uint64_t) -1) {
4592 char buf_in
[FORMAT_BYTES_MAX
], buf_out
[FORMAT_BYTES_MAX
];
4594 printf(" IP: %s in, %s out\n",
4595 format_bytes(buf_in
, sizeof(buf_in
), i
->ip_ingress_bytes
),
4596 format_bytes(buf_out
, sizeof(buf_out
), i
->ip_egress_bytes
));
4599 if (i
->io_read_bytes
!= UINT64_MAX
&& i
->io_write_bytes
!= UINT64_MAX
) {
4600 char buf_in
[FORMAT_BYTES_MAX
], buf_out
[FORMAT_BYTES_MAX
];
4602 printf(" IO: %s read, %s written\n",
4603 format_bytes(buf_in
, sizeof(buf_in
), i
->io_read_bytes
),
4604 format_bytes(buf_out
, sizeof(buf_out
), i
->io_write_bytes
));
4607 if (i
->tasks_current
!= (uint64_t) -1) {
4608 printf(" Tasks: %" PRIu64
, i
->tasks_current
);
4610 if (i
->tasks_max
!= (uint64_t) -1)
4611 printf(" (limit: %" PRIu64
")\n", i
->tasks_max
);
4616 if (i
->memory_current
!= (uint64_t) -1) {
4617 char buf
[FORMAT_BYTES_MAX
];
4619 printf(" Memory: %s", format_bytes(buf
, sizeof(buf
), i
->memory_current
));
4621 if (i
->memory_min
> 0 || i
->memory_low
> 0 ||
4622 i
->memory_high
!= CGROUP_LIMIT_MAX
|| i
->memory_max
!= CGROUP_LIMIT_MAX
||
4623 i
->memory_swap_max
!= CGROUP_LIMIT_MAX
||
4624 i
->memory_limit
!= CGROUP_LIMIT_MAX
) {
4625 const char *prefix
= "";
4628 if (i
->memory_min
> 0) {
4629 printf("%smin: %s", prefix
, format_bytes_cgroup_protection(buf
, sizeof(buf
), i
->memory_min
));
4632 if (i
->memory_low
> 0) {
4633 printf("%slow: %s", prefix
, format_bytes_cgroup_protection(buf
, sizeof(buf
), i
->memory_low
));
4636 if (i
->memory_high
!= CGROUP_LIMIT_MAX
) {
4637 printf("%shigh: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_high
));
4640 if (i
->memory_max
!= CGROUP_LIMIT_MAX
) {
4641 printf("%smax: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_max
));
4644 if (i
->memory_swap_max
!= CGROUP_LIMIT_MAX
) {
4645 printf("%sswap max: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_swap_max
));
4648 if (i
->memory_limit
!= CGROUP_LIMIT_MAX
) {
4649 printf("%slimit: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_limit
));
4657 if (i
->cpu_usage_nsec
!= (uint64_t) -1) {
4658 char buf
[FORMAT_TIMESPAN_MAX
];
4659 printf(" CPU: %s\n", format_timespan(buf
, sizeof(buf
), i
->cpu_usage_nsec
/ NSEC_PER_USEC
, USEC_PER_MSEC
));
4662 if (i
->control_group
) {
4663 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
4664 static const char prefix
[] = " ";
4667 printf(" CGroup: %s\n", i
->control_group
);
4670 if (c
> sizeof(prefix
) - 1)
4671 c
-= sizeof(prefix
) - 1;
4675 r
= unit_show_processes(bus
, i
->id
, i
->control_group
, prefix
, c
, get_output_flags(), &error
);
4680 /* Fallback for older systemd versions where the GetUnitProcesses() call is not yet available */
4682 if (i
->main_pid
> 0)
4683 extra
[k
++] = i
->main_pid
;
4685 if (i
->control_pid
> 0)
4686 extra
[k
++] = i
->control_pid
;
4688 show_cgroup_and_extra(SYSTEMD_CGROUP_CONTROLLER
, i
->control_group
, prefix
, c
, extra
, k
, get_output_flags());
4690 log_warning_errno(r
, "Failed to dump process list for '%s', ignoring: %s",
4691 i
->id
, bus_error_message(&error
, r
));
4694 if (i
->id
&& arg_transport
== BUS_TRANSPORT_LOCAL
)
4695 show_journal_by_unit(
4701 i
->inactive_exit_timestamp_monotonic
,
4704 get_output_flags() | OUTPUT_BEGIN_NEWLINE
,
4705 SD_JOURNAL_LOCAL_ONLY
,
4706 arg_scope
== UNIT_FILE_SYSTEM
,
4709 if (i
->need_daemon_reload
)
4710 warn_unit_file_changed(i
->id
);
4713 static void show_unit_help(UnitStatusInfo
*i
) {
4718 if (!i
->documentation
) {
4719 log_info("Documentation for %s not known.", i
->id
);
4723 STRV_FOREACH(p
, i
->documentation
)
4724 if (startswith(*p
, "man:"))
4725 show_man_page(*p
+ 4, false);
4727 log_info("Can't show: %s", *p
);
4730 static int map_main_pid(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4731 UnitStatusInfo
*i
= userdata
;
4735 r
= sd_bus_message_read(m
, "u", &u
);
4739 i
->main_pid
= (pid_t
) u
;
4745 static int map_load_error(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4746 const char *message
, **p
= userdata
;
4749 r
= sd_bus_message_read(m
, "(ss)", NULL
, &message
);
4753 if (!isempty(message
))
4759 static int map_listen(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4760 const char *type
, *path
;
4761 char ***p
= userdata
;
4764 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
4768 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0) {
4770 r
= strv_extend(p
, type
);
4774 r
= strv_extend(p
, path
);
4781 r
= sd_bus_message_exit_container(m
);
4788 static int map_conditions(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4789 UnitStatusInfo
*i
= userdata
;
4790 const char *cond
, *param
;
4791 int trigger
, negate
;
4795 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sbbsi)");
4799 while ((r
= sd_bus_message_read(m
, "(sbbsi)", &cond
, &trigger
, &negate
, ¶m
, &state
)) > 0) {
4800 _cleanup_(unit_condition_freep
) UnitCondition
*c
= NULL
;
4802 c
= new(UnitCondition
, 1);
4806 *c
= (UnitCondition
) {
4807 .name
= strdup(cond
),
4808 .param
= strdup(param
),
4814 if (!c
->name
|| !c
->param
)
4817 LIST_PREPEND(conditions
, i
->conditions
, TAKE_PTR(c
));
4822 r
= sd_bus_message_exit_container(m
);
4829 static int map_asserts(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4830 UnitStatusInfo
*i
= userdata
;
4831 const char *cond
, *param
;
4832 int trigger
, negate
;
4836 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sbbsi)");
4840 while ((r
= sd_bus_message_read(m
, "(sbbsi)", &cond
, &trigger
, &negate
, ¶m
, &state
)) > 0) {
4841 if (state
< 0 && (!trigger
|| !i
->failed_assert
)) {
4842 i
->failed_assert
= cond
;
4843 i
->failed_assert_trigger
= trigger
;
4844 i
->failed_assert_negate
= negate
;
4845 i
->failed_assert_parameter
= param
;
4851 r
= sd_bus_message_exit_container(m
);
4858 static int map_exec(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4859 _cleanup_free_ ExecStatusInfo
*info
= NULL
;
4860 ExecStatusInfo
*last
;
4861 UnitStatusInfo
*i
= userdata
;
4862 bool is_ex_prop
= endswith(member
, "Ex");
4865 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, is_ex_prop
? "(sasasttttuii)" : "(sasbttttuii)");
4869 info
= new0(ExecStatusInfo
, 1);
4873 LIST_FIND_TAIL(exec
, i
->exec
, last
);
4875 while ((r
= exec_status_info_deserialize(m
, info
, is_ex_prop
)) > 0) {
4877 info
->name
= strdup(member
);
4881 LIST_INSERT_AFTER(exec
, i
->exec
, last
, info
);
4884 info
= new0(ExecStatusInfo
, 1);
4891 r
= sd_bus_message_exit_container(m
);
4898 static int print_property(const char *name
, const char *expected_value
, sd_bus_message
*m
, bool value
, bool all
) {
4900 const char *contents
;
4906 /* This is a low-level property printer, see
4907 * print_status_info() for the nicer output */
4909 r
= sd_bus_message_peek_type(m
, &bus_type
, &contents
);
4915 case SD_BUS_TYPE_INT32
:
4916 if (endswith(name
, "ActionExitStatus")) {
4919 r
= sd_bus_message_read_basic(m
, bus_type
, &i
);
4923 if (i
>= 0 && i
<= 255)
4924 bus_print_property_valuef(name
, expected_value
, value
, "%"PRIi32
, i
);
4926 bus_print_property_value(name
, expected_value
, value
, "[not set]");
4929 } else if (streq(name
, "NUMAPolicy")) {
4932 r
= sd_bus_message_read_basic(m
, bus_type
, &i
);
4936 bus_print_property_valuef(name
, expected_value
, value
, "%s", strna(mpol_to_string(i
)));
4942 case SD_BUS_TYPE_STRUCT
:
4944 if (contents
[0] == SD_BUS_TYPE_UINT32
&& streq(name
, "Job")) {
4947 r
= sd_bus_message_read(m
, "(uo)", &u
, NULL
);
4949 return bus_log_parse_error(r
);
4952 bus_print_property_valuef(name
, expected_value
, value
, "%"PRIu32
, u
);
4954 bus_print_property_value(name
, expected_value
, value
, "");
4958 } else if (contents
[0] == SD_BUS_TYPE_STRING
&& streq(name
, "Unit")) {
4961 r
= sd_bus_message_read(m
, "(so)", &s
, NULL
);
4963 return bus_log_parse_error(r
);
4965 if (all
|| !isempty(s
))
4966 bus_print_property_value(name
, expected_value
, value
, s
);
4970 } else if (contents
[0] == SD_BUS_TYPE_STRING
&& streq(name
, "LoadError")) {
4971 const char *a
= NULL
, *b
= NULL
;
4973 r
= sd_bus_message_read(m
, "(ss)", &a
, &b
);
4975 return bus_log_parse_error(r
);
4977 if (!isempty(a
) || !isempty(b
))
4978 bus_print_property_valuef(name
, expected_value
, value
, "%s \"%s\"", strempty(a
), strempty(b
));
4980 bus_print_property_value(name
, expected_value
, value
, "");
4984 } else if (STR_IN_SET(name
, "SystemCallFilter", "RestrictAddressFamilies")) {
4985 _cleanup_strv_free_
char **l
= NULL
;
4988 r
= sd_bus_message_enter_container(m
, 'r', "bas");
4990 return bus_log_parse_error(r
);
4992 r
= sd_bus_message_read(m
, "b", &whitelist
);
4994 return bus_log_parse_error(r
);
4996 r
= sd_bus_message_read_strv(m
, &l
);
4998 return bus_log_parse_error(r
);
5000 r
= sd_bus_message_exit_container(m
);
5002 return bus_log_parse_error(r
);
5004 if (all
|| whitelist
|| !strv_isempty(l
)) {
5009 fputs(name
, stdout
);
5016 STRV_FOREACH(i
, l
) {
5024 fputc('\n', stdout
);
5029 } else if (STR_IN_SET(name
, "SELinuxContext", "AppArmorProfile", "SmackProcessLabel")) {
5033 r
= sd_bus_message_read(m
, "(bs)", &ignore
, &s
);
5035 return bus_log_parse_error(r
);
5038 bus_print_property_valuef(name
, expected_value
, value
, "%s%s", ignore
? "-" : "", s
);
5040 bus_print_property_value(name
, expected_value
, value
, "");
5044 } else if (endswith(name
, "ExitStatus") && streq(contents
, "aiai")) {
5045 const int32_t *status
, *signal
;
5046 size_t n_status
, n_signal
, i
;
5048 r
= sd_bus_message_enter_container(m
, 'r', "aiai");
5050 return bus_log_parse_error(r
);
5052 r
= sd_bus_message_read_array(m
, 'i', (const void **) &status
, &n_status
);
5054 return bus_log_parse_error(r
);
5056 r
= sd_bus_message_read_array(m
, 'i', (const void **) &signal
, &n_signal
);
5058 return bus_log_parse_error(r
);
5060 r
= sd_bus_message_exit_container(m
);
5062 return bus_log_parse_error(r
);
5064 n_status
/= sizeof(int32_t);
5065 n_signal
/= sizeof(int32_t);
5067 if (all
|| n_status
> 0 || n_signal
> 0) {
5071 fputs(name
, stdout
);
5075 for (i
= 0; i
< n_status
; i
++) {
5081 printf("%"PRIi32
, status
[i
]);
5084 for (i
= 0; i
< n_signal
; i
++) {
5087 str
= signal_to_string((int) signal
[i
]);
5097 printf("%"PRIi32
, status
[i
]);
5100 fputc('\n', stdout
);
5107 case SD_BUS_TYPE_ARRAY
:
5109 if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "EnvironmentFiles")) {
5113 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sb)");
5115 return bus_log_parse_error(r
);
5117 while ((r
= sd_bus_message_read(m
, "(sb)", &path
, &ignore
)) > 0)
5118 bus_print_property_valuef(name
, expected_value
, value
, "%s (ignore_errors=%s)", path
, yes_no(ignore
));
5121 return bus_log_parse_error(r
);
5123 r
= sd_bus_message_exit_container(m
);
5125 return bus_log_parse_error(r
);
5129 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "Paths")) {
5130 const char *type
, *path
;
5132 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5134 return bus_log_parse_error(r
);
5136 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0)
5137 bus_print_property_valuef(name
, expected_value
, value
, "%s (%s)", path
, type
);
5139 return bus_log_parse_error(r
);
5141 r
= sd_bus_message_exit_container(m
);
5143 return bus_log_parse_error(r
);
5147 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "Listen")) {
5148 const char *type
, *path
;
5150 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5152 return bus_log_parse_error(r
);
5154 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0)
5155 bus_print_property_valuef(name
, expected_value
, value
, "%s (%s)", path
, type
);
5157 return bus_log_parse_error(r
);
5159 r
= sd_bus_message_exit_container(m
);
5161 return bus_log_parse_error(r
);
5165 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "TimersMonotonic")) {
5167 uint64_t v
, next_elapse
;
5169 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(stt)");
5171 return bus_log_parse_error(r
);
5173 while ((r
= sd_bus_message_read(m
, "(stt)", &base
, &v
, &next_elapse
)) > 0) {
5174 char timespan1
[FORMAT_TIMESPAN_MAX
] = "n/a", timespan2
[FORMAT_TIMESPAN_MAX
] = "n/a";
5176 (void) format_timespan(timespan1
, sizeof timespan1
, v
, 0);
5177 (void) format_timespan(timespan2
, sizeof timespan2
, next_elapse
, 0);
5179 bus_print_property_valuef(name
, expected_value
, value
,
5180 "{ %s=%s ; next_elapse=%s }", base
, timespan1
, timespan2
);
5183 return bus_log_parse_error(r
);
5185 r
= sd_bus_message_exit_container(m
);
5187 return bus_log_parse_error(r
);
5191 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "TimersCalendar")) {
5192 const char *base
, *spec
;
5193 uint64_t next_elapse
;
5195 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sst)");
5197 return bus_log_parse_error(r
);
5199 while ((r
= sd_bus_message_read(m
, "(sst)", &base
, &spec
, &next_elapse
)) > 0) {
5200 char timestamp
[FORMAT_TIMESTAMP_MAX
] = "n/a";
5202 (void) format_timestamp(timestamp
, sizeof(timestamp
), next_elapse
);
5203 bus_print_property_valuef(name
, expected_value
, value
,
5204 "{ %s=%s ; next_elapse=%s }", base
, spec
, timestamp
);
5207 return bus_log_parse_error(r
);
5209 r
= sd_bus_message_exit_container(m
);
5211 return bus_log_parse_error(r
);
5215 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& startswith(name
, "Exec")) {
5216 ExecStatusInfo info
= {};
5217 bool is_ex_prop
= endswith(name
, "Ex");
5219 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, is_ex_prop
? "(sasasttttuii)" : "(sasbttttuii)");
5221 return bus_log_parse_error(r
);
5223 while ((r
= exec_status_info_deserialize(m
, &info
, is_ex_prop
)) > 0) {
5224 char timestamp1
[FORMAT_TIMESTAMP_MAX
], timestamp2
[FORMAT_TIMESTAMP_MAX
];
5225 _cleanup_strv_free_
char **optv
= NULL
;
5226 _cleanup_free_
char *tt
, *o
= NULL
;
5228 tt
= strv_join(info
.argv
, " ");
5231 r
= exec_command_flags_to_strv(info
.flags
, &optv
);
5233 return log_error_errno(r
, "Failed to convert ExecCommandFlags to strv: %m");
5235 o
= strv_join(optv
, " ");
5237 bus_print_property_valuef(name
, expected_value
, value
,
5238 "{ path=%s ; argv[]=%s ; flags=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT
" ; code=%s ; status=%i%s%s }",
5242 strna(format_timestamp(timestamp1
, sizeof(timestamp1
), info
.start_timestamp
)),
5243 strna(format_timestamp(timestamp2
, sizeof(timestamp2
), info
.exit_timestamp
)),
5245 sigchld_code_to_string(info
.code
),
5247 info
.code
== CLD_EXITED
? "" : "/",
5248 strempty(info
.code
== CLD_EXITED
? NULL
: signal_to_string(info
.status
)));
5250 bus_print_property_valuef(name
, expected_value
, value
,
5251 "{ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT
" ; code=%s ; status=%i%s%s }",
5254 yes_no(info
.ignore
),
5255 strna(format_timestamp(timestamp1
, sizeof(timestamp1
), info
.start_timestamp
)),
5256 strna(format_timestamp(timestamp2
, sizeof(timestamp2
), info
.exit_timestamp
)),
5258 sigchld_code_to_string(info
.code
),
5260 info
.code
== CLD_EXITED
? "" : "/",
5261 strempty(info
.code
== CLD_EXITED
? NULL
: signal_to_string(info
.status
)));
5264 strv_free(info
.argv
);
5268 r
= sd_bus_message_exit_container(m
);
5270 return bus_log_parse_error(r
);
5274 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "DeviceAllow")) {
5275 const char *path
, *rwm
;
5277 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5279 return bus_log_parse_error(r
);
5281 while ((r
= sd_bus_message_read(m
, "(ss)", &path
, &rwm
)) > 0)
5282 bus_print_property_valuef(name
, expected_value
, value
, "%s %s", strna(path
), strna(rwm
));
5284 return bus_log_parse_error(r
);
5286 r
= sd_bus_message_exit_container(m
);
5288 return bus_log_parse_error(r
);
5292 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5293 STR_IN_SET(name
, "IODeviceWeight", "BlockIODeviceWeight")) {
5297 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5299 return bus_log_parse_error(r
);
5301 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &weight
)) > 0)
5302 bus_print_property_valuef(name
, expected_value
, value
, "%s %"PRIu64
, strna(path
), weight
);
5304 return bus_log_parse_error(r
);
5306 r
= sd_bus_message_exit_container(m
);
5308 return bus_log_parse_error(r
);
5312 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5313 (cgroup_io_limit_type_from_string(name
) >= 0 ||
5314 STR_IN_SET(name
, "BlockIOReadBandwidth", "BlockIOWriteBandwidth"))) {
5318 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5320 return bus_log_parse_error(r
);
5322 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &bandwidth
)) > 0)
5323 bus_print_property_valuef(name
, expected_value
, value
, "%s %"PRIu64
, strna(path
), bandwidth
);
5325 return bus_log_parse_error(r
);
5327 r
= sd_bus_message_exit_container(m
);
5329 return bus_log_parse_error(r
);
5333 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5334 streq(name
, "IODeviceLatencyTargetUSec")) {
5335 char ts
[FORMAT_TIMESPAN_MAX
];
5339 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5341 return bus_log_parse_error(r
);
5343 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &target
)) > 0)
5344 bus_print_property_valuef(name
, expected_value
, value
, "%s %s", strna(path
),
5345 format_timespan(ts
, sizeof(ts
), target
, 1));
5347 return bus_log_parse_error(r
);
5349 r
= sd_bus_message_exit_container(m
);
5351 return bus_log_parse_error(r
);
5355 } else if (contents
[0] == SD_BUS_TYPE_BYTE
&& streq(name
, "StandardInputData")) {
5356 _cleanup_free_
char *h
= NULL
;
5361 r
= sd_bus_message_read_array(m
, 'y', &p
, &sz
);
5363 return bus_log_parse_error(r
);
5365 n
= base64mem(p
, sz
, &h
);
5369 bus_print_property_value(name
, expected_value
, value
, h
);
5373 } else if (STR_IN_SET(name
, "IPAddressAllow", "IPAddressDeny")) {
5374 _cleanup_free_
char *addresses
= NULL
;
5376 r
= sd_bus_message_enter_container(m
, 'a', "(iayu)");
5378 return bus_log_parse_error(r
);
5381 _cleanup_free_
char *str
= NULL
;
5387 r
= sd_bus_message_enter_container(m
, 'r', "iayu");
5389 return bus_log_parse_error(r
);
5393 r
= sd_bus_message_read(m
, "i", &family
);
5395 return bus_log_parse_error(r
);
5397 r
= sd_bus_message_read_array(m
, 'y', &ap
, &an
);
5399 return bus_log_parse_error(r
);
5401 r
= sd_bus_message_read(m
, "u", &prefixlen
);
5403 return bus_log_parse_error(r
);
5405 r
= sd_bus_message_exit_container(m
);
5407 return bus_log_parse_error(r
);
5409 if (!IN_SET(family
, AF_INET
, AF_INET6
))
5412 if (an
!= FAMILY_ADDRESS_SIZE(family
))
5415 if (prefixlen
> FAMILY_ADDRESS_SIZE(family
) * 8)
5418 if (in_addr_prefix_to_string(family
, (union in_addr_union
*) ap
, prefixlen
, &str
) < 0)
5421 if (!strextend_with_separator(&addresses
, " ", str
, NULL
))
5425 r
= sd_bus_message_exit_container(m
);
5427 return bus_log_parse_error(r
);
5429 if (all
|| !isempty(addresses
))
5430 bus_print_property_value(name
, expected_value
, value
, strempty(addresses
));
5434 } else if (STR_IN_SET(name
, "BindPaths", "BindReadOnlyPaths")) {
5435 _cleanup_free_
char *paths
= NULL
;
5436 const char *source
, *dest
;
5440 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ssbt)");
5442 return bus_log_parse_error(r
);
5444 while ((r
= sd_bus_message_read(m
, "(ssbt)", &source
, &dest
, &ignore_enoent
, &rbind
)) > 0) {
5445 _cleanup_free_
char *str
= NULL
;
5447 if (isempty(source
))
5450 if (asprintf(&str
, "%s%s%s%s%s",
5451 ignore_enoent
? "-" : "",
5453 isempty(dest
) ? "" : ":",
5455 rbind
== MS_REC
? ":rbind" : "") < 0)
5458 if (!strextend_with_separator(&paths
, " ", str
, NULL
))
5462 return bus_log_parse_error(r
);
5464 r
= sd_bus_message_exit_container(m
);
5466 return bus_log_parse_error(r
);
5468 if (all
|| !isempty(paths
))
5469 bus_print_property_value(name
, expected_value
, value
, strempty(paths
));
5473 } else if (streq(name
, "TemporaryFileSystem")) {
5474 _cleanup_free_
char *paths
= NULL
;
5475 const char *target
, *option
;
5477 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5479 return bus_log_parse_error(r
);
5481 while ((r
= sd_bus_message_read(m
, "(ss)", &target
, &option
)) > 0) {
5482 _cleanup_free_
char *str
= NULL
;
5484 if (isempty(target
))
5487 if (asprintf(&str
, "%s%s%s", target
, isempty(option
) ? "" : ":", strempty(option
)) < 0)
5490 if (!strextend_with_separator(&paths
, " ", str
, NULL
))
5494 return bus_log_parse_error(r
);
5496 r
= sd_bus_message_exit_container(m
);
5498 return bus_log_parse_error(r
);
5500 if (all
|| !isempty(paths
))
5501 bus_print_property_value(name
, expected_value
, value
, strempty(paths
));
5505 } else if (streq(name
, "LogExtraFields")) {
5506 _cleanup_free_
char *fields
= NULL
;
5510 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "ay");
5512 return bus_log_parse_error(r
);
5514 while ((r
= sd_bus_message_read_array(m
, 'y', &p
, &sz
)) > 0) {
5515 _cleanup_free_
char *str
= NULL
;
5518 if (memchr(p
, 0, sz
))
5521 eq
= memchr(p
, '=', sz
);
5525 if (!journal_field_valid(p
, eq
- (const char*) p
, false))
5528 str
= malloc(sz
+ 1);
5535 if (!utf8_is_valid(str
))
5538 if (!strextend_with_separator(&fields
, " ", str
, NULL
))
5542 return bus_log_parse_error(r
);
5544 r
= sd_bus_message_exit_container(m
);
5546 return bus_log_parse_error(r
);
5548 if (all
|| !isempty(fields
))
5549 bus_print_property_value(name
, expected_value
, value
, strempty(fields
));
5552 } else if (contents
[0] == SD_BUS_TYPE_BYTE
&& STR_IN_SET(name
, "CPUAffinity", "NUMAMask", "AllowedCPUs", "AllowedMemoryNodes", "EffectiveCPUs", "EffectiveMemoryNodes")) {
5553 _cleanup_free_
char *affinity
= NULL
;
5554 _cleanup_(cpu_set_reset
) CPUSet set
= {};
5558 r
= sd_bus_message_read_array(m
, 'y', &a
, &n
);
5560 return bus_log_parse_error(r
);
5562 r
= cpu_set_from_dbus(a
, n
, &set
);
5564 return log_error_errno(r
, "Failed to deserialize %s: %m", name
);
5566 affinity
= cpu_set_to_range_string(&set
);
5570 bus_print_property_value(name
, expected_value
, value
, affinity
);
5581 typedef enum SystemctlShowMode
{
5582 SYSTEMCTL_SHOW_PROPERTIES
,
5583 SYSTEMCTL_SHOW_STATUS
,
5584 SYSTEMCTL_SHOW_HELP
,
5585 _SYSTEMCTL_SHOW_MODE_MAX
,
5586 _SYSTEMCTL_SHOW_MODE_INVALID
= -1,
5587 } SystemctlShowMode
;
5589 static const char* const systemctl_show_mode_table
[_SYSTEMCTL_SHOW_MODE_MAX
] = {
5590 [SYSTEMCTL_SHOW_PROPERTIES
] = "show",
5591 [SYSTEMCTL_SHOW_STATUS
] = "status",
5592 [SYSTEMCTL_SHOW_HELP
] = "help",
5595 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(systemctl_show_mode
, SystemctlShowMode
);
5597 static int show_one(
5601 SystemctlShowMode show_mode
,
5605 static const struct bus_properties_map property_map
[] = {
5606 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
5607 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
) },
5608 { "FreezerState", "s", NULL
, offsetof(UnitStatusInfo
, freezer_state
) },
5609 { "Documentation", "as", NULL
, offsetof(UnitStatusInfo
, documentation
) },
5612 { "Id", "s", NULL
, offsetof(UnitStatusInfo
, id
) },
5613 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
5614 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
) },
5615 { "FreezerState", "s", NULL
, offsetof(UnitStatusInfo
, freezer_state
) },
5616 { "SubState", "s", NULL
, offsetof(UnitStatusInfo
, sub_state
) },
5617 { "UnitFileState", "s", NULL
, offsetof(UnitStatusInfo
, unit_file_state
) },
5618 { "UnitFilePreset", "s", NULL
, offsetof(UnitStatusInfo
, unit_file_preset
) },
5619 { "Description", "s", NULL
, offsetof(UnitStatusInfo
, description
) },
5620 { "Following", "s", NULL
, offsetof(UnitStatusInfo
, following
) },
5621 { "Documentation", "as", NULL
, offsetof(UnitStatusInfo
, documentation
) },
5622 { "FragmentPath", "s", NULL
, offsetof(UnitStatusInfo
, fragment_path
) },
5623 { "SourcePath", "s", NULL
, offsetof(UnitStatusInfo
, source_path
) },
5624 { "ControlGroup", "s", NULL
, offsetof(UnitStatusInfo
, control_group
) },
5625 { "DropInPaths", "as", NULL
, offsetof(UnitStatusInfo
, dropin_paths
) },
5626 { "LoadError", "(ss)", map_load_error
, offsetof(UnitStatusInfo
, load_error
) },
5627 { "Result", "s", NULL
, offsetof(UnitStatusInfo
, result
) },
5628 { "TriggeredBy", "as", NULL
, offsetof(UnitStatusInfo
, triggered_by
) },
5629 { "Triggers", "as", NULL
, offsetof(UnitStatusInfo
, triggers
) },
5630 { "InactiveExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, inactive_exit_timestamp
) },
5631 { "InactiveExitTimestampMonotonic", "t", NULL
, offsetof(UnitStatusInfo
, inactive_exit_timestamp_monotonic
) },
5632 { "ActiveEnterTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, active_enter_timestamp
) },
5633 { "ActiveExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, active_exit_timestamp
) },
5634 { "InactiveEnterTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, inactive_enter_timestamp
) },
5635 { "NeedDaemonReload", "b", NULL
, offsetof(UnitStatusInfo
, need_daemon_reload
) },
5636 { "Transient", "b", NULL
, offsetof(UnitStatusInfo
, transient
) },
5637 { "ExecMainPID", "u", NULL
, offsetof(UnitStatusInfo
, main_pid
) },
5638 { "MainPID", "u", map_main_pid
, 0 },
5639 { "ControlPID", "u", NULL
, offsetof(UnitStatusInfo
, control_pid
) },
5640 { "StatusText", "s", NULL
, offsetof(UnitStatusInfo
, status_text
) },
5641 { "PIDFile", "s", NULL
, offsetof(UnitStatusInfo
, pid_file
) },
5642 { "StatusErrno", "i", NULL
, offsetof(UnitStatusInfo
, status_errno
) },
5643 { "ExecMainStartTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, start_timestamp
) },
5644 { "ExecMainExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, exit_timestamp
) },
5645 { "ExecMainCode", "i", NULL
, offsetof(UnitStatusInfo
, exit_code
) },
5646 { "ExecMainStatus", "i", NULL
, offsetof(UnitStatusInfo
, exit_status
) },
5647 { "LogNamespace", "s", NULL
, offsetof(UnitStatusInfo
, log_namespace
) },
5648 { "ConditionTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, condition_timestamp
) },
5649 { "ConditionResult", "b", NULL
, offsetof(UnitStatusInfo
, condition_result
) },
5650 { "Conditions", "a(sbbsi)", map_conditions
, 0 },
5651 { "AssertTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, assert_timestamp
) },
5652 { "AssertResult", "b", NULL
, offsetof(UnitStatusInfo
, assert_result
) },
5653 { "Asserts", "a(sbbsi)", map_asserts
, 0 },
5654 { "NextElapseUSecRealtime", "t", NULL
, offsetof(UnitStatusInfo
, next_elapse_real
) },
5655 { "NextElapseUSecMonotonic", "t", NULL
, offsetof(UnitStatusInfo
, next_elapse_monotonic
) },
5656 { "NAccepted", "u", NULL
, offsetof(UnitStatusInfo
, n_accepted
) },
5657 { "NConnections", "u", NULL
, offsetof(UnitStatusInfo
, n_connections
) },
5658 { "NRefused", "u", NULL
, offsetof(UnitStatusInfo
, n_refused
) },
5659 { "Accept", "b", NULL
, offsetof(UnitStatusInfo
, accept
) },
5660 { "Listen", "a(ss)", map_listen
, offsetof(UnitStatusInfo
, listen
) },
5661 { "SysFSPath", "s", NULL
, offsetof(UnitStatusInfo
, sysfs_path
) },
5662 { "Where", "s", NULL
, offsetof(UnitStatusInfo
, where
) },
5663 { "What", "s", NULL
, offsetof(UnitStatusInfo
, what
) },
5664 { "MemoryCurrent", "t", NULL
, offsetof(UnitStatusInfo
, memory_current
) },
5665 { "DefaultMemoryMin", "t", NULL
, offsetof(UnitStatusInfo
, default_memory_min
) },
5666 { "DefaultMemoryLow", "t", NULL
, offsetof(UnitStatusInfo
, default_memory_low
) },
5667 { "MemoryMin", "t", NULL
, offsetof(UnitStatusInfo
, memory_min
) },
5668 { "MemoryLow", "t", NULL
, offsetof(UnitStatusInfo
, memory_low
) },
5669 { "MemoryHigh", "t", NULL
, offsetof(UnitStatusInfo
, memory_high
) },
5670 { "MemoryMax", "t", NULL
, offsetof(UnitStatusInfo
, memory_max
) },
5671 { "MemorySwapMax", "t", NULL
, offsetof(UnitStatusInfo
, memory_swap_max
) },
5672 { "MemoryLimit", "t", NULL
, offsetof(UnitStatusInfo
, memory_limit
) },
5673 { "CPUUsageNSec", "t", NULL
, offsetof(UnitStatusInfo
, cpu_usage_nsec
) },
5674 { "TasksCurrent", "t", NULL
, offsetof(UnitStatusInfo
, tasks_current
) },
5675 { "TasksMax", "t", NULL
, offsetof(UnitStatusInfo
, tasks_max
) },
5676 { "IPIngressBytes", "t", NULL
, offsetof(UnitStatusInfo
, ip_ingress_bytes
) },
5677 { "IPEgressBytes", "t", NULL
, offsetof(UnitStatusInfo
, ip_egress_bytes
) },
5678 { "IOReadBytes", "t", NULL
, offsetof(UnitStatusInfo
, io_read_bytes
) },
5679 { "IOWriteBytes", "t", NULL
, offsetof(UnitStatusInfo
, io_write_bytes
) },
5680 { "ExecCondition", "a(sasbttttuii)", map_exec
, 0 },
5681 { "ExecConditionEx", "a(sasasttttuii)", map_exec
, 0 },
5682 { "ExecStartPre", "a(sasbttttuii)", map_exec
, 0 },
5683 { "ExecStartPreEx", "a(sasasttttuii)", map_exec
, 0 },
5684 { "ExecStart", "a(sasbttttuii)", map_exec
, 0 },
5685 { "ExecStartEx", "a(sasasttttuii)", map_exec
, 0 },
5686 { "ExecStartPost", "a(sasbttttuii)", map_exec
, 0 },
5687 { "ExecStartPostEx", "a(sasasttttuii)", map_exec
, 0 },
5688 { "ExecReload", "a(sasbttttuii)", map_exec
, 0 },
5689 { "ExecReloadEx", "a(sasasttttuii)", map_exec
, 0 },
5690 { "ExecStopPre", "a(sasbttttuii)", map_exec
, 0 },
5691 { "ExecStop", "a(sasbttttuii)", map_exec
, 0 },
5692 { "ExecStopEx", "a(sasasttttuii)", map_exec
, 0 },
5693 { "ExecStopPost", "a(sasbttttuii)", map_exec
, 0 },
5694 { "ExecStopPostEx", "a(sasasttttuii)", map_exec
, 0 },
5698 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5699 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5700 _cleanup_set_free_ Set
*found_properties
= NULL
;
5701 _cleanup_(unit_status_info_free
) UnitStatusInfo info
= {
5702 .memory_current
= (uint64_t) -1,
5703 .memory_high
= CGROUP_LIMIT_MAX
,
5704 .memory_max
= CGROUP_LIMIT_MAX
,
5705 .memory_swap_max
= CGROUP_LIMIT_MAX
,
5706 .memory_limit
= (uint64_t) -1,
5707 .cpu_usage_nsec
= (uint64_t) -1,
5708 .tasks_current
= (uint64_t) -1,
5709 .tasks_max
= (uint64_t) -1,
5710 .ip_ingress_bytes
= (uint64_t) -1,
5711 .ip_egress_bytes
= (uint64_t) -1,
5712 .io_read_bytes
= UINT64_MAX
,
5713 .io_write_bytes
= UINT64_MAX
,
5721 log_debug("Showing one %s", path
);
5723 r
= bus_map_all_properties(
5725 "org.freedesktop.systemd1",
5727 show_mode
== SYSTEMCTL_SHOW_STATUS
? status_map
: property_map
,
5728 BUS_MAP_BOOLEAN_AS_BOOL
,
5733 return log_error_errno(r
, "Failed to get properties: %s", bus_error_message(&error
, r
));
5735 if (unit
&& streq_ptr(info
.load_state
, "not-found") && streq_ptr(info
.active_state
, "inactive")) {
5736 log_full(show_mode
== SYSTEMCTL_SHOW_STATUS
? LOG_ERR
: LOG_DEBUG
,
5737 "Unit %s could not be found.", unit
);
5739 if (show_mode
== SYSTEMCTL_SHOW_STATUS
)
5740 return EXIT_PROGRAM_OR_SERVICES_STATUS_UNKNOWN
;
5741 else if (show_mode
== SYSTEMCTL_SHOW_HELP
)
5750 if (show_mode
== SYSTEMCTL_SHOW_STATUS
) {
5751 print_status_info(bus
, &info
, ellipsized
);
5753 if (info
.active_state
&& !STR_IN_SET(info
.active_state
, "active", "reloading"))
5754 return EXIT_PROGRAM_NOT_RUNNING
;
5756 return EXIT_PROGRAM_RUNNING_OR_SERVICE_OK
;
5758 } else if (show_mode
== SYSTEMCTL_SHOW_HELP
) {
5759 show_unit_help(&info
);
5763 r
= sd_bus_message_rewind(reply
, true);
5765 return log_error_errno(r
, "Failed to rewind: %s", bus_error_message(&error
, r
));
5767 r
= bus_message_print_all_properties(reply
, print_property
, arg_properties
, arg_value
, arg_all
, &found_properties
);
5769 return bus_log_parse_error(r
);
5771 STRV_FOREACH(pp
, arg_properties
)
5772 if (!set_contains(found_properties
, *pp
))
5773 log_debug("Property %s does not exist.", *pp
);
5778 static int get_unit_dbus_path_by_pid(
5783 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5784 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5788 r
= sd_bus_call_method(
5790 "org.freedesktop.systemd1",
5791 "/org/freedesktop/systemd1",
5792 "org.freedesktop.systemd1.Manager",
5798 return log_error_errno(r
, "Failed to get unit for PID %"PRIu32
": %s", pid
, bus_error_message(&error
, r
));
5800 r
= sd_bus_message_read(reply
, "o", &u
);
5802 return bus_log_parse_error(r
);
5812 static int show_all(
5817 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5818 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
5823 r
= get_unit_list(bus
, NULL
, NULL
, &unit_infos
, 0, &reply
);
5827 (void) pager_open(arg_pager_flags
);
5831 typesafe_qsort(unit_infos
, c
, compare_unit_info
);
5833 for (u
= unit_infos
; u
< unit_infos
+ c
; u
++) {
5834 _cleanup_free_
char *p
= NULL
;
5836 p
= unit_dbus_path_from_name(u
->id
);
5840 r
= show_one(bus
, p
, u
->id
, SYSTEMCTL_SHOW_STATUS
, new_line
, ellipsized
);
5843 else if (r
> 0 && ret
== 0)
5850 static int show_system_status(sd_bus
*bus
) {
5851 char since1
[FORMAT_TIMESTAMP_RELATIVE_MAX
], since2
[FORMAT_TIMESTAMP_MAX
];
5852 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5853 _cleanup_(machine_info_clear
) struct machine_info mi
= {};
5854 _cleanup_free_
char *hn
= NULL
;
5855 const char *on
, *off
;
5858 hn
= gethostname_malloc();
5862 r
= bus_map_all_properties(
5864 "org.freedesktop.systemd1",
5865 "/org/freedesktop/systemd1",
5866 machine_info_property_map
,
5872 return log_error_errno(r
, "Failed to read server status: %s", bus_error_message(&error
, r
));
5874 if (streq_ptr(mi
.state
, "degraded")) {
5875 on
= ansi_highlight_red();
5876 off
= ansi_normal();
5877 } else if (streq_ptr(mi
.state
, "running")) {
5878 on
= ansi_highlight_green();
5879 off
= ansi_normal();
5881 on
= ansi_highlight_yellow();
5882 off
= ansi_normal();
5885 printf("%s%s%s %s\n", on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
, arg_host
? arg_host
: hn
);
5887 printf(" State: %s%s%s\n",
5888 on
, strna(mi
.state
), off
);
5890 printf(" Jobs: %" PRIu32
" queued\n", mi
.n_jobs
);
5891 printf(" Failed: %" PRIu32
" units\n", mi
.n_failed_units
);
5893 printf(" Since: %s; %s\n",
5894 format_timestamp(since2
, sizeof(since2
), mi
.timestamp
),
5895 format_timestamp_relative(since1
, sizeof(since1
), mi
.timestamp
));
5897 printf(" CGroup: %s\n", mi
.control_group
?: "/");
5898 if (IN_SET(arg_transport
,
5899 BUS_TRANSPORT_LOCAL
,
5900 BUS_TRANSPORT_MACHINE
)) {
5901 static const char prefix
[] = " ";
5905 if (c
> sizeof(prefix
) - 1)
5906 c
-= sizeof(prefix
) - 1;
5910 show_cgroup(SYSTEMD_CGROUP_CONTROLLER
, strempty(mi
.control_group
), prefix
, c
, get_output_flags());
5916 static int show(int argc
, char *argv
[], void *userdata
) {
5917 bool new_line
= false, ellipsized
= false;
5918 SystemctlShowMode show_mode
;
5924 show_mode
= systemctl_show_mode_from_string(argv
[0]);
5926 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
5927 "Invalid argument.");
5929 if (show_mode
== SYSTEMCTL_SHOW_HELP
&& argc
<= 1)
5930 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
5931 "'help' command expects one or more unit names.\n"
5932 "(Alternatively, help for systemctl itself may be shown with --help)");
5934 r
= acquire_bus(BUS_MANAGER
, &bus
);
5938 (void) pager_open(arg_pager_flags
);
5940 /* If no argument is specified inspect the manager itself */
5941 if (show_mode
== SYSTEMCTL_SHOW_PROPERTIES
&& argc
<= 1)
5942 return show_one(bus
, "/org/freedesktop/systemd1", NULL
, show_mode
, &new_line
, &ellipsized
);
5944 if (show_mode
== SYSTEMCTL_SHOW_STATUS
&& argc
<= 1) {
5946 show_system_status(bus
);
5950 ret
= show_all(bus
, &new_line
, &ellipsized
);
5952 _cleanup_free_
char **patterns
= NULL
;
5955 STRV_FOREACH(name
, strv_skip(argv
, 1)) {
5956 _cleanup_free_
char *path
= NULL
, *unit
= NULL
;
5959 if (safe_atou32(*name
, &id
) < 0) {
5960 if (strv_push(&patterns
, *name
) < 0)
5964 } else if (show_mode
== SYSTEMCTL_SHOW_PROPERTIES
) {
5965 /* Interpret as job id */
5966 if (asprintf(&path
, "/org/freedesktop/systemd1/job/%u", id
) < 0)
5970 /* Interpret as PID */
5971 r
= get_unit_dbus_path_by_pid(bus
, id
, &path
);
5977 r
= unit_name_from_dbus_path(path
, &unit
);
5982 r
= show_one(bus
, path
, unit
, show_mode
, &new_line
, &ellipsized
);
5985 else if (r
> 0 && ret
== 0)
5989 if (!strv_isempty(patterns
)) {
5990 _cleanup_strv_free_
char **names
= NULL
;
5992 r
= expand_names(bus
, patterns
, NULL
, &names
, NULL
);
5994 return log_error_errno(r
, "Failed to expand names: %m");
5996 r
= maybe_extend_with_unit_dependencies(bus
, &names
);
6000 STRV_FOREACH(name
, names
) {
6001 _cleanup_free_
char *path
;
6003 path
= unit_dbus_path_from_name(*name
);
6007 r
= show_one(bus
, path
, *name
, show_mode
, &new_line
, &ellipsized
);
6010 if (r
> 0 && ret
== 0)
6016 if (ellipsized
&& !arg_quiet
)
6017 printf("Hint: Some lines were ellipsized, use -l to show in full.\n");
6022 static int cat(int argc
, char *argv
[], void *userdata
) {
6023 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
6024 _cleanup_strv_free_
char **names
= NULL
;
6030 /* Include all units by default — i.e. continue as if the --all
6031 * option was used */
6032 if (strv_isempty(arg_states
))
6035 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
6036 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot remotely cat units.");
6038 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
6040 return log_error_errno(r
, "Failed to determine unit paths: %m");
6042 r
= acquire_bus(BUS_MANAGER
, &bus
);
6046 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
6048 return log_error_errno(r
, "Failed to expand names: %m");
6050 r
= maybe_extend_with_unit_dependencies(bus
, &names
);
6054 (void) pager_open(arg_pager_flags
);
6056 STRV_FOREACH(name
, names
) {
6057 _cleanup_free_
char *fragment_path
= NULL
;
6058 _cleanup_strv_free_
char **dropin_paths
= NULL
;
6060 r
= unit_find_paths(bus
, *name
, &lp
, false, &fragment_path
, &dropin_paths
);
6061 if (r
== -ERFKILL
) {
6062 printf("%s# Unit %s is masked%s.\n",
6063 ansi_highlight_magenta(),
6068 if (r
== -EKEYREJECTED
) {
6069 printf("%s# Unit %s could not be loaded.%s\n",
6070 ansi_highlight_magenta(),
6078 /* Skip units which have no on-disk counterpart, but
6079 * propagate the error to the user */
6089 if (need_daemon_reload(bus
, *name
) > 0) /* ignore errors (<0), this is informational output */
6091 "%s# Warning: %s changed on disk, the version systemd has loaded is outdated.\n"
6092 "%s# This output shows the current version of the unit's original fragment and drop-in files.\n"
6093 "%s# If fragments or drop-ins were added or removed, they are not properly reflected in this output.\n"
6094 "%s# Run 'systemctl%s daemon-reload' to reload units.%s\n",
6095 ansi_highlight_red(),
6097 ansi_highlight_red(),
6098 ansi_highlight_red(),
6099 ansi_highlight_red(),
6100 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user",
6103 r
= cat_files(fragment_path
, dropin_paths
, 0);
6111 static int set_property(int argc
, char *argv
[], void *userdata
) {
6112 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6113 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6114 _cleanup_free_
char *n
= NULL
;
6119 r
= acquire_bus(BUS_MANAGER
, &bus
);
6123 polkit_agent_open_maybe();
6125 r
= sd_bus_message_new_method_call(
6128 "org.freedesktop.systemd1",
6129 "/org/freedesktop/systemd1",
6130 "org.freedesktop.systemd1.Manager",
6131 "SetUnitProperties");
6133 return bus_log_create_error(r
);
6135 r
= unit_name_mangle(argv
[1], arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, &n
);
6137 return log_error_errno(r
, "Failed to mangle unit name: %m");
6139 t
= unit_name_to_type(n
);
6141 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid unit type: %s", n
);
6143 r
= sd_bus_message_append(m
, "sb", n
, arg_runtime
);
6145 return bus_log_create_error(r
);
6147 r
= sd_bus_message_open_container(m
, SD_BUS_TYPE_ARRAY
, "(sv)");
6149 return bus_log_create_error(r
);
6151 r
= bus_append_unit_property_assignment_many(m
, t
, strv_skip(argv
, 2));
6155 r
= sd_bus_message_close_container(m
);
6157 return bus_log_create_error(r
);
6159 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6161 return log_error_errno(r
, "Failed to set unit properties on %s: %s", n
, bus_error_message(&error
, r
));
6166 static int daemon_reload(int argc
, char *argv
[], void *userdata
) {
6167 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6168 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6173 r
= acquire_bus(BUS_MANAGER
, &bus
);
6177 polkit_agent_open_maybe();
6179 switch (arg_action
) {
6186 method
= "Reexecute";
6189 case ACTION_SYSTEMCTL
:
6190 method
= streq(argv
[0], "daemon-reexec") ? "Reexecute" :
6191 /* "daemon-reload" */ "Reload";
6195 assert_not_reached("Unexpected action");
6198 r
= sd_bus_message_new_method_call(
6201 "org.freedesktop.systemd1",
6202 "/org/freedesktop/systemd1",
6203 "org.freedesktop.systemd1.Manager",
6206 return bus_log_create_error(r
);
6208 /* Note we use an extra-long timeout here. This is because a reload or reexec means generators are rerun which
6209 * are timed out after DEFAULT_TIMEOUT_USEC. Let's use twice that time here, so that the generators can have
6210 * their timeout, and for everything else there's the same time budget in place. */
6212 r
= sd_bus_call(bus
, m
, DEFAULT_TIMEOUT_USEC
* 2, &error
, NULL
);
6214 /* On reexecution, we expect a disconnect, not a reply */
6215 if (IN_SET(r
, -ETIMEDOUT
, -ECONNRESET
) && streq(method
, "Reexecute"))
6218 if (r
< 0 && arg_action
== ACTION_SYSTEMCTL
)
6219 return log_error_errno(r
, "Failed to reload daemon: %s", bus_error_message(&error
, r
));
6221 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
6222 * old ways of doing things, hence don't log any error in that case here. */
6224 return r
< 0 ? r
: 0;
6227 static int trivial_method(int argc
, char *argv
[], void *userdata
) {
6228 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6236 r
= acquire_bus(BUS_MANAGER
, &bus
);
6240 polkit_agent_open_maybe();
6243 streq(argv
[0], "clear-jobs") ||
6244 streq(argv
[0], "cancel") ? "ClearJobs" :
6245 streq(argv
[0], "reset-failed") ? "ResetFailed" :
6246 streq(argv
[0], "halt") ? "Halt" :
6247 streq(argv
[0], "reboot") ? "Reboot" :
6248 streq(argv
[0], "kexec") ? "KExec" :
6249 streq(argv
[0], "exit") ? "Exit" :
6250 /* poweroff */ "PowerOff";
6252 r
= sd_bus_call_method(
6254 "org.freedesktop.systemd1",
6255 "/org/freedesktop/systemd1",
6256 "org.freedesktop.systemd1.Manager",
6261 if (r
< 0 && arg_action
== ACTION_SYSTEMCTL
)
6262 return log_error_errno(r
, "Failed to execute operation: %s", bus_error_message(&error
, r
));
6264 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
6265 * old ways of doing things, hence don't log any error in that case here. */
6267 return r
< 0 ? r
: 0;
6270 static int reset_failed(int argc
, char *argv
[], void *userdata
) {
6271 _cleanup_strv_free_
char **names
= NULL
;
6277 return trivial_method(argc
, argv
, userdata
);
6279 r
= acquire_bus(BUS_MANAGER
, &bus
);
6283 polkit_agent_open_maybe();
6285 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
6287 return log_error_errno(r
, "Failed to expand names: %m");
6289 STRV_FOREACH(name
, names
) {
6290 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6292 q
= sd_bus_call_method(
6294 "org.freedesktop.systemd1",
6295 "/org/freedesktop/systemd1",
6296 "org.freedesktop.systemd1.Manager",
6302 log_error_errno(q
, "Failed to reset failed state of unit %s: %s", *name
, bus_error_message(&error
, q
));
6311 static int print_variable(const char *s
) {
6313 _cleanup_free_
char *esc
= NULL
;
6315 sep
= strchr(s
, '=');
6317 return log_error_errno(SYNTHETIC_ERRNO(EUCLEAN
),
6318 "Invalid environment block");
6320 esc
= shell_maybe_quote(sep
+ 1, ESCAPE_POSIX
);
6324 printf("%.*s=%s\n", (int)(sep
-s
), s
, esc
);
6328 static int show_environment(int argc
, char *argv
[], void *userdata
) {
6329 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6330 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
6335 r
= acquire_bus(BUS_MANAGER
, &bus
);
6339 (void) pager_open(arg_pager_flags
);
6341 r
= sd_bus_get_property(
6343 "org.freedesktop.systemd1",
6344 "/org/freedesktop/systemd1",
6345 "org.freedesktop.systemd1.Manager",
6351 return log_error_errno(r
, "Failed to get environment: %s", bus_error_message(&error
, r
));
6353 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "s");
6355 return bus_log_parse_error(r
);
6357 while ((r
= sd_bus_message_read_basic(reply
, SD_BUS_TYPE_STRING
, &text
)) > 0) {
6358 r
= print_variable(text
);
6363 return bus_log_parse_error(r
);
6365 r
= sd_bus_message_exit_container(reply
);
6367 return bus_log_parse_error(r
);
6372 static int switch_root(int argc
, char *argv
[], void *userdata
) {
6373 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6374 _cleanup_free_
char *cmdline_init
= NULL
;
6375 const char *root
, *init
;
6379 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
6380 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot switch root remotely.");
6382 if (argc
< 2 || argc
> 3)
6383 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Wrong number of arguments.");
6390 r
= proc_cmdline_get_key("init", 0, &cmdline_init
);
6392 log_debug_errno(r
, "Failed to parse /proc/cmdline: %m");
6394 init
= cmdline_init
;
6397 init
= empty_to_null(init
);
6399 const char *root_systemd_path
= NULL
, *root_init_path
= NULL
;
6401 root_systemd_path
= prefix_roota(root
, "/" SYSTEMD_BINARY_PATH
);
6402 root_init_path
= prefix_roota(root
, init
);
6404 /* If the passed init is actually the same as the
6405 * systemd binary, then let's suppress it. */
6406 if (files_same(root_init_path
, root_systemd_path
, 0) > 0)
6410 /* Instruct PID1 to exclude us from its killing spree applied during the transition. Otherwise we
6411 * would exit with a failure status even though the switch to the new root has succeed. */
6413 assert(saved_argv
[0]);
6414 saved_argv
[0][0] = '@';
6416 r
= acquire_bus(BUS_MANAGER
, &bus
);
6420 /* If we are slow to exit after the root switch, the new systemd instance
6421 * will send us a signal to terminate. Just ignore it and exit normally.
6422 * This way the unit does not end up as failed.
6424 r
= ignore_signals(SIGTERM
, -1);
6426 log_warning_errno(r
, "Failed to change disposition of SIGTERM to ignore: %m");
6428 log_debug("Switching root - root: %s; init: %s", root
, strna(init
));
6430 r
= sd_bus_call_method(
6432 "org.freedesktop.systemd1",
6433 "/org/freedesktop/systemd1",
6434 "org.freedesktop.systemd1.Manager",
6440 (void) default_signals(SIGTERM
, -1);
6442 return log_error_errno(r
, "Failed to switch root: %s", bus_error_message(&error
, r
));
6448 static int log_level(int argc
, char *argv
[], void *userdata
) {
6450 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6453 r
= acquire_bus(BUS_MANAGER
, &bus
);
6458 _cleanup_free_
char *level
= NULL
;
6460 r
= sd_bus_get_property_string(
6462 "org.freedesktop.systemd1",
6463 "/org/freedesktop/systemd1",
6464 "org.freedesktop.systemd1.Manager",
6469 return log_error_errno(r
, "Failed to get log level: %s", bus_error_message(&error
, r
));
6476 r
= sd_bus_set_property(
6478 "org.freedesktop.systemd1",
6479 "/org/freedesktop/systemd1",
6480 "org.freedesktop.systemd1.Manager",
6486 return log_error_errno(r
, "Failed to set log level: %s", bus_error_message(&error
, r
));
6492 static int log_target(int argc
, char *argv
[], void *userdata
) {
6494 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6497 r
= acquire_bus(BUS_MANAGER
, &bus
);
6502 _cleanup_free_
char *target
= NULL
;
6504 r
= sd_bus_get_property_string(
6506 "org.freedesktop.systemd1",
6507 "/org/freedesktop/systemd1",
6508 "org.freedesktop.systemd1.Manager",
6513 return log_error_errno(r
, "Failed to get log target: %s", bus_error_message(&error
, r
));
6520 r
= sd_bus_set_property(
6522 "org.freedesktop.systemd1",
6523 "/org/freedesktop/systemd1",
6524 "org.freedesktop.systemd1.Manager",
6530 return log_error_errno(r
, "Failed to set log target: %s", bus_error_message(&error
, r
));
6536 static int service_watchdogs(int argc
, char *argv
[], void *userdata
) {
6538 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6543 r
= acquire_bus(BUS_MANAGER
, &bus
);
6548 /* get ServiceWatchdogs */
6549 r
= sd_bus_get_property_trivial(
6551 "org.freedesktop.systemd1",
6552 "/org/freedesktop/systemd1",
6553 "org.freedesktop.systemd1.Manager",
6559 return log_error_errno(r
, "Failed to get service-watchdog state: %s", bus_error_message(&error
, r
));
6561 printf("%s\n", yes_no(!!b
));
6564 /* set ServiceWatchdogs */
6567 b
= parse_boolean(argv
[1]);
6569 return log_error_errno(b
, "Failed to parse service-watchdogs argument: %m");
6571 r
= sd_bus_set_property(
6573 "org.freedesktop.systemd1",
6574 "/org/freedesktop/systemd1",
6575 "org.freedesktop.systemd1.Manager",
6581 return log_error_errno(r
, "Failed to set service-watchdog state: %s", bus_error_message(&error
, r
));
6587 static int set_environment(int argc
, char *argv
[], void *userdata
) {
6588 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6589 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6597 r
= acquire_bus(BUS_MANAGER
, &bus
);
6601 polkit_agent_open_maybe();
6603 method
= streq(argv
[0], "set-environment")
6605 : "UnsetEnvironment";
6607 r
= sd_bus_message_new_method_call(
6610 "org.freedesktop.systemd1",
6611 "/org/freedesktop/systemd1",
6612 "org.freedesktop.systemd1.Manager",
6615 return bus_log_create_error(r
);
6617 r
= sd_bus_message_append_strv(m
, strv_skip(argv
, 1));
6619 return bus_log_create_error(r
);
6621 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6623 return log_error_errno(r
, "Failed to set environment: %s", bus_error_message(&error
, r
));
6628 static int import_environment(int argc
, char *argv
[], void *userdata
) {
6629 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6630 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6634 r
= acquire_bus(BUS_MANAGER
, &bus
);
6638 polkit_agent_open_maybe();
6640 r
= sd_bus_message_new_method_call(
6643 "org.freedesktop.systemd1",
6644 "/org/freedesktop/systemd1",
6645 "org.freedesktop.systemd1.Manager",
6648 return bus_log_create_error(r
);
6651 r
= sd_bus_message_append_strv(m
, environ
);
6655 r
= sd_bus_message_open_container(m
, 'a', "s");
6657 return bus_log_create_error(r
);
6659 STRV_FOREACH(a
, strv_skip(argv
, 1)) {
6661 if (!env_name_is_valid(*a
))
6662 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Not a valid environment variable name: %s", *a
);
6664 STRV_FOREACH(b
, environ
) {
6667 eq
= startswith(*b
, *a
);
6668 if (eq
&& *eq
== '=') {
6670 r
= sd_bus_message_append(m
, "s", *b
);
6672 return bus_log_create_error(r
);
6679 r
= sd_bus_message_close_container(m
);
6682 return bus_log_create_error(r
);
6684 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6686 return log_error_errno(r
, "Failed to import environment: %s", bus_error_message(&error
, r
));
6691 static int enable_sysv_units(const char *verb
, char **args
) {
6694 #if HAVE_SYSV_COMPAT
6695 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
6698 /* Processes all SysV units, and reshuffles the array so that afterwards only the native units remain */
6700 if (arg_scope
!= UNIT_FILE_SYSTEM
)
6703 if (getenv_bool("SYSTEMCTL_SKIP_SYSV") > 0)
6706 if (!STR_IN_SET(verb
,
6712 r
= lookup_paths_init(&paths
, arg_scope
, LOOKUP_PATHS_EXCLUDE_GENERATED
, arg_root
);
6719 const char *argv
[] = {
6720 ROOTLIBEXECDIR
"/systemd-sysv-install",
6727 _cleanup_free_
char *p
= NULL
, *q
= NULL
, *l
= NULL
, *v
= NULL
;
6728 bool found_native
= false, found_sysv
;
6736 if (!endswith(name
, ".service"))
6739 if (path_is_absolute(name
))
6742 j
= unit_file_exists(arg_scope
, &paths
, name
);
6743 if (j
< 0 && !IN_SET(j
, -ELOOP
, -ERFKILL
, -EADDRNOTAVAIL
))
6744 return log_error_errno(j
, "Failed to look up unit file state: %m");
6745 found_native
= j
!= 0;
6747 /* If we have both a native unit and a SysV script, enable/disable them both (below); for is-enabled,
6748 * prefer the native unit */
6749 if (found_native
&& streq(verb
, "is-enabled"))
6752 p
= path_join(arg_root
, SYSTEM_SYSVINIT_PATH
, name
);
6756 p
[strlen(p
) - STRLEN(".service")] = 0;
6757 found_sysv
= access(p
, F_OK
) >= 0;
6763 log_info("Synchronizing state of %s with SysV service script with %s.", name
, argv
[0]);
6765 log_info("%s is not a native service, redirecting to systemd-sysv-install.", name
);
6768 if (!isempty(arg_root
)) {
6769 q
= strjoin("--root=", arg_root
);
6776 /* Let's copy the verb, since it's still pointing directly into the original argv[] array we
6777 * got passed, but safe_fork() is likely going to rewrite that for the new child */
6783 argv
[c
++] = basename(p
);
6786 l
= strv_join((char**)argv
, " ");
6791 log_info("Executing: %s", l
);
6793 j
= safe_fork("(sysv-install)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
, &pid
);
6798 execv(argv
[0], (char**) argv
);
6799 log_error_errno(errno
, "Failed to execute %s: %m", argv
[0]);
6800 _exit(EXIT_FAILURE
);
6803 j
= wait_for_terminate_and_check("sysv-install", pid
, WAIT_LOG_ABNORMAL
);
6806 if (streq(verb
, "is-enabled")) {
6807 if (j
== EXIT_SUCCESS
) {
6816 } else if (j
!= EXIT_SUCCESS
)
6817 return -EBADE
; /* We don't warn here, under the assumption the script already showed an explanation */
6822 /* Remove this entry, so that we don't try enabling it as native unit */
6825 assert(args
[f
] == name
);
6826 strv_remove(args
+ f
, name
);
6833 static int mangle_names(const char *operation
, char **original_names
, char ***mangled_names
) {
6834 char **i
, **l
, **name
;
6837 l
= i
= new(char*, strv_length(original_names
) + 1);
6841 STRV_FOREACH(name
, original_names
) {
6843 /* When enabling units qualified path names are OK,
6844 * too, hence allow them explicitly. */
6846 if (is_path(*name
)) {
6853 r
= unit_name_mangle_with_suffix(*name
, operation
,
6854 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
6859 return log_error_errno(r
, "Failed to mangle unit name: %m");
6872 static int normalize_filenames(char **names
) {
6876 STRV_FOREACH(u
, names
)
6877 if (!path_is_absolute(*u
)) {
6878 char* normalized_path
;
6880 if (!isempty(arg_root
))
6881 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6882 "Non-absolute paths are not allowed when --root is used: %s",
6885 if (!strchr(*u
,'/'))
6886 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6887 "Link argument does contain at least one directory separator: %s",
6890 r
= path_make_absolute_cwd(*u
, &normalized_path
);
6894 free_and_replace(*u
, normalized_path
);
6900 static int normalize_names(char **names
, bool warn_if_path
) {
6902 bool was_path
= false;
6904 STRV_FOREACH(u
, names
) {
6910 r
= free_and_strdup(u
, basename(*u
));
6912 return log_error_errno(r
, "Failed to normalize unit file path: %m");
6917 if (warn_if_path
&& was_path
)
6918 log_warning("Warning: Can't execute disable on the unit file path. Proceeding with the unit name.");
6923 static int unit_exists(LookupPaths
*lp
, const char *unit
) {
6924 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6925 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6926 _cleanup_free_
char *path
= NULL
;
6927 static const struct bus_properties_map property_map
[] = {
6928 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
6929 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
)},
6932 UnitStatusInfo info
= {};
6936 if (unit_name_is_valid(unit
, UNIT_NAME_TEMPLATE
))
6937 return unit_find_template_path(unit
, lp
, NULL
, NULL
);
6939 path
= unit_dbus_path_from_name(unit
);
6943 r
= acquire_bus(BUS_MANAGER
, &bus
);
6947 r
= bus_map_all_properties(bus
, "org.freedesktop.systemd1", path
, property_map
, 0, &error
, &m
, &info
);
6949 return log_error_errno(r
, "Failed to get properties: %s", bus_error_message(&error
, r
));
6951 return !streq_ptr(info
.load_state
, "not-found") || !streq_ptr(info
.active_state
, "inactive");
6954 static int enable_unit(int argc
, char *argv
[], void *userdata
) {
6955 _cleanup_strv_free_
char **names
= NULL
;
6956 const char *verb
= argv
[0];
6957 UnitFileChange
*changes
= NULL
;
6958 size_t n_changes
= 0;
6959 int carries_install_info
= -1;
6960 bool ignore_carries_install_info
= arg_quiet
;
6966 r
= mangle_names("to enable", strv_skip(argv
, 1), &names
);
6970 r
= enable_sysv_units(verb
, names
);
6974 /* If the operation was fully executed by the SysV compat, let's finish early */
6975 if (strv_isempty(names
)) {
6976 if (arg_no_reload
|| install_client_side())
6978 return daemon_reload(argc
, argv
, userdata
);
6981 if (streq(verb
, "disable")) {
6982 r
= normalize_names(names
, true);
6987 if (streq(verb
, "link")) {
6988 r
= normalize_filenames(names
);
6993 if (install_client_side()) {
6994 UnitFileFlags flags
;
6996 flags
= args_to_flags();
6997 if (streq(verb
, "enable")) {
6998 r
= unit_file_enable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6999 carries_install_info
= r
;
7000 } else if (streq(verb
, "disable"))
7001 r
= unit_file_disable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
7002 else if (streq(verb
, "reenable")) {
7003 r
= unit_file_reenable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
7004 carries_install_info
= r
;
7005 } else if (streq(verb
, "link"))
7006 r
= unit_file_link(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
7007 else if (streq(verb
, "preset")) {
7008 r
= unit_file_preset(arg_scope
, flags
, arg_root
, names
, arg_preset_mode
, &changes
, &n_changes
);
7009 } else if (streq(verb
, "mask"))
7010 r
= unit_file_mask(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
7011 else if (streq(verb
, "unmask"))
7012 r
= unit_file_unmask(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
7013 else if (streq(verb
, "revert"))
7014 r
= unit_file_revert(arg_scope
, arg_root
, names
, &changes
, &n_changes
);
7016 assert_not_reached("Unknown verb");
7018 unit_file_dump_changes(r
, verb
, changes
, n_changes
, arg_quiet
);
7023 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
, *m
= NULL
;
7024 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7025 bool expect_carries_install_info
= false;
7026 bool send_runtime
= true, send_force
= true, send_preset_mode
= false;
7030 if (STR_IN_SET(verb
, "mask", "unmask")) {
7032 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
7034 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
7038 STRV_FOREACH(name
, names
) {
7039 r
= unit_exists(&lp
, *name
);
7043 log_notice("Unit %s does not exist, proceeding anyway.", *name
);
7047 r
= acquire_bus(BUS_MANAGER
, &bus
);
7051 polkit_agent_open_maybe();
7053 if (streq(verb
, "enable")) {
7054 method
= "EnableUnitFiles";
7055 expect_carries_install_info
= true;
7056 } else if (streq(verb
, "disable")) {
7057 method
= "DisableUnitFiles";
7059 } else if (streq(verb
, "reenable")) {
7060 method
= "ReenableUnitFiles";
7061 expect_carries_install_info
= true;
7062 } else if (streq(verb
, "link"))
7063 method
= "LinkUnitFiles";
7064 else if (streq(verb
, "preset")) {
7066 if (arg_preset_mode
!= UNIT_FILE_PRESET_FULL
) {
7067 method
= "PresetUnitFilesWithMode";
7068 send_preset_mode
= true;
7070 method
= "PresetUnitFiles";
7072 expect_carries_install_info
= true;
7073 ignore_carries_install_info
= true;
7074 } else if (streq(verb
, "mask"))
7075 method
= "MaskUnitFiles";
7076 else if (streq(verb
, "unmask")) {
7077 method
= "UnmaskUnitFiles";
7079 } else if (streq(verb
, "revert")) {
7080 method
= "RevertUnitFiles";
7081 send_runtime
= send_force
= false;
7083 assert_not_reached("Unknown verb");
7085 r
= sd_bus_message_new_method_call(
7088 "org.freedesktop.systemd1",
7089 "/org/freedesktop/systemd1",
7090 "org.freedesktop.systemd1.Manager",
7093 return bus_log_create_error(r
);
7095 r
= sd_bus_message_append_strv(m
, names
);
7097 return bus_log_create_error(r
);
7099 if (send_preset_mode
) {
7100 r
= sd_bus_message_append(m
, "s", unit_file_preset_mode_to_string(arg_preset_mode
));
7102 return bus_log_create_error(r
);
7106 r
= sd_bus_message_append(m
, "b", arg_runtime
);
7108 return bus_log_create_error(r
);
7112 r
= sd_bus_message_append(m
, "b", arg_force
);
7114 return bus_log_create_error(r
);
7117 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
7119 return log_error_errno(r
, "Failed to %s unit: %s", verb
, bus_error_message(&error
, r
));
7121 if (expect_carries_install_info
) {
7122 r
= sd_bus_message_read(reply
, "b", &carries_install_info
);
7124 return bus_log_parse_error(r
);
7127 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
7131 /* Try to reload if enabled */
7133 r
= daemon_reload(argc
, argv
, userdata
);
7138 if (carries_install_info
== 0 && !ignore_carries_install_info
)
7139 log_notice("The unit files have no installation config (WantedBy=, RequiredBy=, Also=,\n"
7140 "Alias= settings in the [Install] section, and DefaultInstance= for template\n"
7141 "units). This means they are not meant to be enabled using systemctl.\n"
7142 " \n" /* trick: the space is needed so that the line does not get stripped from output */
7143 "Possible reasons for having this kind of units are:\n"
7144 "%1$s A unit may be statically enabled by being symlinked from another unit's\n"
7145 " .wants/ or .requires/ directory.\n"
7146 "%1$s A unit's purpose may be to act as a helper for some other unit which has\n"
7147 " a requirement dependency on it.\n"
7148 "%1$s A unit may be started when needed via activation (socket, path, timer,\n"
7149 " D-Bus, udev, scripted systemctl call, ...).\n"
7150 "%1$s In case of template units, the unit is meant to be enabled with some\n"
7151 " instance name specified.",
7152 special_glyph(SPECIAL_GLYPH_BULLET
));
7154 if (arg_now
&& STR_IN_SET(argv
[0], "enable", "disable", "mask")) {
7158 r
= acquire_bus(BUS_MANAGER
, &bus
);
7162 len
= strv_length(names
);
7164 char *new_args
[len
+ 2];
7166 new_args
[0] = (char*) (streq(argv
[0], "enable") ? "start" : "stop");
7167 for (i
= 0; i
< len
; i
++)
7168 new_args
[i
+ 1] = basename(names
[i
]);
7169 new_args
[i
+ 1] = NULL
;
7171 r
= start_unit(len
+ 1, new_args
, userdata
);
7176 unit_file_changes_free(changes
, n_changes
);
7181 static int add_dependency(int argc
, char *argv
[], void *userdata
) {
7182 _cleanup_strv_free_
char **names
= NULL
;
7183 _cleanup_free_
char *target
= NULL
;
7184 const char *verb
= argv
[0];
7185 UnitFileChange
*changes
= NULL
;
7186 size_t n_changes
= 0;
7193 r
= unit_name_mangle_with_suffix(argv
[1], "as target",
7194 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
7195 ".target", &target
);
7197 return log_error_errno(r
, "Failed to mangle unit name: %m");
7199 r
= mangle_names("as dependency", strv_skip(argv
, 2), &names
);
7203 if (streq(verb
, "add-wants"))
7205 else if (streq(verb
, "add-requires"))
7206 dep
= UNIT_REQUIRES
;
7208 assert_not_reached("Unknown verb");
7210 if (install_client_side()) {
7211 r
= unit_file_add_dependency(arg_scope
, args_to_flags(), arg_root
, names
, target
, dep
, &changes
, &n_changes
);
7212 unit_file_dump_changes(r
, "add dependency on", changes
, n_changes
, arg_quiet
);
7217 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
, *m
= NULL
;
7218 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7221 r
= acquire_bus(BUS_MANAGER
, &bus
);
7225 polkit_agent_open_maybe();
7227 r
= sd_bus_message_new_method_call(
7230 "org.freedesktop.systemd1",
7231 "/org/freedesktop/systemd1",
7232 "org.freedesktop.systemd1.Manager",
7233 "AddDependencyUnitFiles");
7235 return bus_log_create_error(r
);
7237 r
= sd_bus_message_append_strv(m
, names
);
7239 return bus_log_create_error(r
);
7241 r
= sd_bus_message_append(m
, "ssbb", target
, unit_dependency_to_string(dep
), arg_runtime
, arg_force
);
7243 return bus_log_create_error(r
);
7245 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
7247 return log_error_errno(r
, "Failed to add dependency: %s", bus_error_message(&error
, r
));
7249 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
7253 if (arg_no_reload
) {
7258 r
= daemon_reload(argc
, argv
, userdata
);
7262 unit_file_changes_free(changes
, n_changes
);
7267 static int preset_all(int argc
, char *argv
[], void *userdata
) {
7268 UnitFileChange
*changes
= NULL
;
7269 size_t n_changes
= 0;
7272 if (install_client_side()) {
7273 r
= unit_file_preset_all(arg_scope
, args_to_flags(), arg_root
, arg_preset_mode
, &changes
, &n_changes
);
7274 unit_file_dump_changes(r
, "preset", changes
, n_changes
, arg_quiet
);
7279 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7280 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7283 r
= acquire_bus(BUS_MANAGER
, &bus
);
7287 polkit_agent_open_maybe();
7289 r
= sd_bus_call_method(
7291 "org.freedesktop.systemd1",
7292 "/org/freedesktop/systemd1",
7293 "org.freedesktop.systemd1.Manager",
7294 "PresetAllUnitFiles",
7298 unit_file_preset_mode_to_string(arg_preset_mode
),
7302 return log_error_errno(r
, "Failed to preset all units: %s", bus_error_message(&error
, r
));
7304 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
7308 if (arg_no_reload
) {
7313 r
= daemon_reload(argc
, argv
, userdata
);
7317 unit_file_changes_free(changes
, n_changes
);
7322 static int show_installation_targets_client_side(const char *name
) {
7323 UnitFileChange
*changes
= NULL
;
7324 size_t n_changes
= 0, i
;
7325 UnitFileFlags flags
;
7329 p
= STRV_MAKE(name
);
7330 flags
= UNIT_FILE_DRY_RUN
|
7331 (arg_runtime
? UNIT_FILE_RUNTIME
: 0);
7333 r
= unit_file_disable(UNIT_FILE_SYSTEM
, flags
, NULL
, p
, &changes
, &n_changes
);
7335 return log_error_errno(r
, "Failed to get file links for %s: %m", name
);
7337 for (i
= 0; i
< n_changes
; i
++)
7338 if (changes
[i
].type
== UNIT_FILE_UNLINK
)
7339 printf(" %s\n", changes
[i
].path
);
7344 static int show_installation_targets(sd_bus
*bus
, const char *name
) {
7345 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7346 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7350 r
= sd_bus_call_method(
7352 "org.freedesktop.systemd1",
7353 "/org/freedesktop/systemd1",
7354 "org.freedesktop.systemd1.Manager",
7358 "sb", name
, arg_runtime
);
7360 return log_error_errno(r
, "Failed to get unit file links for %s: %s", name
, bus_error_message(&error
, r
));
7362 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "s");
7364 return bus_log_parse_error(r
);
7366 while ((r
= sd_bus_message_read(reply
, "s", &link
)) > 0)
7367 printf(" %s\n", link
);
7370 return bus_log_parse_error(r
);
7372 r
= sd_bus_message_exit_container(reply
);
7374 return bus_log_parse_error(r
);
7379 static int unit_is_enabled(int argc
, char *argv
[], void *userdata
) {
7380 _cleanup_strv_free_
char **names
= NULL
;
7385 r
= mangle_names("to check", strv_skip(argv
, 1), &names
);
7389 r
= enable_sysv_units(argv
[0], names
);
7395 if (install_client_side()) {
7396 STRV_FOREACH(name
, names
) {
7397 UnitFileState state
;
7399 r
= unit_file_get_state(arg_scope
, arg_root
, *name
, &state
);
7401 return log_error_errno(r
, "Failed to get unit file state for %s: %m", *name
);
7405 UNIT_FILE_ENABLED_RUNTIME
,
7409 UNIT_FILE_GENERATED
))
7413 puts(unit_file_state_to_string(state
));
7415 r
= show_installation_targets_client_side(*name
);
7424 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7427 r
= acquire_bus(BUS_MANAGER
, &bus
);
7431 STRV_FOREACH(name
, names
) {
7432 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7435 r
= sd_bus_call_method(
7437 "org.freedesktop.systemd1",
7438 "/org/freedesktop/systemd1",
7439 "org.freedesktop.systemd1.Manager",
7445 return log_error_errno(r
, "Failed to get unit file state for %s: %s", *name
, bus_error_message(&error
, r
));
7447 r
= sd_bus_message_read(reply
, "s", &s
);
7449 return bus_log_parse_error(r
);
7451 if (STR_IN_SET(s
, "enabled", "enabled-runtime", "static", "indirect", "generated"))
7457 r
= show_installation_targets(bus
, *name
);
7465 return enabled
? EXIT_SUCCESS
: EXIT_FAILURE
;
7468 static int match_startup_finished(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
7469 char **state
= userdata
;
7474 r
= sd_bus_get_property_string(
7475 sd_bus_message_get_bus(m
),
7476 "org.freedesktop.systemd1",
7477 "/org/freedesktop/systemd1",
7478 "org.freedesktop.systemd1.Manager",
7483 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m
)), r
);
7487 static int is_system_running(int argc
, char *argv
[], void *userdata
) {
7488 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7489 _cleanup_(sd_bus_slot_unrefp
) sd_bus_slot
*slot_startup_finished
= NULL
;
7490 _cleanup_(sd_event_unrefp
) sd_event
* event
= NULL
;
7491 _cleanup_free_
char *state
= NULL
;
7495 if (running_in_chroot() > 0 || (arg_transport
== BUS_TRANSPORT_LOCAL
&& !sd_booted())) {
7498 return EXIT_FAILURE
;
7501 r
= acquire_bus(BUS_MANAGER
, &bus
);
7506 r
= sd_event_default(&event
);
7508 r
= sd_bus_attach_event(bus
, event
, 0);
7510 r
= sd_bus_match_signal_async(
7512 &slot_startup_finished
,
7513 "org.freedesktop.systemd1",
7514 "/org/freedesktop/systemd1",
7515 "org.freedesktop.systemd1.Manager",
7517 match_startup_finished
, NULL
, &state
);
7519 log_warning_errno(r
, "Failed to request match for StartupFinished: %m");
7524 r
= sd_bus_get_property_string(
7526 "org.freedesktop.systemd1",
7527 "/org/freedesktop/systemd1",
7528 "org.freedesktop.systemd1.Manager",
7533 log_warning_errno(r
, "Failed to query system state: %s", bus_error_message(&error
, r
));
7537 return EXIT_FAILURE
;
7540 if (arg_wait
&& STR_IN_SET(state
, "initializing", "starting")) {
7541 r
= sd_event_loop(event
);
7543 log_warning_errno(r
, "Failed to get property from event loop: %m");
7546 return EXIT_FAILURE
;
7553 return streq(state
, "running") ? EXIT_SUCCESS
: EXIT_FAILURE
;
7556 static int create_edit_temp_file(const char *new_path
, const char *original_path
, char **ret_tmp_fn
) {
7557 _cleanup_free_
char *t
= NULL
;
7561 assert(original_path
);
7564 r
= tempfn_random(new_path
, NULL
, &t
);
7566 return log_error_errno(r
, "Failed to determine temporary filename for \"%s\": %m", new_path
);
7568 r
= mkdir_parents(new_path
, 0755);
7570 return log_error_errno(r
, "Failed to create directories for \"%s\": %m", new_path
);
7572 r
= copy_file(original_path
, t
, 0, 0644, 0, 0, COPY_REFLINK
);
7577 return log_error_errno(r
, "Failed to create temporary file \"%s\": %m", t
);
7580 return log_error_errno(r
, "Failed to create temporary file for \"%s\": %m", new_path
);
7582 *ret_tmp_fn
= TAKE_PTR(t
);
7587 static int get_file_to_edit(
7588 const LookupPaths
*paths
,
7592 _cleanup_free_
char *path
= NULL
, *run
= NULL
;
7597 path
= path_join(paths
->persistent_config
, name
);
7602 run
= path_join(paths
->runtime_config
, name
);
7608 if (access(path
, F_OK
) >= 0)
7609 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
7610 "Refusing to create \"%s\" because it would be overridden by \"%s\" anyway.",
7613 *ret_path
= TAKE_PTR(run
);
7615 *ret_path
= TAKE_PTR(path
);
7620 static int unit_file_create_new(
7621 const LookupPaths
*paths
,
7622 const char *unit_name
,
7624 char **ret_new_path
,
7625 char **ret_tmp_path
) {
7627 _cleanup_free_
char *new_path
= NULL
, *tmp_path
= NULL
;
7632 assert(ret_new_path
);
7633 assert(ret_tmp_path
);
7635 ending
= strjoina(unit_name
, suffix
);
7636 r
= get_file_to_edit(paths
, ending
, &new_path
);
7640 r
= create_edit_temp_file(new_path
, new_path
, &tmp_path
);
7644 *ret_new_path
= TAKE_PTR(new_path
);
7645 *ret_tmp_path
= TAKE_PTR(tmp_path
);
7650 static int unit_file_create_copy(
7651 const LookupPaths
*paths
,
7652 const char *unit_name
,
7653 const char *fragment_path
,
7654 char **ret_new_path
,
7655 char **ret_tmp_path
) {
7657 _cleanup_free_
char *new_path
= NULL
, *tmp_path
= NULL
;
7660 assert(fragment_path
);
7662 assert(ret_new_path
);
7663 assert(ret_tmp_path
);
7665 r
= get_file_to_edit(paths
, unit_name
, &new_path
);
7669 if (!path_equal(fragment_path
, new_path
) && access(new_path
, F_OK
) >= 0) {
7672 r
= ask_char(&response
, "yn", "\"%s\" already exists. Overwrite with \"%s\"? [(y)es, (n)o] ", new_path
, fragment_path
);
7675 if (response
!= 'y')
7676 return log_warning_errno(SYNTHETIC_ERRNO(EKEYREJECTED
), "%s skipped.", unit_name
);
7679 r
= create_edit_temp_file(new_path
, fragment_path
, &tmp_path
);
7683 *ret_new_path
= TAKE_PTR(new_path
);
7684 *ret_tmp_path
= TAKE_PTR(tmp_path
);
7689 static int run_editor(char **paths
) {
7694 r
= safe_fork("(editor)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
|FORK_WAIT
, NULL
);
7698 char **editor_args
= NULL
, **tmp_path
, **original_path
;
7699 size_t n_editor_args
= 0, i
= 1, argc
;
7700 const char **args
, *editor
, *p
;
7702 argc
= strv_length(paths
)/2 + 1;
7704 /* SYSTEMD_EDITOR takes precedence over EDITOR which takes precedence over VISUAL
7705 * If neither SYSTEMD_EDITOR nor EDITOR nor VISUAL are present,
7706 * we try to execute well known editors
7708 editor
= getenv("SYSTEMD_EDITOR");
7710 editor
= getenv("EDITOR");
7712 editor
= getenv("VISUAL");
7714 if (!isempty(editor
)) {
7715 editor_args
= strv_split(editor
, WHITESPACE
);
7718 _exit(EXIT_FAILURE
);
7720 n_editor_args
= strv_length(editor_args
);
7721 argc
+= n_editor_args
- 1;
7724 args
= newa(const char*, argc
+ 1);
7726 if (n_editor_args
> 0) {
7727 args
[0] = editor_args
[0];
7728 for (; i
< n_editor_args
; i
++)
7729 args
[i
] = editor_args
[i
];
7732 STRV_FOREACH_PAIR(original_path
, tmp_path
, paths
)
7733 args
[i
++] = *tmp_path
;
7736 if (n_editor_args
> 0)
7737 execvp(args
[0], (char* const*) args
);
7739 FOREACH_STRING(p
, "editor", "nano", "vim", "vi") {
7741 execvp(p
, (char* const*) args
);
7742 /* We do not fail if the editor doesn't exist
7743 * because we want to try each one of them before
7746 if (errno
!= ENOENT
) {
7747 log_error_errno(errno
, "Failed to execute %s: %m", editor
);
7748 _exit(EXIT_FAILURE
);
7752 log_error("Cannot edit unit(s), no editor available. Please set either $SYSTEMD_EDITOR, $EDITOR or $VISUAL.");
7753 _exit(EXIT_FAILURE
);
7759 static int find_paths_to_edit(sd_bus
*bus
, char **names
, char ***paths
) {
7760 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
7767 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
7771 STRV_FOREACH(name
, names
) {
7772 _cleanup_free_
char *path
= NULL
, *new_path
= NULL
, *tmp_path
= NULL
, *tmp_name
= NULL
;
7773 const char *unit_name
;
7775 r
= unit_find_paths(bus
, *name
, &lp
, false, &path
, NULL
);
7776 if (r
== -EKEYREJECTED
) {
7777 /* If loading of the unit failed server side complete, then the server won't tell us the unit
7778 * file path. In that case, find the file client side. */
7779 log_debug_errno(r
, "Unit '%s' was not loaded correctly, retrying client-side.", *name
);
7780 r
= unit_find_paths(bus
, *name
, &lp
, true, &path
, NULL
);
7783 return log_error_errno(r
, "Unit '%s' masked, cannot edit.", *name
);
7791 log_info("Run 'systemctl edit%s --force --full %s' to create a new unit.",
7792 arg_scope
== UNIT_FILE_GLOBAL
? " --global" :
7793 arg_scope
== UNIT_FILE_USER
? " --user" : "",
7798 /* Create a new unit from scratch */
7800 r
= unit_file_create_new(&lp
, unit_name
,
7801 arg_full
? NULL
: ".d/override.conf",
7802 &new_path
, &tmp_path
);
7806 unit_name
= basename(path
);
7807 /* We follow unit aliases, but we need to propagate the instance */
7808 if (unit_name_is_valid(*name
, UNIT_NAME_INSTANCE
) &&
7809 unit_name_is_valid(unit_name
, UNIT_NAME_TEMPLATE
)) {
7810 _cleanup_free_
char *instance
= NULL
;
7812 r
= unit_name_to_instance(*name
, &instance
);
7816 r
= unit_name_replace_instance(unit_name
, instance
, &tmp_name
);
7820 unit_name
= tmp_name
;
7824 r
= unit_file_create_copy(&lp
, unit_name
, path
, &new_path
, &tmp_path
);
7826 r
= unit_file_create_new(&lp
, unit_name
, ".d/override.conf", &new_path
, &tmp_path
);
7831 r
= strv_push_pair(paths
, new_path
, tmp_path
);
7835 new_path
= tmp_path
= NULL
;
7841 static int edit(int argc
, char *argv
[], void *userdata
) {
7842 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
7843 _cleanup_strv_free_
char **names
= NULL
;
7844 _cleanup_strv_free_
char **paths
= NULL
;
7845 char **original
, **tmp
;
7850 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit units if not on a tty.");
7852 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
7853 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit units remotely.");
7855 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
7857 return log_error_errno(r
, "Failed to determine unit paths: %m");
7859 r
= acquire_bus(BUS_MANAGER
, &bus
);
7863 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
7865 return log_error_errno(r
, "Failed to expand names: %m");
7867 STRV_FOREACH(tmp
, names
) {
7868 r
= unit_is_masked(bus
, &lp
, *tmp
);
7872 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit %s: unit is masked.", *tmp
);
7875 r
= find_paths_to_edit(bus
, names
, &paths
);
7879 if (strv_isempty(paths
))
7882 r
= run_editor(paths
);
7886 STRV_FOREACH_PAIR(original
, tmp
, paths
) {
7887 /* If the temporary file is empty we ignore it.
7888 * This allows the user to cancel the modification.
7890 if (null_or_empty_path(*tmp
)) {
7891 log_warning("Editing \"%s\" canceled: temporary file is empty.", *original
);
7895 r
= rename(*tmp
, *original
);
7897 r
= log_error_errno(errno
, "Failed to rename \"%s\" to \"%s\": %m", *tmp
, *original
);
7904 if (!arg_no_reload
&& !install_client_side())
7905 r
= daemon_reload(argc
, argv
, userdata
);
7908 STRV_FOREACH_PAIR(original
, tmp
, paths
) {
7909 (void) unlink(*tmp
);
7911 /* Removing empty dropin dirs */
7913 _cleanup_free_
char *dir
;
7915 dir
= dirname_malloc(*original
);
7919 /* no need to check if the dir is empty, rmdir
7920 * does nothing if it is not the case.
7929 static int systemctl_help(void) {
7930 _cleanup_free_
char *link
= NULL
;
7933 (void) pager_open(arg_pager_flags
);
7935 r
= terminal_urlify_man("systemctl", "1", &link
);
7939 printf("%1$s [OPTIONS...] COMMAND ...\n\n"
7940 "%5$sQuery or send control commands to the system manager.%6$s\n"
7941 "\n%3$sUnit Commands:%4$s\n"
7942 " list-units [PATTERN...] List units currently in memory\n"
7943 " list-sockets [PATTERN...] List socket units currently in memory,\n"
7944 " ordered by address\n"
7945 " list-timers [PATTERN...] List timer units currently in memory,\n"
7946 " ordered by next elapse\n"
7947 " start UNIT... Start (activate) one or more units\n"
7948 " stop UNIT... Stop (deactivate) one or more units\n"
7949 " reload UNIT... Reload one or more units\n"
7950 " restart UNIT... Start or restart one or more units\n"
7951 " try-restart UNIT... Restart one or more units if active\n"
7952 " reload-or-restart UNIT... Reload one or more units if possible,\n"
7953 " otherwise start or restart\n"
7954 " try-reload-or-restart UNIT... If active, reload one or more units,\n"
7955 " if supported, otherwise restart\n"
7956 " isolate UNIT Start one unit and stop all others\n"
7957 " kill UNIT... Send signal to processes of a unit\n"
7958 " clean UNIT... Clean runtime, cache, state, logs or\n"
7959 " configuration of unit\n"
7960 " freeze PATTERN... Freeze execution of unit processes\n"
7961 " thaw PATTERN... Resume execution of a frozen unit\n"
7962 " is-active PATTERN... Check whether units are active\n"
7963 " is-failed PATTERN... Check whether units are failed\n"
7964 " status [PATTERN...|PID...] Show runtime status of one or more units\n"
7965 " show [PATTERN...|JOB...] Show properties of one or more\n"
7966 " units/jobs or the manager\n"
7967 " cat PATTERN... Show files and drop-ins of specified units\n"
7968 " set-property UNIT PROPERTY=VALUE... Sets one or more properties of a unit\n"
7969 " help PATTERN...|PID... Show manual for one or more units\n"
7970 " reset-failed [PATTERN...] Reset failed state for all, one, or more\n"
7972 " list-dependencies [UNIT...] Recursively show units which are required\n"
7973 " or wanted by the units or by which those\n"
7974 " units are required or wanted"
7975 "\n%3$sUnit File Commands:%4$s\n"
7976 " list-unit-files [PATTERN...] List installed unit files\n"
7977 " enable [UNIT...|PATH...] Enable one or more unit files\n"
7978 " disable UNIT... Disable one or more unit files\n"
7979 " reenable UNIT... Reenable one or more unit files\n"
7980 " preset UNIT... Enable/disable one or more unit files\n"
7981 " based on preset configuration\n"
7982 " preset-all Enable/disable all unit files based on\n"
7983 " preset configuration\n"
7984 " is-enabled UNIT... Check whether unit files are enabled\n"
7985 " mask UNIT... Mask one or more units\n"
7986 " unmask UNIT... Unmask one or more units\n"
7987 " link PATH... Link one or more units files into\n"
7988 " the search path\n"
7989 " revert UNIT... Revert one or more unit files to vendor\n"
7991 " add-wants TARGET UNIT... Add 'Wants' dependency for the target\n"
7992 " on specified one or more units\n"
7993 " add-requires TARGET UNIT... Add 'Requires' dependency for the target\n"
7994 " on specified one or more units\n"
7995 " edit UNIT... Edit one or more unit files\n"
7996 " get-default Get the name of the default target\n"
7997 " set-default TARGET Set the default target\n"
7998 "\n%3$sMachine Commands:%4$s\n"
7999 " list-machines [PATTERN...] List local containers and host\n"
8000 "\n%3$sJob Commands:%4$s\n"
8001 " list-jobs [PATTERN...] List jobs\n"
8002 " cancel [JOB...] Cancel all, one, or more jobs\n"
8003 "\n%3$sEnvironment Commands:%4$s\n"
8004 " show-environment Dump environment\n"
8005 " set-environment VARIABLE=VALUE... Set one or more environment variables\n"
8006 " unset-environment VARIABLE... Unset one or more environment variables\n"
8007 " import-environment [VARIABLE...] Import all or some environment variables\n"
8008 "\n%3$sManager State Commands:%4$s\n"
8009 " daemon-reload Reload systemd manager configuration\n"
8010 " daemon-reexec Reexecute systemd manager\n"
8011 " log-level [LEVEL] Get/set logging threshold for manager\n"
8012 " log-target [TARGET] Get/set logging target for manager\n"
8013 " service-watchdogs [BOOL] Get/set service watchdog state\n"
8014 "\n%3$sSystem Commands:%4$s\n"
8015 " is-system-running Check whether system is fully running\n"
8016 " default Enter system default mode\n"
8017 " rescue Enter system rescue mode\n"
8018 " emergency Enter system emergency mode\n"
8019 " halt Shut down and halt the system\n"
8020 " poweroff Shut down and power-off the system\n"
8021 " reboot [ARG] Shut down and reboot the system\n"
8022 " kexec Shut down and reboot the system with kexec\n"
8023 " exit [EXIT_CODE] Request user instance or container exit\n"
8024 " switch-root ROOT [INIT] Change to a different root file system\n"
8025 " suspend Suspend the system\n"
8026 " hibernate Hibernate the system\n"
8027 " hybrid-sleep Hibernate and suspend the system\n"
8028 " suspend-then-hibernate Suspend the system, wake after a period of\n"
8029 " time, and hibernate"
8030 "\n%3$sOptions:%4$s\n"
8031 " -h --help Show this help\n"
8032 " --version Show package version\n"
8033 " --system Connect to system manager\n"
8034 " --user Connect to user service manager\n"
8035 " -H --host=[USER@]HOST Operate on remote host\n"
8036 " -M --machine=CONTAINER Operate on a local container\n"
8037 " -t --type=TYPE List units of a particular type\n"
8038 " --state=STATE List units with particular LOAD or SUB or ACTIVE state\n"
8039 " --failed Shorcut for --state=failed\n"
8040 " -p --property=NAME Show only properties by this name\n"
8041 " -P NAME Equivalent to --value --property=NAME\n"
8042 " -a --all Show all properties/all units currently in memory,\n"
8043 " including dead/empty ones. To list all units installed\n"
8044 " on the system, use 'list-unit-files' instead.\n"
8045 " -l --full Don't ellipsize unit names on output\n"
8046 " -r --recursive Show unit list of host and local containers\n"
8047 " --reverse Show reverse dependencies with 'list-dependencies'\n"
8048 " --with-dependencies Show unit dependencies with 'status', 'cat',\n"
8049 " 'list-units', and 'list-unit-files'.\n"
8050 " --job-mode=MODE Specify how to deal with already queued jobs, when\n"
8051 " queueing a new job\n"
8052 " -T --show-transaction When enqueuing a unit job, show full transaction\n"
8053 " --show-types When showing sockets, explicitly show their type\n"
8054 " --value When showing properties, only print the value\n"
8055 " -i --ignore-inhibitors When shutting down or sleeping, ignore inhibitors\n"
8056 " --kill-who=WHO Whom to send signal to\n"
8057 " -s --signal=SIGNAL Which signal to send\n"
8058 " --what=RESOURCES Which types of resources to remove\n"
8059 " --now Start or stop unit after enabling or disabling it\n"
8060 " --dry-run Only print what would be done\n"
8061 " Currently supported by verbs: halt, poweroff, reboot,\n"
8062 " kexec, suspend, hibernate, suspend-then-hibernate,\n"
8063 " hybrid-sleep, default, rescue, emergency, and exit.\n"
8064 " -q --quiet Suppress output\n"
8065 " --wait For (re)start, wait until service stopped again\n"
8066 " For is-system-running, wait until startup is completed\n"
8067 " --no-block Do not wait until operation finished\n"
8068 " --no-wall Don't send wall message before halt/power-off/reboot\n"
8069 " --no-reload Don't reload daemon after en-/dis-abling unit files\n"
8070 " --no-legend Do not print a legend (column headers and hints)\n"
8071 " --no-pager Do not pipe output into a pager\n"
8072 " --no-ask-password Do not ask for system passwords\n"
8073 " --global Enable/disable/mask unit files globally\n"
8074 " --runtime Enable/disable/mask unit files temporarily until next\n"
8076 " -f --force When enabling unit files, override existing symlinks\n"
8077 " When shutting down, execute action immediately\n"
8078 " --preset-mode= Apply only enable, only disable, or all presets\n"
8079 " --root=PATH Enable/disable/mask unit files in the specified root\n"
8081 " -n --lines=INTEGER Number of journal entries to show\n"
8082 " -o --output=STRING Change journal output mode (short, short-precise,\n"
8083 " short-iso, short-iso-precise, short-full,\n"
8084 " short-monotonic, short-unix,\n"
8085 " verbose, export, json, json-pretty, json-sse, cat)\n"
8086 " --firmware-setup Tell the firmware to show the setup menu on next boot\n"
8087 " --boot-loader-menu=TIME\n"
8088 " Boot into boot loader menu on next boot\n"
8089 " --boot-loader-entry=NAME\n"
8090 " Boot into a specific boot loader entry on next boot\n"
8091 " --plain Print unit dependencies as a list instead of a tree\n"
8092 "\nSee the %2$s for details.\n"
8093 , program_invocation_short_name
8095 , ansi_underline(), ansi_normal()
8096 , ansi_highlight(), ansi_normal()
8102 static int halt_help(void) {
8103 _cleanup_free_
char *link
= NULL
;
8106 r
= terminal_urlify_man("halt", "8", &link
);
8110 printf("%s [OPTIONS...]%s\n"
8111 "\n%s%s the system.%s\n"
8113 " --help Show this help\n"
8114 " --halt Halt the machine\n"
8115 " -p --poweroff Switch off the machine\n"
8116 " --reboot Reboot the machine\n"
8117 " -f --force Force immediate halt/power-off/reboot\n"
8118 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
8119 " -d --no-wtmp Don't write wtmp record\n"
8120 " --no-wall Don't send wall message before halt/power-off/reboot\n"
8121 "\nSee the %s for details.\n"
8122 , program_invocation_short_name
8123 , arg_action
== ACTION_REBOOT
? " [ARG]" : ""
8125 , arg_action
== ACTION_REBOOT
? "Reboot" :
8126 arg_action
== ACTION_POWEROFF
? "Power off" :
8135 static int shutdown_help(void) {
8136 _cleanup_free_
char *link
= NULL
;
8139 r
= terminal_urlify_man("shutdown", "8", &link
);
8143 printf("%s [OPTIONS...] [TIME] [WALL...]\n"
8144 "\n%sShut down the system.%s\n"
8146 " --help Show this help\n"
8147 " -H --halt Halt the machine\n"
8148 " -P --poweroff Power-off the machine\n"
8149 " -r --reboot Reboot the machine\n"
8150 " -h Equivalent to --poweroff, overridden by --halt\n"
8151 " -k Don't halt/power-off/reboot, just send warnings\n"
8152 " --no-wall Don't send wall message before halt/power-off/reboot\n"
8153 " -c Cancel a pending shutdown\n"
8154 "\nSee the %s for details.\n"
8155 , program_invocation_short_name
8156 , ansi_highlight(), ansi_normal()
8163 static int telinit_help(void) {
8164 _cleanup_free_
char *link
= NULL
;
8167 r
= terminal_urlify_man("telinit", "8", &link
);
8171 printf("%s [OPTIONS...] COMMAND\n\n"
8172 "%sSend control commands to the init daemon.%s\n"
8174 " 0 Power-off the machine\n"
8175 " 6 Reboot the machine\n"
8176 " 2, 3, 4, 5 Start runlevelX.target unit\n"
8177 " 1, s, S Enter rescue mode\n"
8178 " q, Q Reload init daemon configuration\n"
8179 " u, U Reexecute init daemon\n"
8181 " --help Show this help\n"
8182 " --no-wall Don't send wall message before halt/power-off/reboot\n"
8183 "\nSee the %s for details.\n"
8184 , program_invocation_short_name
8185 , ansi_highlight(), ansi_normal()
8192 static int runlevel_help(void) {
8193 _cleanup_free_
char *link
= NULL
;
8196 r
= terminal_urlify_man("runlevel", "8", &link
);
8200 printf("%s [OPTIONS...]\n"
8201 "\n%sPrints the previous and current runlevel of the init system.%s\n"
8203 " --help Show this help\n"
8204 "\nSee the %s for details.\n"
8205 , program_invocation_short_name
8206 , ansi_highlight(), ansi_normal()
8213 static void help_types(void) {
8215 puts("Available unit types:");
8217 DUMP_STRING_TABLE(unit_type
, UnitType
, _UNIT_TYPE_MAX
);
8220 static void help_states(void) {
8222 puts("Available unit load states:");
8223 DUMP_STRING_TABLE(unit_load_state
, UnitLoadState
, _UNIT_LOAD_STATE_MAX
);
8226 puts("\nAvailable unit active states:");
8227 DUMP_STRING_TABLE(unit_active_state
, UnitActiveState
, _UNIT_ACTIVE_STATE_MAX
);
8230 puts("\nAvailable unit file states:");
8231 DUMP_STRING_TABLE(unit_file_state
, UnitFileState
, _UNIT_FILE_STATE_MAX
);
8234 puts("\nAvailable automount unit substates:");
8235 DUMP_STRING_TABLE(automount_state
, AutomountState
, _AUTOMOUNT_STATE_MAX
);
8238 puts("\nAvailable device unit substates:");
8239 DUMP_STRING_TABLE(device_state
, DeviceState
, _DEVICE_STATE_MAX
);
8242 puts("\nAvailable mount unit substates:");
8243 DUMP_STRING_TABLE(mount_state
, MountState
, _MOUNT_STATE_MAX
);
8246 puts("\nAvailable path unit substates:");
8247 DUMP_STRING_TABLE(path_state
, PathState
, _PATH_STATE_MAX
);
8250 puts("\nAvailable scope unit substates:");
8251 DUMP_STRING_TABLE(scope_state
, ScopeState
, _SCOPE_STATE_MAX
);
8254 puts("\nAvailable service unit substates:");
8255 DUMP_STRING_TABLE(service_state
, ServiceState
, _SERVICE_STATE_MAX
);
8258 puts("\nAvailable slice unit substates:");
8259 DUMP_STRING_TABLE(slice_state
, SliceState
, _SLICE_STATE_MAX
);
8262 puts("\nAvailable socket unit substates:");
8263 DUMP_STRING_TABLE(socket_state
, SocketState
, _SOCKET_STATE_MAX
);
8266 puts("\nAvailable swap unit substates:");
8267 DUMP_STRING_TABLE(swap_state
, SwapState
, _SWAP_STATE_MAX
);
8270 puts("\nAvailable target unit substates:");
8271 DUMP_STRING_TABLE(target_state
, TargetState
, _TARGET_STATE_MAX
);
8274 puts("\nAvailable timer unit substates:");
8275 DUMP_STRING_TABLE(timer_state
, TimerState
, _TIMER_STATE_MAX
);
8278 static int help_boot_loader_entry(void) {
8279 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
8280 _cleanup_strv_free_
char **l
= NULL
;
8285 r
= acquire_bus(BUS_FULL
, &bus
);
8289 r
= sd_bus_get_property_strv(
8291 "org.freedesktop.login1",
8292 "/org/freedesktop/login1",
8293 "org.freedesktop.login1.Manager",
8294 "BootLoaderEntries",
8298 return log_error_errno(r
, "Failed to enumerate boot loader entries: %s", bus_error_message(&error
, r
));
8300 if (strv_isempty(l
))
8301 return log_error_errno(SYNTHETIC_ERRNO(ENODATA
), "No boot loader entries discovered.");
8309 static int systemctl_parse_argv(int argc
, char *argv
[]) {
8318 ARG_IGNORE_DEPENDENCIES
,
8331 ARG_NO_ASK_PASSWORD
,
8339 ARG_BOOT_LOADER_MENU
,
8340 ARG_BOOT_LOADER_ENTRY
,
8343 ARG_WITH_DEPENDENCIES
,
8348 static const struct option options
[] = {
8349 { "help", no_argument
, NULL
, 'h' },
8350 { "version", no_argument
, NULL
, ARG_VERSION
},
8351 { "type", required_argument
, NULL
, 't' },
8352 { "property", required_argument
, NULL
, 'p' },
8353 { "all", no_argument
, NULL
, 'a' },
8354 { "reverse", no_argument
, NULL
, ARG_REVERSE
},
8355 { "after", no_argument
, NULL
, ARG_AFTER
},
8356 { "before", no_argument
, NULL
, ARG_BEFORE
},
8357 { "show-types", no_argument
, NULL
, ARG_SHOW_TYPES
},
8358 { "failed", no_argument
, NULL
, ARG_FAILED
}, /* compatibility only */
8359 { "full", no_argument
, NULL
, 'l' },
8360 { "job-mode", required_argument
, NULL
, ARG_JOB_MODE
},
8361 { "fail", no_argument
, NULL
, ARG_FAIL
}, /* compatibility only */
8362 { "irreversible", no_argument
, NULL
, ARG_IRREVERSIBLE
}, /* compatibility only */
8363 { "ignore-dependencies", no_argument
, NULL
, ARG_IGNORE_DEPENDENCIES
}, /* compatibility only */
8364 { "ignore-inhibitors", no_argument
, NULL
, 'i' },
8365 { "value", no_argument
, NULL
, ARG_VALUE
},
8366 { "user", no_argument
, NULL
, ARG_USER
},
8367 { "system", no_argument
, NULL
, ARG_SYSTEM
},
8368 { "global", no_argument
, NULL
, ARG_GLOBAL
},
8369 { "wait", no_argument
, NULL
, ARG_WAIT
},
8370 { "no-block", no_argument
, NULL
, ARG_NO_BLOCK
},
8371 { "no-legend", no_argument
, NULL
, ARG_NO_LEGEND
},
8372 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
8373 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8374 { "dry-run", no_argument
, NULL
, ARG_DRY_RUN
},
8375 { "quiet", no_argument
, NULL
, 'q' },
8376 { "root", required_argument
, NULL
, ARG_ROOT
},
8377 { "force", no_argument
, NULL
, 'f' },
8378 { "no-reload", no_argument
, NULL
, ARG_NO_RELOAD
},
8379 { "kill-who", required_argument
, NULL
, ARG_KILL_WHO
},
8380 { "signal", required_argument
, NULL
, 's' },
8381 { "no-ask-password", no_argument
, NULL
, ARG_NO_ASK_PASSWORD
},
8382 { "host", required_argument
, NULL
, 'H' },
8383 { "machine", required_argument
, NULL
, 'M' },
8384 { "runtime", no_argument
, NULL
, ARG_RUNTIME
},
8385 { "lines", required_argument
, NULL
, 'n' },
8386 { "output", required_argument
, NULL
, 'o' },
8387 { "plain", no_argument
, NULL
, ARG_PLAIN
},
8388 { "state", required_argument
, NULL
, ARG_STATE
},
8389 { "recursive", no_argument
, NULL
, 'r' },
8390 { "with-dependencies", no_argument
, NULL
, ARG_WITH_DEPENDENCIES
},
8391 { "preset-mode", required_argument
, NULL
, ARG_PRESET_MODE
},
8392 { "firmware-setup", no_argument
, NULL
, ARG_FIRMWARE_SETUP
},
8393 { "boot-loader-menu", required_argument
, NULL
, ARG_BOOT_LOADER_MENU
},
8394 { "boot-loader-entry", required_argument
, NULL
, ARG_BOOT_LOADER_ENTRY
},
8395 { "now", no_argument
, NULL
, ARG_NOW
},
8396 { "message", required_argument
, NULL
, ARG_MESSAGE
},
8397 { "show-transaction", no_argument
, NULL
, 'T' },
8398 { "what", required_argument
, NULL
, ARG_WHAT
},
8407 /* we default to allowing interactive authorization only in systemctl (not in the legacy commands) */
8408 arg_ask_password
= true;
8410 while ((c
= getopt_long(argc
, argv
, "ht:p:P:alqfs:H:M:n:o:iTr.::", options
, NULL
)) >= 0)
8415 return systemctl_help();
8423 if (isempty(optarg
))
8424 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8425 "--type= requires arguments.");
8427 for (p
= optarg
;;) {
8428 _cleanup_free_
char *type
= NULL
;
8430 r
= extract_first_word(&p
, &type
, ",", 0);
8432 return log_error_errno(r
, "Failed to parse type: %s", optarg
);
8436 if (streq(type
, "help")) {
8441 if (unit_type_from_string(type
) >= 0) {
8442 if (strv_consume(&arg_types
, TAKE_PTR(type
)) < 0)
8447 /* It's much nicer to use --state= for
8448 * load states, but let's support this
8449 * in --types= too for compatibility
8450 * with old versions */
8451 if (unit_load_state_from_string(type
) >= 0) {
8452 if (strv_consume(&arg_states
, TAKE_PTR(type
)) < 0)
8457 log_error("Unknown unit type or load state '%s'.", type
);
8458 return log_info_errno(SYNTHETIC_ERRNO(EINVAL
),
8459 "Use -t help to see a list of allowed values.");
8470 /* Make sure that if the empty property list was specified, we won't show any
8472 if (isempty(optarg
) && !arg_properties
) {
8473 arg_properties
= new0(char*, 1);
8474 if (!arg_properties
)
8479 for (p
= optarg
;;) {
8480 _cleanup_free_
char *prop
= NULL
;
8482 r
= extract_first_word(&p
, &prop
, ",", 0);
8484 return log_error_errno(r
, "Failed to parse property: %s", optarg
);
8488 if (strv_consume(&arg_properties
, TAKE_PTR(prop
)) < 0)
8493 /* If the user asked for a particular property, show it, even if it is empty. */
8503 arg_dependency
= DEPENDENCY_REVERSE
;
8507 arg_dependency
= DEPENDENCY_AFTER
;
8508 arg_jobs_after
= true;
8512 arg_dependency
= DEPENDENCY_BEFORE
;
8513 arg_jobs_before
= true;
8516 case ARG_SHOW_TYPES
:
8517 arg_show_types
= true;
8525 arg_job_mode
= optarg
;
8529 arg_job_mode
= "fail";
8532 case ARG_IRREVERSIBLE
:
8533 arg_job_mode
= "replace-irreversibly";
8536 case ARG_IGNORE_DEPENDENCIES
:
8537 arg_job_mode
= "ignore-dependencies";
8541 arg_scope
= UNIT_FILE_USER
;
8545 arg_scope
= UNIT_FILE_SYSTEM
;
8549 arg_scope
= UNIT_FILE_GLOBAL
;
8557 arg_no_block
= true;
8561 arg_no_legend
= true;
8565 arg_pager_flags
|= PAGER_DISABLE
;
8573 r
= parse_path_argument_and_warn(optarg
, false, &arg_root
);
8583 if (strv_extend(&arg_states
, "failed") < 0)
8601 arg_no_reload
= true;
8605 arg_kill_who
= optarg
;
8609 if (streq(optarg
, "help")) {
8610 DUMP_STRING_TABLE(signal
, int, _NSIG
);
8614 arg_signal
= signal_from_string(optarg
);
8616 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8617 "Failed to parse signal string %s.",
8621 case ARG_NO_ASK_PASSWORD
:
8622 arg_ask_password
= false;
8626 arg_transport
= BUS_TRANSPORT_REMOTE
;
8631 arg_transport
= BUS_TRANSPORT_MACHINE
;
8640 if (safe_atou(optarg
, &arg_lines
) < 0)
8641 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8642 "Failed to parse lines '%s'",
8647 if (streq(optarg
, "help")) {
8648 DUMP_STRING_TABLE(output_mode
, OutputMode
, _OUTPUT_MODE_MAX
);
8652 arg_output
= output_mode_from_string(optarg
);
8654 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8655 "Unknown output '%s'.",
8658 if (OUTPUT_MODE_IS_JSON(arg_output
)) {
8659 arg_no_legend
= true;
8665 arg_ignore_inhibitors
= true;
8672 case ARG_FIRMWARE_SETUP
:
8673 arg_firmware_setup
= true;
8676 case ARG_BOOT_LOADER_MENU
:
8678 r
= parse_sec(optarg
, &arg_boot_loader_menu
);
8680 return log_error_errno(r
, "Failed to parse --boot-loader-menu= argument '%s': %m", optarg
);
8684 case ARG_BOOT_LOADER_ENTRY
:
8686 if (streq(optarg
, "help")) { /* Yes, this means, "help" is not a valid boot loader entry name we can deal with */
8687 r
= help_boot_loader_entry();
8694 arg_boot_loader_entry
= empty_to_null(optarg
);
8700 if (isempty(optarg
))
8701 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8702 "--state= requires arguments.");
8704 for (p
= optarg
;;) {
8705 _cleanup_free_
char *s
= NULL
;
8707 r
= extract_first_word(&p
, &s
, ",", 0);
8709 return log_error_errno(r
, "Failed to parse state: %s", optarg
);
8713 if (streq(s
, "help")) {
8718 if (strv_consume(&arg_states
, TAKE_PTR(s
)) < 0)
8726 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
8727 "--recursive requires root privileges.");
8729 arg_recursive
= true;
8732 case ARG_PRESET_MODE
:
8733 if (streq(optarg
, "help")) {
8734 DUMP_STRING_TABLE(unit_file_preset_mode
, UnitFilePresetMode
, _UNIT_FILE_PRESET_MAX
);
8738 arg_preset_mode
= unit_file_preset_mode_from_string(optarg
);
8739 if (arg_preset_mode
< 0)
8740 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8741 "Failed to parse preset mode: %s.", optarg
);
8750 if (strv_extend(&arg_wall
, optarg
) < 0)
8755 arg_show_transaction
= true;
8758 case ARG_WITH_DEPENDENCIES
:
8759 arg_with_dependencies
= true;
8765 if (isempty(optarg
))
8766 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "--what= requires arguments.");
8768 for (p
= optarg
;;) {
8769 _cleanup_free_
char *k
= NULL
;
8771 r
= extract_first_word(&p
, &k
, ",", 0);
8773 return log_error_errno(r
, "Failed to parse directory type: %s", optarg
);
8777 if (streq(k
, "help")) {
8786 r
= strv_consume(&arg_clean_what
, TAKE_PTR(k
));
8795 /* Output an error mimicking getopt, and print a hint afterwards */
8796 log_error("%s: invalid option -- '.'", program_invocation_name
);
8797 log_notice("Hint: to specify units starting with a dash, use \"--\":\n"
8798 " %s [OPTIONS...] COMMAND -- -.%s ...",
8799 program_invocation_name
, optarg
?: "mount");
8806 assert_not_reached("Unhandled option");
8809 if (arg_transport
!= BUS_TRANSPORT_LOCAL
&& arg_scope
!= UNIT_FILE_SYSTEM
)
8810 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8811 "Cannot access user instance remotely.");
8813 if (arg_wait
&& arg_no_block
)
8814 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8815 "--wait may not be combined with --no-block.");
8820 static int halt_parse_argv(int argc
, char *argv
[]) {
8828 static const struct option options
[] = {
8829 { "help", no_argument
, NULL
, ARG_HELP
},
8830 { "halt", no_argument
, NULL
, ARG_HALT
},
8831 { "poweroff", no_argument
, NULL
, 'p' },
8832 { "reboot", no_argument
, NULL
, ARG_REBOOT
},
8833 { "force", no_argument
, NULL
, 'f' },
8834 { "wtmp-only", no_argument
, NULL
, 'w' },
8835 { "no-wtmp", no_argument
, NULL
, 'd' },
8836 { "no-sync", no_argument
, NULL
, 'n' },
8837 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8846 if (utmp_get_runlevel(&runlevel
, NULL
) >= 0)
8847 if (IN_SET(runlevel
, '0', '6'))
8850 while ((c
= getopt_long(argc
, argv
, "pfwdnih", options
, NULL
)) >= 0)
8857 arg_action
= ACTION_HALT
;
8861 if (arg_action
!= ACTION_REBOOT
)
8862 arg_action
= ACTION_POWEROFF
;
8866 arg_action
= ACTION_REBOOT
;
8891 /* Compatibility nops */
8898 assert_not_reached("Unhandled option");
8901 if (arg_action
== ACTION_REBOOT
&& (argc
== optind
|| argc
== optind
+ 1)) {
8902 r
= update_reboot_parameter_and_warn(argc
== optind
+ 1 ? argv
[optind
] : NULL
, false);
8905 } else if (optind
< argc
)
8906 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8907 "Too many arguments.");
8912 static int shutdown_parse_argv(int argc
, char *argv
[]) {
8918 static const struct option options
[] = {
8919 { "help", no_argument
, NULL
, ARG_HELP
},
8920 { "halt", no_argument
, NULL
, 'H' },
8921 { "poweroff", no_argument
, NULL
, 'P' },
8922 { "reboot", no_argument
, NULL
, 'r' },
8923 { "kexec", no_argument
, NULL
, 'K' }, /* not documented extension */
8924 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8934 while ((c
= getopt_long(argc
, argv
, "HPrhkKat:fFc", options
, NULL
)) >= 0)
8938 return shutdown_help();
8941 arg_action
= ACTION_HALT
;
8945 arg_action
= ACTION_POWEROFF
;
8950 arg_action
= ACTION_KEXEC
;
8952 arg_action
= ACTION_REBOOT
;
8956 arg_action
= ACTION_KEXEC
;
8960 if (arg_action
!= ACTION_HALT
)
8961 arg_action
= ACTION_POWEROFF
;
8973 case 't': /* Note that we also ignore any passed argument to -t, not just the -t itself */
8976 /* Compatibility nops */
8980 arg_action
= ACTION_CANCEL_SHUTDOWN
;
8987 assert_not_reached("Unhandled option");
8990 if (argc
> optind
&& arg_action
!= ACTION_CANCEL_SHUTDOWN
) {
8991 r
= parse_shutdown_time_spec(argv
[optind
], &arg_when
);
8993 log_error("Failed to parse time specification: %s", argv
[optind
]);
8997 arg_when
= now(CLOCK_REALTIME
) + USEC_PER_MINUTE
;
8999 if (argc
> optind
&& arg_action
== ACTION_CANCEL_SHUTDOWN
)
9000 /* No time argument for shutdown cancel */
9001 wall
= argv
+ optind
;
9002 else if (argc
> optind
+ 1)
9003 /* We skip the time argument */
9004 wall
= argv
+ optind
+ 1;
9007 arg_wall
= strv_copy(wall
);
9017 static int telinit_parse_argv(int argc
, char *argv
[]) {
9023 static const struct option options
[] = {
9024 { "help", no_argument
, NULL
, ARG_HELP
},
9025 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
9029 static const struct {
9033 { '0', ACTION_POWEROFF
},
9034 { '6', ACTION_REBOOT
},
9035 { '1', ACTION_RESCUE
},
9036 { '2', ACTION_RUNLEVEL2
},
9037 { '3', ACTION_RUNLEVEL3
},
9038 { '4', ACTION_RUNLEVEL4
},
9039 { '5', ACTION_RUNLEVEL5
},
9040 { 's', ACTION_RESCUE
},
9041 { 'S', ACTION_RESCUE
},
9042 { 'q', ACTION_RELOAD
},
9043 { 'Q', ACTION_RELOAD
},
9044 { 'u', ACTION_REEXEC
},
9045 { 'U', ACTION_REEXEC
}
9054 while ((c
= getopt_long(argc
, argv
, "", options
, NULL
)) >= 0)
9058 return telinit_help();
9068 assert_not_reached("Unhandled option");
9072 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
9073 "%s: required argument missing.",
9074 program_invocation_short_name
);
9076 if (optind
+ 1 < argc
)
9077 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
9078 "Too many arguments.");
9080 if (strlen(argv
[optind
]) != 1)
9081 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
9082 "Expected single character argument.");
9084 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
9085 if (table
[i
].from
== argv
[optind
][0])
9088 if (i
>= ELEMENTSOF(table
))
9089 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
9090 "Unknown command '%s'.", argv
[optind
]);
9092 arg_action
= table
[i
].to
;
9099 static int runlevel_parse_argv(int argc
, char *argv
[]) {
9104 static const struct option options
[] = {
9105 { "help", no_argument
, NULL
, ARG_HELP
},
9114 while ((c
= getopt_long(argc
, argv
, "", options
, NULL
)) >= 0)
9118 return runlevel_help();
9124 assert_not_reached("Unhandled option");
9128 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
9129 "Too many arguments.");
9134 static int parse_argv(int argc
, char *argv
[]) {
9138 if (program_invocation_short_name
) {
9140 if (strstr(program_invocation_short_name
, "halt")) {
9141 arg_action
= ACTION_HALT
;
9142 return halt_parse_argv(argc
, argv
);
9144 } else if (strstr(program_invocation_short_name
, "poweroff")) {
9145 arg_action
= ACTION_POWEROFF
;
9146 return halt_parse_argv(argc
, argv
);
9148 } else if (strstr(program_invocation_short_name
, "reboot")) {
9150 arg_action
= ACTION_KEXEC
;
9152 arg_action
= ACTION_REBOOT
;
9153 return halt_parse_argv(argc
, argv
);
9155 } else if (strstr(program_invocation_short_name
, "shutdown")) {
9156 arg_action
= ACTION_POWEROFF
;
9157 return shutdown_parse_argv(argc
, argv
);
9159 } else if (strstr(program_invocation_short_name
, "init")) {
9161 /* Matches invocations as "init" as well as "telinit", which are synonymous when run as PID !=
9164 * On SysV "telinit" was the official command to communicate with PID 1, but "init" would
9165 * redirect itself to "telinit" if called with PID != 1. We follow the same logic here still,
9166 * though we add one level of indirection, as we implement "telinit" in "systemctl". Hence, for
9167 * us if you invoke "init" you get "systemd", but it will execve() "systemctl" immediately with
9168 * argv[] unmodified if PID is != 1. If you invoke "telinit" you directly get "systemctl". In
9169 * both cases we shall do the same thing, which is why we do strstr(p_i_s_n, "init") here, as a
9170 * quick way to match both.
9172 * Also see redirect_telinit() in src/core/main.c. */
9174 if (sd_booted() > 0) {
9175 arg_action
= _ACTION_INVALID
;
9176 return telinit_parse_argv(argc
, argv
);
9178 /* Hmm, so some other init system is running, we need to forward this request to
9179 * it. For now we simply guess that it is Upstart. */
9181 (void) rlimit_nofile_safe();
9182 execv(TELINIT
, argv
);
9184 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
9185 "Couldn't find an alternative telinit implementation to spawn.");
9188 } else if (strstr(program_invocation_short_name
, "runlevel")) {
9189 arg_action
= ACTION_RUNLEVEL
;
9190 return runlevel_parse_argv(argc
, argv
);
9194 arg_action
= ACTION_SYSTEMCTL
;
9195 return systemctl_parse_argv(argc
, argv
);
9198 #if HAVE_SYSV_COMPAT
9199 _pure_
static int action_to_runlevel(void) {
9200 static const char table
[_ACTION_MAX
] = {
9201 [ACTION_HALT
] = '0',
9202 [ACTION_POWEROFF
] = '0',
9203 [ACTION_REBOOT
] = '6',
9204 [ACTION_RUNLEVEL2
] = '2',
9205 [ACTION_RUNLEVEL3
] = '3',
9206 [ACTION_RUNLEVEL4
] = '4',
9207 [ACTION_RUNLEVEL5
] = '5',
9208 [ACTION_RESCUE
] = '1'
9211 assert(arg_action
>= 0 && arg_action
< _ACTION_MAX
);
9212 return table
[arg_action
];
9216 static int systemctl_main(int argc
, char *argv
[]) {
9217 static const Verb verbs
[] = {
9218 { "list-units", VERB_ANY
, VERB_ANY
, VERB_DEFAULT
|VERB_ONLINE_ONLY
, list_units
},
9219 { "list-unit-files", VERB_ANY
, VERB_ANY
, 0, list_unit_files
},
9220 { "list-sockets", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_sockets
},
9221 { "list-timers", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_timers
},
9222 { "list-jobs", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_jobs
},
9223 { "list-machines", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_machines
},
9224 { "clear-jobs", VERB_ANY
, 1, VERB_ONLINE_ONLY
, trivial_method
},
9225 { "cancel", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, cancel_job
},
9226 { "start", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9227 { "stop", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9228 { "condstop", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with ALTLinux */
9229 { "reload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9230 { "restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9231 { "try-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9232 { "reload-or-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9233 { "reload-or-try-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with old systemctl <= 228 */
9234 { "try-reload-or-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9235 { "force-reload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with SysV */
9236 { "condreload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with ALTLinux */
9237 { "condrestart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with RH */
9238 { "isolate", 2, 2, VERB_ONLINE_ONLY
, start_unit
},
9239 { "kill", 2, VERB_ANY
, VERB_ONLINE_ONLY
, kill_unit
},
9240 { "clean", 2, VERB_ANY
, VERB_ONLINE_ONLY
, clean_or_freeze_unit
},
9241 { "freeze", 2, VERB_ANY
, VERB_ONLINE_ONLY
, clean_or_freeze_unit
},
9242 { "thaw", 2, VERB_ANY
, VERB_ONLINE_ONLY
, clean_or_freeze_unit
},
9243 { "is-active", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_active
},
9244 { "check", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_active
}, /* deprecated alias of is-active */
9245 { "is-failed", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_failed
},
9246 { "show", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
9247 { "cat", 2, VERB_ANY
, VERB_ONLINE_ONLY
, cat
},
9248 { "status", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
9249 { "help", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
9250 { "daemon-reload", VERB_ANY
, 1, VERB_ONLINE_ONLY
, daemon_reload
},
9251 { "daemon-reexec", VERB_ANY
, 1, VERB_ONLINE_ONLY
, daemon_reload
},
9252 { "log-level", VERB_ANY
, 2, VERB_ONLINE_ONLY
, log_level
},
9253 { "log-target", VERB_ANY
, 2, VERB_ONLINE_ONLY
, log_target
},
9254 { "service-watchdogs", VERB_ANY
, 2, VERB_ONLINE_ONLY
, service_watchdogs
},
9255 { "show-environment", VERB_ANY
, 1, VERB_ONLINE_ONLY
, show_environment
},
9256 { "set-environment", 2, VERB_ANY
, VERB_ONLINE_ONLY
, set_environment
},
9257 { "unset-environment", 2, VERB_ANY
, VERB_ONLINE_ONLY
, set_environment
},
9258 { "import-environment", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, import_environment
},
9259 { "halt", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9260 { "poweroff", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9261 { "reboot", VERB_ANY
, 2, VERB_ONLINE_ONLY
, start_system_special
},
9262 { "kexec", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9263 { "suspend", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9264 { "hibernate", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9265 { "hybrid-sleep", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9266 { "suspend-then-hibernate",VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9267 { "default", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_special
},
9268 { "rescue", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9269 { "emergency", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9270 { "exit", VERB_ANY
, 2, VERB_ONLINE_ONLY
, start_special
},
9271 { "reset-failed", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, reset_failed
},
9272 { "enable", 2, VERB_ANY
, 0, enable_unit
},
9273 { "disable", 2, VERB_ANY
, 0, enable_unit
},
9274 { "is-enabled", 2, VERB_ANY
, 0, unit_is_enabled
},
9275 { "reenable", 2, VERB_ANY
, 0, enable_unit
},
9276 { "preset", 2, VERB_ANY
, 0, enable_unit
},
9277 { "preset-all", VERB_ANY
, 1, 0, preset_all
},
9278 { "mask", 2, VERB_ANY
, 0, enable_unit
},
9279 { "unmask", 2, VERB_ANY
, 0, enable_unit
},
9280 { "link", 2, VERB_ANY
, 0, enable_unit
},
9281 { "revert", 2, VERB_ANY
, 0, enable_unit
},
9282 { "switch-root", 2, VERB_ANY
, VERB_ONLINE_ONLY
, switch_root
},
9283 { "list-dependencies", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_dependencies
},
9284 { "set-default", 2, 2, 0, set_default
},
9285 { "get-default", VERB_ANY
, 1, 0, get_default
},
9286 { "set-property", 3, VERB_ANY
, VERB_ONLINE_ONLY
, set_property
},
9287 { "is-system-running", VERB_ANY
, 1, 0, is_system_running
},
9288 { "add-wants", 3, VERB_ANY
, 0, add_dependency
},
9289 { "add-requires", 3, VERB_ANY
, 0, add_dependency
},
9290 { "edit", 2, VERB_ANY
, VERB_ONLINE_ONLY
, edit
},
9294 const Verb
*verb
= verbs_find_verb(argv
[optind
], verbs
);
9295 if (verb
&& (verb
->flags
& VERB_ONLINE_ONLY
) && arg_root
)
9296 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
9297 "Verb '%s' cannot be used with --root=.",
9298 argv
[optind
] ?: verb
->verb
);
9300 return dispatch_verb(argc
, argv
, verbs
, NULL
);
9303 static int reload_with_fallback(void) {
9304 /* First, try systemd via D-Bus. */
9305 if (daemon_reload(0, NULL
, NULL
) >= 0)
9308 /* Nothing else worked, so let's try signals */
9309 assert(IN_SET(arg_action
, ACTION_RELOAD
, ACTION_REEXEC
));
9311 if (kill(1, arg_action
== ACTION_RELOAD
? SIGHUP
: SIGTERM
) < 0)
9312 return log_error_errno(errno
, "kill() failed: %m");
9317 static int start_with_fallback(void) {
9318 /* First, try systemd via D-Bus. */
9319 if (start_unit(0, NULL
, NULL
) == 0)
9322 #if HAVE_SYSV_COMPAT
9323 /* Nothing else worked, so let's try /dev/initctl */
9324 if (talk_initctl(action_to_runlevel()) > 0)
9328 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
9329 "Failed to talk to init daemon.");
9332 static int halt_now(enum action a
) {
9333 /* The kernel will automatically flush ATA disks and suchlike on reboot(), but the file systems need to be
9334 * synced explicitly in advance. */
9335 if (!arg_no_sync
&& !arg_dry_run
)
9338 /* Make sure C-A-D is handled by the kernel from this point on... */
9340 (void) reboot(RB_ENABLE_CAD
);
9346 log_info("Halting.");
9349 (void) reboot(RB_HALT_SYSTEM
);
9352 case ACTION_POWEROFF
:
9354 log_info("Powering off.");
9357 (void) reboot(RB_POWER_OFF
);
9362 return reboot_with_parameter(REBOOT_FALLBACK
|
9363 (arg_quiet
? 0 : REBOOT_LOG
) |
9364 (arg_dry_run
? REBOOT_DRY_RUN
: 0));
9367 assert_not_reached("Unknown action.");
9371 static int logind_schedule_shutdown(void) {
9374 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
9375 char date
[FORMAT_TIMESTAMP_MAX
];
9380 r
= acquire_bus(BUS_FULL
, &bus
);
9384 switch (arg_action
) {
9388 case ACTION_POWEROFF
:
9389 action
= "poweroff";
9404 action
= strjoina("dry-", action
);
9406 (void) logind_set_wall_message();
9408 r
= sd_bus_call_method(
9410 "org.freedesktop.login1",
9411 "/org/freedesktop/login1",
9412 "org.freedesktop.login1.Manager",
9420 return log_warning_errno(r
, "Failed to call ScheduleShutdown in logind, proceeding with immediate shutdown: %s", bus_error_message(&error
, r
));
9423 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.", format_timestamp(date
, sizeof(date
), arg_when
));
9426 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
9427 "Cannot schedule shutdown without logind support, proceeding with immediate shutdown.");
9431 static int halt_main(void) {
9434 r
= logind_check_inhibitors(arg_action
);
9438 /* Delayed shutdown requested, and was successful */
9439 if (arg_when
> 0 && logind_schedule_shutdown() == 0)
9441 /* no delay, or logind failed or is not at all available */
9443 if (geteuid() != 0) {
9444 if (arg_dry_run
|| arg_force
> 0) {
9445 (void) must_be_root();
9449 /* Try logind if we are a normal user and no special
9450 * mode applies. Maybe polkit allows us to shutdown
9452 if (IN_SET(arg_action
, ACTION_POWEROFF
, ACTION_REBOOT
, ACTION_HALT
)) {
9453 r
= logind_reboot(arg_action
);
9456 if (IN_SET(r
, -EOPNOTSUPP
, -EINPROGRESS
))
9457 /* requested operation is not
9458 * supported on the local system or
9459 * already in progress */
9461 /* on all other errors, try low-level operation */
9465 /* In order to minimize the difference between operation with and
9466 * without logind, we explicitly enable non-blocking mode for this,
9467 * as logind's shutdown operations are always non-blocking. */
9468 arg_no_block
= true;
9470 if (!arg_dry_run
&& !arg_force
)
9471 return start_with_fallback();
9473 assert(geteuid() == 0);
9476 if (sd_booted() > 0)
9477 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
9479 r
= utmp_put_shutdown();
9481 log_warning_errno(r
, "Failed to write utmp record: %m");
9488 r
= halt_now(arg_action
);
9489 return log_error_errno(r
, "Failed to reboot: %m");
9492 static int runlevel_main(void) {
9493 int r
, runlevel
, previous
;
9495 r
= utmp_get_runlevel(&runlevel
, &previous
);
9502 previous
<= 0 ? 'N' : previous
,
9503 runlevel
<= 0 ? 'N' : runlevel
);
9508 static int logind_cancel_shutdown(void) {
9510 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
9514 r
= acquire_bus(BUS_FULL
, &bus
);
9518 (void) logind_set_wall_message();
9520 r
= sd_bus_call_method(
9522 "org.freedesktop.login1",
9523 "/org/freedesktop/login1",
9524 "org.freedesktop.login1.Manager",
9525 "CancelScheduledShutdown",
9529 return log_warning_errno(r
, "Failed to talk to logind, shutdown hasn't been cancelled: %s", bus_error_message(&error
, r
));
9533 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
9534 "Not compiled with logind support, cannot cancel scheduled shutdowns.");
9538 static int run(int argc
, char *argv
[]) {
9541 setlocale(LC_ALL
, "");
9542 log_parse_environment();
9545 /* The journal merging logic potentially needs a lot of fds. */
9546 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE
);
9550 /* Explicitly not on_tty() to avoid setting cached value.
9551 * This becomes relevant for piping output which might be
9553 original_stdout_is_tty
= isatty(STDOUT_FILENO
);
9555 r
= parse_argv(argc
, argv
);
9559 if (arg_action
!= ACTION_SYSTEMCTL
&& running_in_chroot() > 0) {
9561 log_info("Running in chroot, ignoring request.");
9566 /* systemctl_main() will print an error message for the bus
9567 * connection, but only if it needs to */
9569 switch (arg_action
) {
9571 case ACTION_SYSTEMCTL
:
9572 r
= systemctl_main(argc
, argv
);
9575 /* Legacy command aliases set arg_action. They provide some fallbacks,
9576 * e.g. to tell sysvinit to reboot after you have installed systemd
9580 case ACTION_POWEROFF
:
9586 case ACTION_RUNLEVEL2
:
9587 case ACTION_RUNLEVEL3
:
9588 case ACTION_RUNLEVEL4
:
9589 case ACTION_RUNLEVEL5
:
9591 r
= start_with_fallback();
9596 r
= reload_with_fallback();
9599 case ACTION_CANCEL_SHUTDOWN
:
9600 r
= logind_cancel_shutdown();
9603 case ACTION_RUNLEVEL
:
9604 r
= runlevel_main();
9608 case ACTION_SUSPEND
:
9609 case ACTION_HIBERNATE
:
9610 case ACTION_HYBRID_SLEEP
:
9611 case ACTION_SUSPEND_THEN_HIBERNATE
:
9612 case ACTION_EMERGENCY
:
9613 case ACTION_DEFAULT
:
9614 /* systemctl verbs with no equivalent in the legacy commands.
9615 * These cannot appear in arg_action. Fall through. */
9617 case _ACTION_INVALID
:
9619 assert_not_reached("Unknown action");
9625 /* Note that we return r here, not 0, so that we can implement the LSB-like return codes */
9629 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);