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"
38 #include "exec-util.h"
39 #include "exit-status.h"
41 #include "format-util.h"
43 #include "glob-util.h"
44 #include "hexdecoct.h"
45 #include "hostname-util.h"
46 #include "in-addr-util.h"
50 #include "journal-util.h"
52 #include "locale-util.h"
54 #include "logs-show.h"
56 #include "main-func.h"
57 #include "memory-util.h"
60 #include "parse-util.h"
61 #include "path-lookup.h"
62 #include "path-util.h"
63 #include "pretty-print.h"
64 #include "proc-cmdline.h"
65 #include "process-util.h"
66 #include "reboot-util.h"
67 #include "rlimit-util.h"
70 #include "signal-util.h"
71 #include "socket-util.h"
72 #include "sort-util.h"
73 #include "spawn-ask-password-agent.h"
74 #include "spawn-polkit-agent.h"
76 #include "stat-util.h"
77 #include "string-table.h"
79 #include "sysv-compat.h"
80 #include "terminal-util.h"
81 #include "tmpfile-util.h"
83 #include "unit-file.h"
84 #include "unit-name.h"
85 #include "user-util.h"
87 #include "utmp-wtmp.h"
91 static char **arg_types
= NULL
;
92 static char **arg_states
= NULL
;
93 static char **arg_properties
= NULL
;
94 static bool arg_all
= false;
95 static enum dependency
{
101 } arg_dependency
= DEPENDENCY_FORWARD
;
102 static const char *arg_job_mode
= "replace";
103 static UnitFileScope arg_scope
= UNIT_FILE_SYSTEM
;
104 static bool arg_wait
= false;
105 static bool arg_no_block
= false;
106 static bool arg_no_legend
= false;
107 static PagerFlags arg_pager_flags
= 0;
108 static bool arg_no_wtmp
= false;
109 static bool arg_no_sync
= false;
110 static bool arg_no_wall
= false;
111 static bool arg_no_reload
= false;
112 static bool arg_value
= false;
113 static bool arg_show_types
= false;
114 static bool arg_ignore_inhibitors
= false;
115 static bool arg_dry_run
= false;
116 static bool arg_quiet
= false;
117 static bool arg_full
= false;
118 static bool arg_recursive
= false;
119 static bool arg_show_transaction
= false;
120 static int arg_force
= 0;
121 static bool arg_ask_password
= false;
122 static bool arg_runtime
= false;
123 static UnitFilePresetMode arg_preset_mode
= UNIT_FILE_PRESET_FULL
;
124 static char **arg_wall
= NULL
;
125 static const char *arg_kill_who
= NULL
;
126 static int arg_signal
= SIGTERM
;
127 static char *arg_root
= NULL
;
128 static usec_t arg_when
= 0;
139 ACTION_SUSPEND_THEN_HIBERNATE
,
150 ACTION_CANCEL_SHUTDOWN
,
153 } arg_action
= ACTION_SYSTEMCTL
;
154 static BusTransport arg_transport
= BUS_TRANSPORT_LOCAL
;
155 static const char *arg_host
= NULL
;
156 static unsigned arg_lines
= 10;
157 static OutputMode arg_output
= OUTPUT_SHORT
;
158 static bool arg_plain
= false;
159 static bool arg_firmware_setup
= false;
160 static usec_t arg_boot_loader_menu
= USEC_INFINITY
;
161 static const char *arg_boot_loader_entry
= NULL
;
162 static bool arg_now
= false;
163 static bool arg_jobs_before
= false;
164 static bool arg_jobs_after
= false;
165 static char **arg_clean_what
= NULL
;
167 /* This is a global cache that will be constructed on first use. */
168 static Hashmap
*cached_id_map
= NULL
;
169 static Hashmap
*cached_name_map
= NULL
;
171 STATIC_DESTRUCTOR_REGISTER(arg_wall
, strv_freep
);
172 STATIC_DESTRUCTOR_REGISTER(arg_root
, freep
);
173 STATIC_DESTRUCTOR_REGISTER(arg_types
, strv_freep
);
174 STATIC_DESTRUCTOR_REGISTER(arg_states
, strv_freep
);
175 STATIC_DESTRUCTOR_REGISTER(arg_properties
, strv_freep
);
176 STATIC_DESTRUCTOR_REGISTER(arg_clean_what
, strv_freep
);
177 STATIC_DESTRUCTOR_REGISTER(cached_id_map
, hashmap_freep
);
178 STATIC_DESTRUCTOR_REGISTER(cached_name_map
, hashmap_freep
);
180 static int daemon_reload(int argc
, char *argv
[], void* userdata
);
181 static int trivial_method(int argc
, char *argv
[], void *userdata
);
182 static int halt_now(enum action a
);
183 static int get_state_one_unit(sd_bus
*bus
, const char *name
, UnitActiveState
*active_state
);
185 static bool original_stdout_is_tty
;
187 typedef enum BusFocus
{
188 BUS_FULL
, /* The full bus indicated via --system or --user */
189 BUS_MANAGER
, /* The manager itself, possibly directly, possibly via the bus */
193 static sd_bus
*buses
[_BUS_FOCUS_MAX
] = {};
195 static UnitFileFlags
args_to_flags(void) {
196 return (arg_runtime
? UNIT_FILE_RUNTIME
: 0) |
197 (arg_force
? UNIT_FILE_FORCE
: 0);
200 static int acquire_bus(BusFocus focus
, sd_bus
**ret
) {
203 assert(focus
< _BUS_FOCUS_MAX
);
206 /* We only go directly to the manager, if we are using a local transport */
207 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
210 if (getenv_bool("SYSTEMCTL_FORCE_BUS") > 0)
216 user
= arg_scope
!= UNIT_FILE_SYSTEM
;
218 if (focus
== BUS_MANAGER
)
219 r
= bus_connect_transport_systemd(arg_transport
, arg_host
, user
, &buses
[focus
]);
221 r
= bus_connect_transport(arg_transport
, arg_host
, user
, &buses
[focus
]);
223 return log_error_errno(r
, "Failed to connect to bus: %m");
225 (void) sd_bus_set_allow_interactive_authorization(buses
[focus
], arg_ask_password
);
232 static void release_busses(void) {
235 for (w
= 0; w
< _BUS_FOCUS_MAX
; w
++)
236 buses
[w
] = sd_bus_flush_close_unref(buses
[w
]);
239 static void ask_password_agent_open_maybe(void) {
240 /* Open the password agent as a child process if necessary */
245 if (arg_scope
!= UNIT_FILE_SYSTEM
)
248 ask_password_agent_open_if_enabled(arg_transport
, arg_ask_password
);
251 static void polkit_agent_open_maybe(void) {
252 /* Open the polkit agent as a child process if necessary */
254 if (arg_scope
!= UNIT_FILE_SYSTEM
)
257 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
260 static OutputFlags
get_output_flags(void) {
262 arg_all
* OUTPUT_SHOW_ALL
|
263 (arg_full
|| !on_tty() || pager_have()) * OUTPUT_FULL_WIDTH
|
264 colors_enabled() * OUTPUT_COLOR
|
265 !arg_quiet
* OUTPUT_WARN_CUTOFF
;
268 static int translate_bus_error_to_exit_status(int r
, const sd_bus_error
*error
) {
271 if (!sd_bus_error_is_set(error
))
274 if (sd_bus_error_has_name(error
, SD_BUS_ERROR_ACCESS_DENIED
) ||
275 sd_bus_error_has_name(error
, BUS_ERROR_ONLY_BY_DEPENDENCY
) ||
276 sd_bus_error_has_name(error
, BUS_ERROR_NO_ISOLATION
) ||
277 sd_bus_error_has_name(error
, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE
))
278 return EXIT_NOPERMISSION
;
280 if (sd_bus_error_has_name(error
, BUS_ERROR_NO_SUCH_UNIT
))
281 return EXIT_NOTINSTALLED
;
283 if (sd_bus_error_has_name(error
, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE
) ||
284 sd_bus_error_has_name(error
, SD_BUS_ERROR_NOT_SUPPORTED
))
285 return EXIT_NOTIMPLEMENTED
;
287 if (sd_bus_error_has_name(error
, BUS_ERROR_LOAD_FAILED
))
288 return EXIT_NOTCONFIGURED
;
296 static bool install_client_side(void) {
297 /* Decides when to execute enable/disable/... operations
298 * client-side rather than server-side. */
300 if (running_in_chroot_or_offline())
303 if (sd_booted() <= 0)
306 if (!isempty(arg_root
))
309 if (arg_scope
== UNIT_FILE_GLOBAL
)
312 /* Unsupported environment variable, mostly for debugging purposes */
313 if (getenv_bool("SYSTEMCTL_INSTALL_CLIENT_SIDE") > 0)
319 static int compare_unit_info(const UnitInfo
*a
, const UnitInfo
*b
) {
323 /* First, order by machine */
324 if (!a
->machine
&& b
->machine
)
326 if (a
->machine
&& !b
->machine
)
328 if (a
->machine
&& b
->machine
) {
329 r
= strcasecmp(a
->machine
, b
->machine
);
334 /* Second, order by unit type */
335 d1
= strrchr(a
->id
, '.');
336 d2
= strrchr(b
->id
, '.');
338 r
= strcasecmp(d1
, d2
);
343 /* Third, order by name */
344 return strcasecmp(a
->id
, b
->id
);
347 static const char* unit_type_suffix(const char *name
) {
350 dot
= strrchr(name
, '.');
357 static bool output_show_unit(const UnitInfo
*u
, char **patterns
) {
360 if (!strv_fnmatch_or_empty(patterns
, u
->id
, FNM_NOESCAPE
))
363 if (arg_types
&& !strv_find(arg_types
, unit_type_suffix(u
->id
)))
369 /* Note that '--all' is not purely a state filter, but also a
370 * filter that hides units that "follow" other units (which is
371 * used for device units that appear under different names). */
372 if (!isempty(u
->following
))
375 if (!strv_isempty(arg_states
))
378 /* By default show all units except the ones in inactive
379 * state and with no pending job */
383 if (streq(u
->active_state
, "inactive"))
389 static int output_units_list(const UnitInfo
*unit_infos
, unsigned c
) {
390 unsigned circle_len
= 0, id_len
, max_id_len
, load_len
, active_len
, sub_len
, job_len
, desc_len
, max_desc_len
;
392 unsigned n_shown
= 0;
394 bool full
= arg_full
|| FLAGS_SET(arg_pager_flags
, PAGER_DISABLE
);
396 max_id_len
= STRLEN("UNIT");
397 load_len
= STRLEN("LOAD");
398 active_len
= STRLEN("ACTIVE");
399 sub_len
= STRLEN("SUB");
400 job_len
= STRLEN("JOB");
401 max_desc_len
= STRLEN("DESCRIPTION");
403 for (u
= unit_infos
; u
< unit_infos
+ c
; u
++) {
404 max_id_len
= MAX(max_id_len
, strlen(u
->id
) + (u
->machine
? strlen(u
->machine
)+1 : 0));
405 load_len
= MAX(load_len
, strlen(u
->load_state
));
406 active_len
= MAX(active_len
, strlen(u
->active_state
));
407 sub_len
= MAX(sub_len
, strlen(u
->sub_state
));
408 max_desc_len
= MAX(max_desc_len
, strlen(u
->description
));
410 if (u
->job_id
!= 0) {
411 job_len
= MAX(job_len
, strlen(u
->job_type
));
415 if (!arg_no_legend
&&
416 (streq(u
->active_state
, "failed") ||
417 STR_IN_SET(u
->load_state
, "error", "not-found", "bad-setting", "masked")))
421 if (!arg_full
&& original_stdout_is_tty
) {
424 id_len
= MIN(max_id_len
, 25u); /* as much as it needs, but at most 25 for now */
425 basic_len
= circle_len
+ 1 + id_len
+ 1 + load_len
+ 1 + active_len
+ 1 + sub_len
+ 1;
428 basic_len
+= job_len
+ 1;
430 if (basic_len
< (unsigned) columns()) {
431 unsigned extra_len
, incr
;
432 extra_len
= columns() - basic_len
;
434 /* Either UNIT already got 25, or is fully satisfied.
435 * Grant up to 25 to DESC now. */
436 incr
= MIN(extra_len
, 25u);
440 /* Of the remainder give as much as the ID needs to the ID, and give the rest to the
441 * description but not more than it needs. */
443 incr
= MIN(max_id_len
- id_len
, extra_len
);
445 desc_len
+= MIN(extra_len
- incr
, max_desc_len
- desc_len
);
451 desc_len
= max_desc_len
;
454 for (u
= unit_infos
; u
< unit_infos
+ c
; u
++) {
455 _cleanup_free_
char *e
= NULL
, *j
= NULL
;
456 const char *on_underline
= "", *off_underline
= "";
457 const char *on_loaded
= "", *off_loaded
= "";
458 const char *on_active
= "", *off_active
= "";
459 const char *on_circle
= "", *off_circle
= "";
461 bool circle
= false, underline
= false;
463 if (!n_shown
&& !arg_no_legend
) {
468 printf("%s%-*s %-*s %-*s %-*s ",
472 active_len
, "ACTIVE",
476 printf("%-*s ", job_len
, "JOB");
480 full
? -1 : (int) desc_len
,
487 if (u
+ 1 < unit_infos
+ c
&&
488 !streq(unit_type_suffix(u
->id
), unit_type_suffix((u
+ 1)->id
))) {
489 on_underline
= ansi_underline();
490 off_underline
= ansi_normal();
494 if (STR_IN_SET(u
->load_state
, "error", "not-found", "bad-setting", "masked") && !arg_plain
) {
495 on_circle
= ansi_highlight_yellow();
496 off_circle
= ansi_normal();
498 on_loaded
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
499 off_loaded
= underline
? on_underline
: ansi_normal();
500 } else if (streq(u
->active_state
, "failed") && !arg_plain
) {
501 on_circle
= ansi_highlight_red();
502 off_circle
= ansi_normal();
504 on_active
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
505 off_active
= underline
? on_underline
: ansi_normal();
509 j
= strjoin(u
->machine
, ":", u
->id
);
518 e
= ellipsize(id
, id_len
, 33);
526 printf("%s%s%s ", on_circle
, circle
? special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
) : " ", off_circle
);
528 printf("%s%s%-*s%s %s%-*s%s %s%-*s %-*s%s %-*s",
530 on_active
, id_len
, id
, off_active
,
531 on_loaded
, load_len
, u
->load_state
, off_loaded
,
532 on_active
, active_len
, u
->active_state
,
533 sub_len
, u
->sub_state
, off_active
,
534 job_count
? job_len
+ 1 : 0, u
->job_id
? u
->job_type
: "");
538 full
? -1 : (int) desc_len
,
543 if (!arg_no_legend
) {
544 const char *on
, *off
;
548 "LOAD = Reflects whether the unit definition was properly loaded.\n"
549 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
550 "SUB = The low-level unit activation state, values depend on unit type.");
551 puts(job_count
? "JOB = Pending job for the unit.\n" : "");
552 on
= ansi_highlight();
555 on
= ansi_highlight_red();
559 if (arg_all
|| strv_contains(arg_states
, "inactive"))
560 printf("%s%u loaded units listed.%s\n"
561 "To show all installed unit files use 'systemctl list-unit-files'.\n",
563 else if (!arg_states
)
564 printf("%s%u loaded units listed.%s Pass --all to see loaded but inactive units, too.\n"
565 "To show all installed unit files use 'systemctl list-unit-files'.\n",
568 printf("%u loaded units listed.\n", n_shown
);
574 static int get_unit_list(
578 UnitInfo
**unit_infos
,
580 sd_bus_message
**_reply
) {
582 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
583 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
584 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
588 bool fallback
= false;
594 r
= sd_bus_message_new_method_call(
597 "org.freedesktop.systemd1",
598 "/org/freedesktop/systemd1",
599 "org.freedesktop.systemd1.Manager",
600 "ListUnitsByPatterns");
602 return bus_log_create_error(r
);
604 r
= sd_bus_message_append_strv(m
, arg_states
);
606 return bus_log_create_error(r
);
608 r
= sd_bus_message_append_strv(m
, patterns
);
610 return bus_log_create_error(r
);
612 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
613 if (r
< 0 && (sd_bus_error_has_name(&error
, SD_BUS_ERROR_UNKNOWN_METHOD
) ||
614 sd_bus_error_has_name(&error
, SD_BUS_ERROR_ACCESS_DENIED
))) {
615 /* Fallback to legacy ListUnitsFiltered method */
617 log_debug_errno(r
, "Failed to list units: %s Falling back to ListUnitsFiltered method.", bus_error_message(&error
, r
));
618 m
= sd_bus_message_unref(m
);
619 sd_bus_error_free(&error
);
621 r
= sd_bus_message_new_method_call(
624 "org.freedesktop.systemd1",
625 "/org/freedesktop/systemd1",
626 "org.freedesktop.systemd1.Manager",
627 "ListUnitsFiltered");
629 return bus_log_create_error(r
);
631 r
= sd_bus_message_append_strv(m
, arg_states
);
633 return bus_log_create_error(r
);
635 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
638 return log_error_errno(r
, "Failed to list units: %s", bus_error_message(&error
, r
));
640 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssssouso)");
642 return bus_log_parse_error(r
);
644 while ((r
= bus_parse_unit_info(reply
, &u
)) > 0) {
647 if (!output_show_unit(&u
, fallback
? patterns
: NULL
))
650 if (!GREEDY_REALLOC(*unit_infos
, size
, c
+1))
653 (*unit_infos
)[c
++] = u
;
656 return bus_log_parse_error(r
);
658 r
= sd_bus_message_exit_container(reply
);
660 return bus_log_parse_error(r
);
662 *_reply
= TAKE_PTR(reply
);
667 static void message_set_freep(Set
**set
) {
668 set_free_with_destructor(*set
, sd_bus_message_unref
);
671 static int get_unit_list_recursive(
674 UnitInfo
**_unit_infos
,
678 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
679 _cleanup_(message_set_freep
) Set
*replies
;
680 sd_bus_message
*reply
;
688 replies
= set_new(NULL
);
692 c
= get_unit_list(bus
, NULL
, patterns
, &unit_infos
, 0, &reply
);
696 r
= set_put(replies
, reply
);
698 sd_bus_message_unref(reply
);
703 _cleanup_strv_free_
char **machines
= NULL
;
706 r
= sd_get_machine_names(&machines
);
708 return log_error_errno(r
, "Failed to get machine names: %m");
710 STRV_FOREACH(i
, machines
) {
711 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*container
= NULL
;
714 r
= sd_bus_open_system_machine(&container
, *i
);
716 log_warning_errno(r
, "Failed to connect to container %s, ignoring: %m", *i
);
720 k
= get_unit_list(container
, *i
, patterns
, &unit_infos
, c
, &reply
);
726 r
= set_put(replies
, reply
);
728 sd_bus_message_unref(reply
);
733 *_machines
= TAKE_PTR(machines
);
737 *_unit_infos
= TAKE_PTR(unit_infos
);
738 *_replies
= TAKE_PTR(replies
);
743 static int expand_names(sd_bus
*bus
, char **names
, const char* suffix
, char ***ret
, bool *ret_expanded
) {
744 _cleanup_strv_free_
char **mangled
= NULL
, **globs
= NULL
;
751 STRV_FOREACH(name
, names
) {
753 UnitNameMangle options
= UNIT_NAME_MANGLE_GLOB
| (arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
);
755 r
= unit_name_mangle_with_suffix(*name
, NULL
, options
, suffix
?: ".service", &t
);
757 return log_error_errno(r
, "Failed to mangle name: %m");
759 if (string_is_glob(t
))
760 r
= strv_consume(&globs
, t
);
762 r
= strv_consume(&mangled
, t
);
767 /* Query the manager only if any of the names are a glob, since
768 * this is fairly expensive */
769 bool expanded
= !strv_isempty(globs
);
771 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
772 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
775 r
= get_unit_list(bus
, NULL
, globs
, &unit_infos
, 0, &reply
);
779 n
= strv_length(mangled
);
782 for (i
= 0; i
< r
; i
++) {
783 if (!GREEDY_REALLOC(mangled
, allocated
, n
+2))
786 mangled
[n
] = strdup(unit_infos
[i
].id
);
795 *ret_expanded
= expanded
;
797 *ret
= TAKE_PTR(mangled
);
801 static int list_units(int argc
, char *argv
[], void *userdata
) {
802 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
803 _cleanup_(message_set_freep
) Set
*replies
= NULL
;
804 _cleanup_strv_free_
char **machines
= NULL
;
808 r
= acquire_bus(BUS_MANAGER
, &bus
);
812 (void) pager_open(arg_pager_flags
);
814 r
= get_unit_list_recursive(bus
, strv_skip(argv
, 1), &unit_infos
, &replies
, &machines
);
818 typesafe_qsort(unit_infos
, r
, compare_unit_info
);
819 return output_units_list(unit_infos
, r
);
822 static int get_triggered_units(
827 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
834 r
= sd_bus_get_property_strv(
836 "org.freedesktop.systemd1",
838 "org.freedesktop.systemd1.Unit",
843 return log_error_errno(r
, "Failed to determine triggers: %s", bus_error_message(&error
, r
));
848 static int get_listening(
850 const char* unit_path
,
853 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
854 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
855 const char *type
, *path
;
858 r
= sd_bus_get_property(
860 "org.freedesktop.systemd1",
862 "org.freedesktop.systemd1.Socket",
868 return log_error_errno(r
, "Failed to get list of listening sockets: %s", bus_error_message(&error
, r
));
870 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ss)");
872 return bus_log_parse_error(r
);
874 while ((r
= sd_bus_message_read(reply
, "(ss)", &type
, &path
)) > 0) {
876 r
= strv_extend(listening
, type
);
880 r
= strv_extend(listening
, path
);
887 return bus_log_parse_error(r
);
889 r
= sd_bus_message_exit_container(reply
);
891 return bus_log_parse_error(r
);
903 /* Note: triggered is a list here, although it almost certainly
904 * will always be one unit. Nevertheless, dbus API allows for multiple
905 * values, so let's follow that. */
908 /* The strv above is shared. free is set only in the first one. */
912 static int socket_info_compare(const struct socket_info
*a
, const struct socket_info
*b
) {
918 if (!a
->machine
&& b
->machine
)
920 if (a
->machine
&& !b
->machine
)
922 if (a
->machine
&& b
->machine
) {
923 r
= strcasecmp(a
->machine
, b
->machine
);
928 r
= strcmp(a
->path
, b
->path
);
930 r
= strcmp(a
->type
, b
->type
);
935 static int output_sockets_list(struct socket_info
*socket_infos
, unsigned cs
) {
936 struct socket_info
*s
;
937 unsigned pathlen
= STRLEN("LISTEN"),
938 typelen
= STRLEN("TYPE") * arg_show_types
,
939 socklen
= STRLEN("UNIT"),
940 servlen
= STRLEN("ACTIVATES");
941 const char *on
, *off
;
943 for (s
= socket_infos
; s
< socket_infos
+ cs
; s
++) {
947 socklen
= MAX(socklen
, strlen(s
->id
));
949 typelen
= MAX(typelen
, strlen(s
->type
));
950 pathlen
= MAX(pathlen
, strlen(s
->path
) + (s
->machine
? strlen(s
->machine
)+1 : 0));
952 STRV_FOREACH(a
, s
->triggered
)
953 tmp
+= strlen(*a
) + 2*(a
!= s
->triggered
);
954 servlen
= MAX(servlen
, tmp
);
959 printf("%-*s %-*.*s%-*s %s\n",
961 typelen
+ arg_show_types
, typelen
+ arg_show_types
, "TYPE ",
965 for (s
= socket_infos
; s
< socket_infos
+ cs
; s
++) {
966 _cleanup_free_
char *j
= NULL
;
971 j
= strjoin(s
->machine
, ":", s
->path
);
979 printf("%-*s %-*s %-*s",
980 pathlen
, path
, typelen
, s
->type
, socklen
, s
->id
);
983 pathlen
, path
, socklen
, s
->id
);
984 STRV_FOREACH(a
, s
->triggered
)
986 a
== s
->triggered
? "" : ",", *a
);
990 on
= ansi_highlight();
995 on
= ansi_highlight_red();
999 if (!arg_no_legend
) {
1000 printf("%s%u sockets listed.%s\n", on
, cs
, off
);
1002 printf("Pass --all to see loaded but inactive sockets, too.\n");
1008 static int list_sockets(int argc
, char *argv
[], void *userdata
) {
1009 _cleanup_(message_set_freep
) Set
*replies
= NULL
;
1010 _cleanup_strv_free_
char **machines
= NULL
;
1011 _cleanup_strv_free_
char **sockets_with_suffix
= NULL
;
1012 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
1013 _cleanup_free_
struct socket_info
*socket_infos
= NULL
;
1015 struct socket_info
*s
;
1021 r
= acquire_bus(BUS_MANAGER
, &bus
);
1025 (void) pager_open(arg_pager_flags
);
1027 r
= expand_names(bus
, strv_skip(argv
, 1), ".socket", &sockets_with_suffix
, NULL
);
1031 if (argc
== 1 || sockets_with_suffix
) {
1032 n
= get_unit_list_recursive(bus
, sockets_with_suffix
, &unit_infos
, &replies
, &machines
);
1036 for (u
= unit_infos
; u
< unit_infos
+ n
; u
++) {
1037 _cleanup_strv_free_
char **listening
= NULL
, **triggered
= NULL
;
1040 if (!endswith(u
->id
, ".socket"))
1043 r
= get_triggered_units(bus
, u
->unit_path
, &triggered
);
1047 c
= get_listening(bus
, u
->unit_path
, &listening
);
1053 if (!GREEDY_REALLOC(socket_infos
, size
, cs
+ c
)) {
1058 for (i
= 0; i
< c
; i
++)
1059 socket_infos
[cs
+ i
] = (struct socket_info
) {
1060 .machine
= u
->machine
,
1062 .type
= listening
[i
*2],
1063 .path
= listening
[i
*2 + 1],
1064 .triggered
= triggered
,
1065 .own_triggered
= i
==0,
1068 /* from this point on we will cleanup those socket_infos */
1071 listening
= triggered
= NULL
; /* avoid cleanup */
1074 typesafe_qsort(socket_infos
, cs
, socket_info_compare
);
1077 output_sockets_list(socket_infos
, cs
);
1080 assert(cs
== 0 || socket_infos
);
1081 for (s
= socket_infos
; s
< socket_infos
+ cs
; s
++) {
1084 if (s
->own_triggered
)
1085 strv_free(s
->triggered
);
1091 static int get_next_elapse(
1094 dual_timestamp
*next
) {
1096 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1104 r
= sd_bus_get_property_trivial(
1106 "org.freedesktop.systemd1",
1108 "org.freedesktop.systemd1.Timer",
1109 "NextElapseUSecMonotonic",
1114 return log_error_errno(r
, "Failed to get next elapse time: %s", bus_error_message(&error
, r
));
1116 r
= sd_bus_get_property_trivial(
1118 "org.freedesktop.systemd1",
1120 "org.freedesktop.systemd1.Timer",
1121 "NextElapseUSecRealtime",
1126 return log_error_errno(r
, "Failed to get next elapse time: %s", bus_error_message(&error
, r
));
1132 static int get_last_trigger(
1137 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1144 r
= sd_bus_get_property_trivial(
1146 "org.freedesktop.systemd1",
1148 "org.freedesktop.systemd1.Timer",
1154 return log_error_errno(r
, "Failed to get last trigger time: %s", bus_error_message(&error
, r
));
1160 const char* machine
;
1163 usec_t last_trigger
;
1167 static int timer_info_compare(const struct timer_info
*a
, const struct timer_info
*b
) {
1173 if (!a
->machine
&& b
->machine
)
1175 if (a
->machine
&& !b
->machine
)
1177 if (a
->machine
&& b
->machine
) {
1178 r
= strcasecmp(a
->machine
, b
->machine
);
1183 r
= CMP(a
->next_elapse
, b
->next_elapse
);
1187 return strcmp(a
->id
, b
->id
);
1190 static int output_timers_list(struct timer_info
*timer_infos
, unsigned n
) {
1191 struct timer_info
*t
;
1193 nextlen
= STRLEN("NEXT"),
1194 leftlen
= STRLEN("LEFT"),
1195 lastlen
= STRLEN("LAST"),
1196 passedlen
= STRLEN("PASSED"),
1197 unitlen
= STRLEN("UNIT"),
1198 activatelen
= STRLEN("ACTIVATES");
1200 const char *on
, *off
;
1202 assert(timer_infos
|| n
== 0);
1204 for (t
= timer_infos
; t
< timer_infos
+ n
; t
++) {
1208 if (t
->next_elapse
> 0) {
1209 char tstamp
[FORMAT_TIMESTAMP_MAX
] = "", trel
[FORMAT_TIMESTAMP_RELATIVE_MAX
] = "";
1211 format_timestamp(tstamp
, sizeof(tstamp
), t
->next_elapse
);
1212 nextlen
= MAX(nextlen
, strlen(tstamp
) + 1);
1214 format_timestamp_relative(trel
, sizeof(trel
), t
->next_elapse
);
1215 leftlen
= MAX(leftlen
, strlen(trel
));
1218 if (t
->last_trigger
> 0) {
1219 char tstamp
[FORMAT_TIMESTAMP_MAX
] = "", trel
[FORMAT_TIMESTAMP_RELATIVE_MAX
] = "";
1221 format_timestamp(tstamp
, sizeof(tstamp
), t
->last_trigger
);
1222 lastlen
= MAX(lastlen
, strlen(tstamp
) + 1);
1224 format_timestamp_relative(trel
, sizeof(trel
), t
->last_trigger
);
1225 passedlen
= MAX(passedlen
, strlen(trel
));
1228 unitlen
= MAX(unitlen
, strlen(t
->id
) + (t
->machine
? strlen(t
->machine
)+1 : 0));
1230 STRV_FOREACH(a
, t
->triggered
)
1231 ul
+= strlen(*a
) + 2*(a
!= t
->triggered
);
1233 activatelen
= MAX(activatelen
, ul
);
1238 printf("%-*s %-*s %-*s %-*s %-*s %s\n",
1242 passedlen
, "PASSED",
1246 for (t
= timer_infos
; t
< timer_infos
+ n
; t
++) {
1247 _cleanup_free_
char *j
= NULL
;
1249 char tstamp1
[FORMAT_TIMESTAMP_MAX
] = "n/a", trel1
[FORMAT_TIMESTAMP_RELATIVE_MAX
] = "n/a";
1250 char tstamp2
[FORMAT_TIMESTAMP_MAX
] = "n/a", trel2
[FORMAT_TIMESTAMP_RELATIVE_MAX
] = "n/a";
1253 format_timestamp(tstamp1
, sizeof(tstamp1
), t
->next_elapse
);
1254 format_timestamp_relative(trel1
, sizeof(trel1
), t
->next_elapse
);
1256 format_timestamp(tstamp2
, sizeof(tstamp2
), t
->last_trigger
);
1257 format_timestamp_relative(trel2
, sizeof(trel2
), t
->last_trigger
);
1260 j
= strjoin(t
->machine
, ":", t
->id
);
1267 printf("%-*s %-*s %-*s %-*s %-*s",
1268 nextlen
, tstamp1
, leftlen
, trel1
, lastlen
, tstamp2
, passedlen
, trel2
, unitlen
, unit
);
1270 STRV_FOREACH(a
, t
->triggered
)
1272 a
== t
->triggered
? "" : ",", *a
);
1276 on
= ansi_highlight();
1277 off
= ansi_normal();
1281 on
= ansi_highlight_red();
1282 off
= ansi_normal();
1285 if (!arg_no_legend
) {
1286 printf("%s%u timers listed.%s\n", on
, n
, off
);
1288 printf("Pass --all to see loaded but inactive timers, too.\n");
1294 static usec_t
calc_next_elapse(dual_timestamp
*nw
, dual_timestamp
*next
) {
1300 if (timestamp_is_set(next
->monotonic
)) {
1303 if (next
->monotonic
> nw
->monotonic
)
1304 converted
= nw
->realtime
+ (next
->monotonic
- nw
->monotonic
);
1306 converted
= nw
->realtime
- (nw
->monotonic
- next
->monotonic
);
1308 if (timestamp_is_set(next
->realtime
))
1309 next_elapse
= MIN(converted
, next
->realtime
);
1311 next_elapse
= converted
;
1314 next_elapse
= next
->realtime
;
1319 static int list_timers(int argc
, char *argv
[], void *userdata
) {
1320 _cleanup_(message_set_freep
) Set
*replies
= NULL
;
1321 _cleanup_strv_free_
char **machines
= NULL
;
1322 _cleanup_strv_free_
char **timers_with_suffix
= NULL
;
1323 _cleanup_free_
struct timer_info
*timer_infos
= NULL
;
1324 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
1325 struct timer_info
*t
;
1333 r
= acquire_bus(BUS_MANAGER
, &bus
);
1337 (void) pager_open(arg_pager_flags
);
1339 r
= expand_names(bus
, strv_skip(argv
, 1), ".timer", &timers_with_suffix
, NULL
);
1343 if (argc
== 1 || timers_with_suffix
) {
1344 n
= get_unit_list_recursive(bus
, timers_with_suffix
, &unit_infos
, &replies
, &machines
);
1348 dual_timestamp_get(&nw
);
1350 for (u
= unit_infos
; u
< unit_infos
+ n
; u
++) {
1351 _cleanup_strv_free_
char **triggered
= NULL
;
1352 dual_timestamp next
= DUAL_TIMESTAMP_NULL
;
1355 if (!endswith(u
->id
, ".timer"))
1358 r
= get_triggered_units(bus
, u
->unit_path
, &triggered
);
1362 r
= get_next_elapse(bus
, u
->unit_path
, &next
);
1366 get_last_trigger(bus
, u
->unit_path
, &last
);
1368 if (!GREEDY_REALLOC(timer_infos
, size
, c
+1)) {
1373 m
= calc_next_elapse(&nw
, &next
);
1375 timer_infos
[c
++] = (struct timer_info
) {
1376 .machine
= u
->machine
,
1379 .last_trigger
= last
,
1380 .triggered
= TAKE_PTR(triggered
),
1384 typesafe_qsort(timer_infos
, c
, timer_info_compare
);
1387 output_timers_list(timer_infos
, c
);
1390 for (t
= timer_infos
; t
< timer_infos
+ c
; t
++)
1391 strv_free(t
->triggered
);
1396 static int compare_unit_file_list(const UnitFileList
*a
, const UnitFileList
*b
) {
1397 const char *d1
, *d2
;
1399 d1
= strrchr(a
->path
, '.');
1400 d2
= strrchr(b
->path
, '.');
1405 r
= strcasecmp(d1
, d2
);
1410 return strcasecmp(basename(a
->path
), basename(b
->path
));
1413 static bool output_show_unit_file(const UnitFileList
*u
, char **states
, char **patterns
) {
1416 if (!strv_fnmatch_or_empty(patterns
, basename(u
->path
), FNM_NOESCAPE
))
1419 if (!strv_isempty(arg_types
)) {
1422 dot
= strrchr(u
->path
, '.');
1426 if (!strv_find(arg_types
, dot
+1))
1430 if (!strv_isempty(states
) &&
1431 !strv_find(states
, unit_file_state_to_string(u
->state
)))
1437 static void output_unit_file_list(const UnitFileList
*units
, unsigned c
) {
1438 unsigned max_id_len
, id_cols
, state_cols
;
1439 const UnitFileList
*u
;
1441 max_id_len
= STRLEN("UNIT FILE");
1442 state_cols
= STRLEN("STATE");
1444 for (u
= units
; u
< units
+ c
; u
++) {
1445 max_id_len
= MAX(max_id_len
, strlen(basename(u
->path
)));
1446 state_cols
= MAX(state_cols
, strlen(unit_file_state_to_string(u
->state
)));
1450 unsigned basic_cols
;
1452 id_cols
= MIN(max_id_len
, 25u);
1453 basic_cols
= 1 + id_cols
+ state_cols
;
1454 if (basic_cols
< (unsigned) columns())
1455 id_cols
+= MIN(columns() - basic_cols
, max_id_len
- id_cols
);
1457 id_cols
= max_id_len
;
1459 if (!arg_no_legend
&& c
> 0)
1460 printf("%s%-*s %-*s%s\n",
1462 id_cols
, "UNIT FILE",
1463 state_cols
, "STATE",
1466 for (u
= units
; u
< units
+ c
; u
++) {
1467 const char *on_underline
= NULL
, *on_color
= NULL
, *off
= NULL
, *id
;
1468 _cleanup_free_
char *e
= NULL
;
1471 underline
= u
+ 1 < units
+ c
&&
1472 !streq(unit_type_suffix(u
->path
), unit_type_suffix((u
+ 1)->path
));
1475 on_underline
= ansi_underline();
1477 if (IN_SET(u
->state
,
1479 UNIT_FILE_MASKED_RUNTIME
,
1482 on_color
= underline
? ansi_highlight_red_underline() : ansi_highlight_red();
1483 else if (u
->state
== UNIT_FILE_ENABLED
)
1484 on_color
= underline
? ansi_highlight_green_underline() : ansi_highlight_green();
1486 if (on_underline
|| on_color
)
1487 off
= ansi_normal();
1489 id
= basename(u
->path
);
1491 e
= arg_full
? NULL
: ellipsize(id
, id_cols
, 33);
1493 printf("%s%-*s %s%-*s%s\n",
1494 strempty(on_underline
),
1495 id_cols
, e
? e
: id
,
1496 strempty(on_color
), state_cols
, unit_file_state_to_string(u
->state
), strempty(off
));
1500 printf("\n%u unit files listed.\n", c
);
1503 static int list_unit_files(int argc
, char *argv
[], void *userdata
) {
1504 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1505 _cleanup_free_ UnitFileList
*units
= NULL
;
1512 bool fallback
= false;
1514 if (install_client_side()) {
1520 h
= hashmap_new(&string_hash_ops
);
1524 r
= unit_file_get_list(arg_scope
, arg_root
, h
, arg_states
, strv_skip(argv
, 1));
1526 unit_file_list_free(h
);
1527 return log_error_errno(r
, "Failed to get unit file list: %m");
1530 n_units
= hashmap_size(h
);
1532 units
= new(UnitFileList
, n_units
?: 1); /* avoid malloc(0) */
1534 unit_file_list_free(h
);
1538 HASHMAP_FOREACH(u
, h
, i
) {
1539 if (!output_show_unit_file(u
, NULL
, NULL
))
1546 assert(c
<= n_units
);
1551 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
1552 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1555 r
= acquire_bus(BUS_MANAGER
, &bus
);
1559 r
= sd_bus_message_new_method_call(
1562 "org.freedesktop.systemd1",
1563 "/org/freedesktop/systemd1",
1564 "org.freedesktop.systemd1.Manager",
1565 "ListUnitFilesByPatterns");
1567 return bus_log_create_error(r
);
1569 r
= sd_bus_message_append_strv(m
, arg_states
);
1571 return bus_log_create_error(r
);
1573 r
= sd_bus_message_append_strv(m
, strv_skip(argv
, 1));
1575 return bus_log_create_error(r
);
1577 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1578 if (r
< 0 && sd_bus_error_has_name(&error
, SD_BUS_ERROR_UNKNOWN_METHOD
)) {
1579 /* Fallback to legacy ListUnitFiles method */
1581 log_debug_errno(r
, "Failed to list unit files: %s Falling back to ListUnitsFiles method.", bus_error_message(&error
, r
));
1582 m
= sd_bus_message_unref(m
);
1583 sd_bus_error_free(&error
);
1585 r
= sd_bus_message_new_method_call(
1588 "org.freedesktop.systemd1",
1589 "/org/freedesktop/systemd1",
1590 "org.freedesktop.systemd1.Manager",
1593 return bus_log_create_error(r
);
1595 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1598 return log_error_errno(r
, "Failed to list unit files: %s", bus_error_message(&error
, r
));
1600 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ss)");
1602 return bus_log_parse_error(r
);
1604 while ((r
= sd_bus_message_read(reply
, "(ss)", &path
, &state
)) > 0) {
1606 if (!GREEDY_REALLOC(units
, size
, c
+ 1))
1609 units
[c
] = (struct UnitFileList
) {
1611 unit_file_state_from_string(state
)
1614 if (output_show_unit_file(&units
[c
],
1615 fallback
? arg_states
: NULL
,
1616 fallback
? strv_skip(argv
, 1) : NULL
))
1621 return bus_log_parse_error(r
);
1623 r
= sd_bus_message_exit_container(reply
);
1625 return bus_log_parse_error(r
);
1628 (void) pager_open(arg_pager_flags
);
1630 typesafe_qsort(units
, c
, compare_unit_file_list
);
1631 output_unit_file_list(units
, c
);
1633 if (install_client_side())
1634 for (unit
= units
; unit
< units
+ c
; unit
++)
1640 static int list_dependencies_print(const char *name
, int level
, unsigned branches
, bool last
) {
1641 _cleanup_free_
char *n
= NULL
;
1642 size_t max_len
= MAX(columns(),20u);
1648 for (i
= level
- 1; i
>= 0; i
--) {
1650 if (len
> max_len
- 3 && !arg_full
) {
1651 printf("%s...\n",max_len
% 2 ? "" : " ");
1654 printf("%s", special_glyph(branches
& (1 << i
) ? SPECIAL_GLYPH_TREE_VERTICAL
: SPECIAL_GLYPH_TREE_SPACE
));
1658 if (len
> max_len
- 3 && !arg_full
) {
1659 printf("%s...\n",max_len
% 2 ? "" : " ");
1663 printf("%s", special_glyph(last
? SPECIAL_GLYPH_TREE_RIGHT
: SPECIAL_GLYPH_TREE_BRANCH
));
1667 printf("%s\n", name
);
1671 n
= ellipsize(name
, max_len
-len
, 100);
1679 static int list_dependencies_get_dependencies(sd_bus
*bus
, const char *name
, char ***deps
) {
1680 struct DependencyStatusInfo
{
1684 static const struct bus_properties_map map
[_DEPENDENCY_MAX
][6] = {
1685 [DEPENDENCY_FORWARD
] = {
1686 { "Requires", "as", NULL
, offsetof(struct DependencyStatusInfo
, dep
[0]) },
1687 { "Requisite", "as", NULL
, offsetof(struct DependencyStatusInfo
, dep
[1]) },
1688 { "Wants", "as", NULL
, offsetof(struct DependencyStatusInfo
, dep
[2]) },
1689 { "ConsistsOf", "as", NULL
, offsetof(struct DependencyStatusInfo
, dep
[3]) },
1690 { "BindsTo", "as", NULL
, offsetof(struct DependencyStatusInfo
, dep
[4]) },
1693 [DEPENDENCY_REVERSE
] = {
1694 { "RequiredBy", "as", NULL
, offsetof(struct DependencyStatusInfo
, dep
[0]) },
1695 { "RequisiteOf", "as", NULL
, offsetof(struct DependencyStatusInfo
, dep
[1]) },
1696 { "WantedBy", "as", NULL
, offsetof(struct DependencyStatusInfo
, dep
[2]) },
1697 { "PartOf", "as", NULL
, offsetof(struct DependencyStatusInfo
, dep
[3]) },
1698 { "BoundBy", "as", NULL
, offsetof(struct DependencyStatusInfo
, dep
[4]) },
1701 [DEPENDENCY_AFTER
] = {
1702 { "After", "as", NULL
, offsetof(struct DependencyStatusInfo
, dep
[0]) },
1705 [DEPENDENCY_BEFORE
] = {
1706 { "Before", "as", NULL
, offsetof(struct DependencyStatusInfo
, dep
[0]) },
1711 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1712 _cleanup_strv_free_
char **ret
= NULL
;
1713 _cleanup_free_
char *dbus_path
= NULL
;
1720 dbus_path
= unit_dbus_path_from_name(name
);
1724 r
= bus_map_all_properties(bus
,
1725 "org.freedesktop.systemd1",
1727 map
[arg_dependency
],
1733 return log_error_errno(r
, "Failed to get properties of %s: %s", name
, bus_error_message(&error
, r
));
1735 if (IN_SET(arg_dependency
, DEPENDENCY_AFTER
, DEPENDENCY_BEFORE
)) {
1736 *deps
= info
.dep
[0];
1740 for (i
= 0; i
< 5; i
++) {
1741 r
= strv_extend_strv(&ret
, info
.dep
[i
], true);
1744 info
.dep
[i
] = strv_free(info
.dep
[i
]);
1747 *deps
= TAKE_PTR(ret
);
1752 static int list_dependencies_compare(char * const *a
, char * const *b
) {
1753 if (unit_name_to_type(*a
) == UNIT_TARGET
&& unit_name_to_type(*b
) != UNIT_TARGET
)
1755 if (unit_name_to_type(*a
) != UNIT_TARGET
&& unit_name_to_type(*b
) == UNIT_TARGET
)
1758 return strcasecmp(*a
, *b
);
1761 static int list_dependencies_one(
1766 unsigned branches
) {
1768 _cleanup_strv_free_
char **deps
= NULL
;
1776 r
= strv_extend(units
, name
);
1780 r
= list_dependencies_get_dependencies(bus
, name
, &deps
);
1784 typesafe_qsort(deps
, strv_length(deps
), list_dependencies_compare
);
1786 STRV_FOREACH(c
, deps
) {
1787 if (strv_contains(*units
, *c
)) {
1790 r
= list_dependencies_print("...", level
+ 1, (branches
<< 1) | (c
[1] == NULL
? 0 : 1), 1);
1800 UnitActiveState active_state
= _UNIT_ACTIVE_STATE_INVALID
;
1803 (void) get_state_one_unit(bus
, *c
, &active_state
);
1805 switch (active_state
) {
1807 case UNIT_RELOADING
:
1808 case UNIT_ACTIVATING
:
1809 on
= ansi_highlight_green();
1813 case UNIT_DEACTIVATING
:
1818 on
= ansi_highlight_red();
1822 printf("%s%s%s ", on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), ansi_normal());
1825 r
= list_dependencies_print(*c
, level
, branches
, c
[1] == NULL
);
1829 if (arg_all
|| unit_name_to_type(*c
) == UNIT_TARGET
) {
1830 r
= list_dependencies_one(bus
, *c
, level
+ 1, units
, (branches
<< 1) | (c
[1] == NULL
? 0 : 1));
1837 strv_remove(*units
, name
);
1842 static int list_dependencies(int argc
, char *argv
[], void *userdata
) {
1843 _cleanup_strv_free_
char **units
= NULL
;
1844 _cleanup_free_
char *unit
= NULL
;
1850 r
= unit_name_mangle(argv
[1], arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, &unit
);
1852 return log_error_errno(r
, "Failed to mangle unit name: %m");
1856 u
= SPECIAL_DEFAULT_TARGET
;
1858 r
= acquire_bus(BUS_MANAGER
, &bus
);
1862 (void) pager_open(arg_pager_flags
);
1866 return list_dependencies_one(bus
, u
, 0, &units
, 0);
1869 struct machine_info
{
1873 char *control_group
;
1874 uint32_t n_failed_units
;
1879 static const struct bus_properties_map machine_info_property_map
[] = {
1880 { "SystemState", "s", NULL
, offsetof(struct machine_info
, state
) },
1881 { "NJobs", "u", NULL
, offsetof(struct machine_info
, n_jobs
) },
1882 { "NFailedUnits", "u", NULL
, offsetof(struct machine_info
, n_failed_units
) },
1883 { "ControlGroup", "s", NULL
, offsetof(struct machine_info
, control_group
) },
1884 { "UserspaceTimestamp", "t", NULL
, offsetof(struct machine_info
, timestamp
) },
1888 static void machine_info_clear(struct machine_info
*info
) {
1893 free(info
->control_group
);
1897 static void free_machines_list(struct machine_info
*machine_infos
, int n
) {
1903 for (i
= 0; i
< n
; i
++)
1904 machine_info_clear(&machine_infos
[i
]);
1906 free(machine_infos
);
1909 static int compare_machine_info(const struct machine_info
*a
, const struct machine_info
*b
) {
1912 r
= CMP(b
->is_host
, a
->is_host
);
1916 return strcasecmp(a
->name
, b
->name
);
1919 static int get_machine_properties(sd_bus
*bus
, struct machine_info
*mi
) {
1920 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*container
= NULL
;
1926 r
= sd_bus_open_system_machine(&container
, mi
->name
);
1933 r
= bus_map_all_properties(
1935 "org.freedesktop.systemd1",
1936 "/org/freedesktop/systemd1",
1937 machine_info_property_map
,
1948 static bool output_show_machine(const char *name
, char **patterns
) {
1949 return strv_fnmatch_or_empty(patterns
, name
, FNM_NOESCAPE
);
1952 static int get_machine_list(
1954 struct machine_info
**_machine_infos
,
1957 struct machine_info
*machine_infos
= NULL
;
1958 _cleanup_strv_free_
char **m
= NULL
;
1959 _cleanup_free_
char *hn
= NULL
;
1964 hn
= gethostname_malloc();
1968 if (output_show_machine(hn
, patterns
)) {
1969 if (!GREEDY_REALLOC0(machine_infos
, sz
, c
+1))
1972 machine_infos
[c
].is_host
= true;
1973 machine_infos
[c
].name
= TAKE_PTR(hn
);
1975 (void) get_machine_properties(bus
, &machine_infos
[c
]);
1979 r
= sd_get_machine_names(&m
);
1981 return log_error_errno(r
, "Failed to get machine list: %m");
1983 STRV_FOREACH(i
, m
) {
1984 _cleanup_free_
char *class = NULL
;
1986 if (!output_show_machine(*i
, patterns
))
1989 sd_machine_get_class(*i
, &class);
1990 if (!streq_ptr(class, "container"))
1993 if (!GREEDY_REALLOC0(machine_infos
, sz
, c
+1)) {
1994 free_machines_list(machine_infos
, c
);
1998 machine_infos
[c
].is_host
= false;
1999 machine_infos
[c
].name
= strdup(*i
);
2000 if (!machine_infos
[c
].name
) {
2001 free_machines_list(machine_infos
, c
);
2005 (void) get_machine_properties(NULL
, &machine_infos
[c
]);
2009 *_machine_infos
= machine_infos
;
2013 static void output_machines_list(struct machine_info
*machine_infos
, unsigned n
) {
2014 struct machine_info
*m
;
2017 namelen
= STRLEN("NAME"),
2018 statelen
= STRLEN("STATE"),
2019 failedlen
= STRLEN("FAILED"),
2020 jobslen
= STRLEN("JOBS");
2021 bool state_missing
= false;
2023 assert(machine_infos
|| n
== 0);
2025 for (m
= machine_infos
; m
< machine_infos
+ n
; m
++) {
2026 namelen
= MAX(namelen
,
2027 strlen(m
->name
) + (m
->is_host
? STRLEN(" (host)") : 0));
2028 statelen
= MAX(statelen
, strlen_ptr(m
->state
));
2029 failedlen
= MAX(failedlen
, DECIMAL_STR_WIDTH(m
->n_failed_units
));
2030 jobslen
= MAX(jobslen
, DECIMAL_STR_WIDTH(m
->n_jobs
));
2032 if (!arg_plain
&& m
->state
&& !streq(m
->state
, "running"))
2036 if (!arg_no_legend
) {
2040 printf("%-*s %-*s %-*s %-*s\n",
2043 failedlen
, "FAILED",
2047 for (m
= machine_infos
; m
< machine_infos
+ n
; m
++) {
2048 const char *on_state
= "", *off_state
= "";
2049 const char *on_failed
= "", *off_failed
= "";
2050 bool circle
= false;
2052 if (streq_ptr(m
->state
, "degraded")) {
2053 on_state
= ansi_highlight_red();
2054 off_state
= ansi_normal();
2056 } else if (!streq_ptr(m
->state
, "running")) {
2057 on_state
= ansi_highlight_yellow();
2058 off_state
= ansi_normal();
2062 if (m
->n_failed_units
> 0) {
2063 on_failed
= ansi_highlight_red();
2064 off_failed
= ansi_normal();
2066 on_failed
= off_failed
= "";
2069 printf("%s%s%s ", on_state
, circle
? special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
) : " ", off_state
);
2072 state_missing
= true;
2075 printf("%-*s (host) %s%-*s%s %s%*" PRIu32
"%s %*" PRIu32
"\n",
2076 (int) (namelen
- strlen(" (host)")),
2078 on_state
, statelen
, strna(m
->state
), off_state
,
2079 on_failed
, failedlen
, m
->n_failed_units
, off_failed
,
2080 jobslen
, m
->n_jobs
);
2082 printf("%-*s %s%-*s%s %s%*" PRIu32
"%s %*" PRIu32
"\n",
2083 namelen
, strna(m
->name
),
2084 on_state
, statelen
, strna(m
->state
), off_state
,
2085 on_failed
, failedlen
, m
->n_failed_units
, off_failed
,
2086 jobslen
, m
->n_jobs
);
2089 if (!arg_no_legend
) {
2091 if (state_missing
&& geteuid() != 0)
2092 printf("Notice: some information only available to privileged users was not shown.\n");
2093 printf("%u machines listed.\n", n
);
2097 static int list_machines(int argc
, char *argv
[], void *userdata
) {
2098 struct machine_info
*machine_infos
= NULL
;
2102 r
= acquire_bus(BUS_MANAGER
, &bus
);
2106 r
= get_machine_list(bus
, &machine_infos
, strv_skip(argv
, 1));
2110 (void) pager_open(arg_pager_flags
);
2112 typesafe_qsort(machine_infos
, r
, compare_machine_info
);
2113 output_machines_list(machine_infos
, r
);
2114 free_machines_list(machine_infos
, r
);
2119 static int get_default(int argc
, char *argv
[], void *userdata
) {
2120 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2121 _cleanup_free_
char *_path
= NULL
;
2125 if (install_client_side()) {
2126 r
= unit_file_get_default(arg_scope
, arg_root
, &_path
);
2128 return log_error_errno(r
, "Failed to get default target: %m");
2133 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2136 r
= acquire_bus(BUS_MANAGER
, &bus
);
2140 r
= sd_bus_call_method(
2142 "org.freedesktop.systemd1",
2143 "/org/freedesktop/systemd1",
2144 "org.freedesktop.systemd1.Manager",
2150 return log_error_errno(r
, "Failed to get default target: %s", bus_error_message(&error
, r
));
2152 r
= sd_bus_message_read(reply
, "s", &path
);
2154 return bus_log_parse_error(r
);
2158 printf("%s\n", path
);
2163 static int set_default(int argc
, char *argv
[], void *userdata
) {
2164 _cleanup_free_
char *unit
= NULL
;
2165 UnitFileChange
*changes
= NULL
;
2166 size_t n_changes
= 0;
2172 r
= unit_name_mangle_with_suffix(argv
[1], "set-default",
2173 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
2176 return log_error_errno(r
, "Failed to mangle unit name: %m");
2178 if (install_client_side()) {
2179 r
= unit_file_set_default(arg_scope
, UNIT_FILE_FORCE
, arg_root
, unit
, &changes
, &n_changes
);
2180 unit_file_dump_changes(r
, "set default", changes
, n_changes
, arg_quiet
);
2185 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2186 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2189 polkit_agent_open_maybe();
2191 r
= acquire_bus(BUS_MANAGER
, &bus
);
2195 r
= sd_bus_call_method(
2197 "org.freedesktop.systemd1",
2198 "/org/freedesktop/systemd1",
2199 "org.freedesktop.systemd1.Manager",
2205 return log_error_errno(r
, "Failed to set default target: %s", bus_error_message(&error
, r
));
2207 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
2211 /* Try to reload if enabled */
2213 r
= daemon_reload(argc
, argv
, userdata
);
2219 unit_file_changes_free(changes
, n_changes
);
2224 static int output_waiting_jobs(sd_bus
*bus
, uint32_t id
, const char *method
, const char *prefix
) {
2225 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2226 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2227 const char *name
, *type
;
2233 r
= sd_bus_call_method(
2235 "org.freedesktop.systemd1",
2236 "/org/freedesktop/systemd1",
2237 "org.freedesktop.systemd1.Manager",
2243 return log_debug_errno(r
, "Failed to get waiting jobs for job %" PRIu32
, id
);
2245 r
= sd_bus_message_enter_container(reply
, 'a', "(usssoo)");
2247 return bus_log_parse_error(r
);
2249 while ((r
= sd_bus_message_read(reply
, "(usssoo)", &other_id
, &name
, &type
, NULL
, NULL
, NULL
)) > 0)
2250 printf("%s %u (%s/%s)\n", prefix
, other_id
, name
, type
);
2252 return bus_log_parse_error(r
);
2254 r
= sd_bus_message_exit_container(reply
);
2256 return bus_log_parse_error(r
);
2263 const char *name
, *type
, *state
;
2266 static void output_jobs_list(sd_bus
*bus
, const struct job_info
* jobs
, unsigned n
, bool skipped
) {
2267 unsigned id_len
, unit_len
, type_len
, state_len
;
2268 const struct job_info
*j
;
2269 const char *on
, *off
;
2270 bool shorten
= false;
2272 assert(n
== 0 || jobs
);
2275 if (!arg_no_legend
) {
2276 on
= ansi_highlight_green();
2277 off
= ansi_normal();
2279 printf("%sNo jobs %s.%s\n", on
, skipped
? "listed" : "running", off
);
2284 (void) pager_open(arg_pager_flags
);
2286 id_len
= STRLEN("JOB");
2287 unit_len
= STRLEN("UNIT");
2288 type_len
= STRLEN("TYPE");
2289 state_len
= STRLEN("STATE");
2291 for (j
= jobs
; j
< jobs
+ n
; j
++) {
2292 uint32_t id
= j
->id
;
2293 assert(j
->name
&& j
->type
&& j
->state
);
2295 id_len
= MAX(id_len
, DECIMAL_STR_WIDTH(id
));
2296 unit_len
= MAX(unit_len
, strlen(j
->name
));
2297 type_len
= MAX(type_len
, strlen(j
->type
));
2298 state_len
= MAX(state_len
, strlen(j
->state
));
2301 if (!arg_full
&& id_len
+ 1 + unit_len
+ type_len
+ 1 + state_len
> columns()) {
2302 unit_len
= MAX(33u, columns() - id_len
- type_len
- state_len
- 3);
2307 printf("%*s %-*s %-*s %-*s\n",
2311 state_len
, "STATE");
2313 for (j
= jobs
; j
< jobs
+ n
; j
++) {
2314 _cleanup_free_
char *e
= NULL
;
2316 if (streq(j
->state
, "running")) {
2317 on
= ansi_highlight();
2318 off
= ansi_normal();
2322 e
= shorten
? ellipsize(j
->name
, unit_len
, 33) : NULL
;
2323 printf("%*u %s%-*s%s %-*s %s%-*s%s\n",
2325 on
, unit_len
, e
? e
: j
->name
, off
,
2327 on
, state_len
, j
->state
, off
);
2330 output_waiting_jobs(bus
, j
->id
, "GetJobAfter", "\twaiting for job");
2331 if (arg_jobs_before
)
2332 output_waiting_jobs(bus
, j
->id
, "GetJobBefore", "\tblocking job");
2335 if (!arg_no_legend
) {
2336 on
= ansi_highlight();
2337 off
= ansi_normal();
2339 printf("\n%s%u jobs listed%s.\n", on
, n
, off
);
2343 static bool output_show_job(struct job_info
*job
, char **patterns
) {
2344 return strv_fnmatch_or_empty(patterns
, job
->name
, FNM_NOESCAPE
);
2347 static int list_jobs(int argc
, char *argv
[], void *userdata
) {
2348 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2349 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2350 _cleanup_free_
struct job_info
*jobs
= NULL
;
2351 const char *name
, *type
, *state
;
2352 bool skipped
= false;
2359 r
= acquire_bus(BUS_MANAGER
, &bus
);
2363 r
= sd_bus_call_method(
2365 "org.freedesktop.systemd1",
2366 "/org/freedesktop/systemd1",
2367 "org.freedesktop.systemd1.Manager",
2373 return log_error_errno(r
, "Failed to list jobs: %s", bus_error_message(&error
, r
));
2375 r
= sd_bus_message_enter_container(reply
, 'a', "(usssoo)");
2377 return bus_log_parse_error(r
);
2379 while ((r
= sd_bus_message_read(reply
, "(usssoo)", &id
, &name
, &type
, &state
, NULL
, NULL
)) > 0) {
2380 struct job_info job
= { id
, name
, type
, state
};
2382 if (!output_show_job(&job
, strv_skip(argv
, 1))) {
2387 if (!GREEDY_REALLOC(jobs
, size
, c
+ 1))
2393 return bus_log_parse_error(r
);
2395 r
= sd_bus_message_exit_container(reply
);
2397 return bus_log_parse_error(r
);
2399 (void) pager_open(arg_pager_flags
);
2401 output_jobs_list(bus
, jobs
, c
, skipped
);
2405 static int cancel_job(int argc
, char *argv
[], void *userdata
) {
2411 return trivial_method(argc
, argv
, userdata
);
2413 r
= acquire_bus(BUS_MANAGER
, &bus
);
2417 polkit_agent_open_maybe();
2419 STRV_FOREACH(name
, strv_skip(argv
, 1)) {
2420 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2424 q
= safe_atou32(*name
, &id
);
2426 return log_error_errno(q
, "Failed to parse job id \"%s\": %m", *name
);
2428 q
= sd_bus_call_method(
2430 "org.freedesktop.systemd1",
2431 "/org/freedesktop/systemd1",
2432 "org.freedesktop.systemd1.Manager",
2438 log_error_errno(q
, "Failed to cancel job %"PRIu32
": %s", id
, bus_error_message(&error
, q
));
2447 static int need_daemon_reload(sd_bus
*bus
, const char *unit
) {
2448 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2452 /* We ignore all errors here, since this is used to show a
2455 /* We don't use unit_dbus_path_from_name() directly since we
2456 * don't want to load the unit if it isn't loaded. */
2458 r
= sd_bus_call_method(
2460 "org.freedesktop.systemd1",
2461 "/org/freedesktop/systemd1",
2462 "org.freedesktop.systemd1.Manager",
2470 r
= sd_bus_message_read(reply
, "o", &path
);
2474 r
= sd_bus_get_property_trivial(
2476 "org.freedesktop.systemd1",
2478 "org.freedesktop.systemd1.Unit",
2488 static void warn_unit_file_changed(const char *name
) {
2491 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.",
2492 ansi_highlight_red(),
2495 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user");
2498 static int unit_file_find_path(LookupPaths
*lp
, const char *unit_name
, char **ret_unit_path
) {
2504 STRV_FOREACH(p
, lp
->search_path
) {
2505 _cleanup_free_
char *path
= NULL
, *lpath
= NULL
;
2508 path
= path_join(*p
, unit_name
);
2512 r
= chase_symlinks(path
, arg_root
, 0, &lpath
, NULL
);
2518 return log_error_errno(r
, "Failed to access path \"%s\": %m", path
);
2521 *ret_unit_path
= TAKE_PTR(lpath
);
2527 *ret_unit_path
= NULL
;
2532 static int unit_find_template_path(
2533 const char *unit_name
,
2535 char **ret_fragment_path
,
2536 char **ret_template
) {
2538 _cleanup_free_
char *t
= NULL
, *f
= NULL
;
2541 /* Returns 1 if a fragment was found, 0 if not found, negative on error. */
2543 r
= unit_file_find_path(lp
, unit_name
, &f
);
2547 if (ret_fragment_path
)
2548 *ret_fragment_path
= TAKE_PTR(f
);
2550 *ret_template
= NULL
;
2551 return r
; /* found a real unit */
2554 r
= unit_name_template(unit_name
, &t
);
2556 if (ret_fragment_path
)
2557 *ret_fragment_path
= NULL
;
2559 *ret_template
= NULL
;
2561 return 0; /* not a template, does not exist */
2564 return log_error_errno(r
, "Failed to determine template name: %m");
2566 r
= unit_file_find_path(lp
, t
, ret_fragment_path
);
2571 *ret_template
= r
> 0 ? TAKE_PTR(t
) : NULL
;
2576 static int unit_find_paths(
2578 const char *unit_name
,
2580 bool force_client_side
,
2581 char **ret_fragment_path
,
2582 char ***ret_dropin_paths
) {
2584 _cleanup_strv_free_
char **dropins
= NULL
;
2585 _cleanup_free_
char *path
= NULL
;
2589 * Finds where the unit is defined on disk. Returns 0 if the unit is not found. Returns 1 if it is
2591 * - the path to the unit in *ret_frament_path, if it exists on disk,
2592 * - and a strv of existing drop-ins in *ret_dropin_paths, if the arg is not NULL and any dropins
2595 * Returns -ERFKILL if the unit is masked, and -EKEYREJECTED if the unit file could not be loaded for
2596 * some reason (the latter only applies if we are going through the service manager).
2600 assert(ret_fragment_path
);
2603 /* Go via the bus to acquire the path, unless we are explicitly told not to, or when the unit name is a template */
2604 if (!force_client_side
&&
2605 !install_client_side() &&
2606 !unit_name_is_valid(unit_name
, UNIT_NAME_TEMPLATE
)) {
2607 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2608 _cleanup_free_
char *load_state
= NULL
, *dbus_path
= NULL
;
2610 dbus_path
= unit_dbus_path_from_name(unit_name
);
2614 r
= sd_bus_get_property_string(
2616 "org.freedesktop.systemd1",
2618 "org.freedesktop.systemd1.Unit",
2623 return log_error_errno(r
, "Failed to get LoadState: %s", bus_error_message(&error
, r
));
2625 if (streq(load_state
, "masked"))
2627 if (streq(load_state
, "not-found")) {
2631 if (!STR_IN_SET(load_state
, "loaded", "bad-setting"))
2632 return -EKEYREJECTED
;
2634 r
= sd_bus_get_property_string(
2636 "org.freedesktop.systemd1",
2638 "org.freedesktop.systemd1.Unit",
2643 return log_error_errno(r
, "Failed to get FragmentPath: %s", bus_error_message(&error
, r
));
2645 if (ret_dropin_paths
) {
2646 r
= sd_bus_get_property_strv(
2648 "org.freedesktop.systemd1",
2650 "org.freedesktop.systemd1.Unit",
2655 return log_error_errno(r
, "Failed to get DropInPaths: %s", bus_error_message(&error
, r
));
2659 _cleanup_set_free_free_ Set
*names
= NULL
;
2661 if (!cached_name_map
) {
2662 r
= unit_file_build_name_map(lp
, NULL
, &cached_id_map
, &cached_name_map
, NULL
);
2667 r
= unit_file_find_fragment(cached_id_map
, cached_name_map
, unit_name
, &_path
, &names
);
2672 path
= strdup(_path
);
2677 if (ret_dropin_paths
) {
2678 r
= unit_file_find_dropin_paths(arg_root
, lp
->search_path
, NULL
,
2686 if (isempty(path
)) {
2687 *ret_fragment_path
= NULL
;
2690 *ret_fragment_path
= TAKE_PTR(path
);
2694 if (ret_dropin_paths
) {
2695 if (!strv_isempty(dropins
)) {
2696 *ret_dropin_paths
= TAKE_PTR(dropins
);
2699 *ret_dropin_paths
= NULL
;
2703 if (r
== 0 && !arg_force
)
2704 log_error("No files found for %s.", unit_name
);
2709 static int get_state_one_unit(sd_bus
*bus
, const char *name
, UnitActiveState
*active_state
) {
2710 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2711 _cleanup_free_
char *buf
= NULL
, *dbus_path
= NULL
;
2712 UnitActiveState state
;
2716 assert(active_state
);
2718 dbus_path
= unit_dbus_path_from_name(name
);
2722 r
= sd_bus_get_property_string(
2724 "org.freedesktop.systemd1",
2726 "org.freedesktop.systemd1.Unit",
2731 return log_error_errno(r
, "Failed to retrieve unit state: %s", bus_error_message(&error
, r
));
2733 state
= unit_active_state_from_string(buf
);
2735 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid unit state '%s' for: %s", buf
, name
);
2737 *active_state
= state
;
2741 static int unit_is_masked(sd_bus
*bus
, LookupPaths
*lp
, const char *name
) {
2742 _cleanup_free_
char *load_state
= NULL
;
2745 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
2746 _cleanup_free_
char *path
= NULL
;
2748 /* A template cannot be loaded, but it can be still masked, so
2749 * we need to use a different method. */
2751 r
= unit_file_find_path(lp
, name
, &path
);
2756 return null_or_empty_path(path
);
2759 r
= unit_load_state(bus
, name
, &load_state
);
2763 return streq(load_state
, "masked");
2766 static int check_triggering_units(sd_bus
*bus
, const char *name
) {
2767 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2768 _cleanup_free_
char *n
= NULL
, *dbus_path
= NULL
, *load_state
= NULL
;
2769 _cleanup_strv_free_
char **triggered_by
= NULL
;
2770 bool print_warning_label
= true;
2771 UnitActiveState active_state
;
2775 r
= unit_name_mangle(name
, 0, &n
);
2777 return log_error_errno(r
, "Failed to mangle unit name: %m");
2779 r
= unit_load_state(bus
, name
, &load_state
);
2783 if (streq(load_state
, "masked"))
2786 dbus_path
= unit_dbus_path_from_name(n
);
2790 r
= sd_bus_get_property_strv(
2792 "org.freedesktop.systemd1",
2794 "org.freedesktop.systemd1.Unit",
2799 return log_error_errno(r
, "Failed to get triggered by array of %s: %s", n
, bus_error_message(&error
, r
));
2801 STRV_FOREACH(i
, triggered_by
) {
2802 r
= get_state_one_unit(bus
, *i
, &active_state
);
2806 if (!IN_SET(active_state
, UNIT_ACTIVE
, UNIT_RELOADING
))
2809 if (print_warning_label
) {
2810 log_warning("Warning: Stopping %s, but it can still be activated by:", n
);
2811 print_warning_label
= false;
2814 log_warning(" %s", *i
);
2820 static const struct {
2821 const char *verb
; /* systemctl verb */
2822 const char *method
; /* Name of the specific D-Bus method */
2823 const char *job_type
; /* Job type when passing to the generic EnqueueUnitJob() method */
2824 } unit_actions
[] = {
2825 { "start", "StartUnit", "start" },
2826 { "stop", "StopUnit", "stop" },
2827 { "condstop", "StopUnit", "stop" }, /* legacy alias */
2828 { "reload", "ReloadUnit", "reload" },
2829 { "restart", "RestartUnit", "restart" },
2830 { "try-restart", "TryRestartUnit", "try-restart" },
2831 { "condrestart", "TryRestartUnit", "try-restart" }, /* legacy alias */
2832 { "reload-or-restart", "ReloadOrRestartUnit", "reload-or-restart" },
2833 { "try-reload-or-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" },
2834 { "reload-or-try-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2835 { "condreload", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2836 { "force-reload", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2839 static const char *verb_to_method(const char *verb
) {
2842 for (i
= 0; i
< ELEMENTSOF(unit_actions
); i
++)
2843 if (streq_ptr(unit_actions
[i
].verb
, verb
))
2844 return unit_actions
[i
].method
;
2849 static const char *verb_to_job_type(const char *verb
) {
2852 for (i
= 0; i
< ELEMENTSOF(unit_actions
); i
++)
2853 if (streq_ptr(unit_actions
[i
].verb
, verb
))
2854 return unit_actions
[i
].job_type
;
2859 static int start_unit_one(
2861 const char *method
, /* When using classic per-job bus methods */
2862 const char *job_type
, /* When using new-style EnqueueUnitJob() */
2865 sd_bus_error
*error
,
2867 BusWaitForUnits
*wu
) {
2869 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2879 log_debug("%s dbus call org.freedesktop.systemd1.Manager %s(%s, %s)",
2880 arg_dry_run
? "Would execute" : "Executing",
2881 method
, name
, mode
);
2886 if (arg_show_transaction
) {
2887 _cleanup_(sd_bus_error_free
) sd_bus_error enqueue_error
= SD_BUS_ERROR_NULL
;
2889 /* Use the new, fancy EnqueueUnitJob() API if the user wants us to print the transaction */
2890 r
= sd_bus_call_method(
2892 "org.freedesktop.systemd1",
2893 "/org/freedesktop/systemd1",
2894 "org.freedesktop.systemd1.Manager",
2899 name
, job_type
, mode
);
2901 if (!sd_bus_error_has_name(&enqueue_error
, SD_BUS_ERROR_UNKNOWN_METHOD
)) {
2902 (void) sd_bus_error_move(error
, &enqueue_error
);
2906 /* Hmm, the API is not yet available. Let's use the classic API instead (see below). */
2907 log_notice("--show-transaction not supported by this service manager, proceeding without.");
2912 r
= sd_bus_message_read(reply
, "uosos", &id
, &path
, &u
, NULL
, &jt
);
2914 return bus_log_parse_error(r
);
2916 log_info("Enqueued anchor job %" PRIu32
" %s/%s.", id
, u
, jt
);
2918 r
= sd_bus_message_enter_container(reply
, 'a', "(uosos)");
2920 return bus_log_parse_error(r
);
2922 r
= sd_bus_message_read(reply
, "(uosos)", &id
, NULL
, &u
, NULL
, &jt
);
2924 return bus_log_parse_error(r
);
2928 log_info("Enqueued auxiliary job %" PRIu32
" %s/%s.", id
, u
, jt
);
2931 r
= sd_bus_message_exit_container(reply
);
2933 return bus_log_parse_error(r
);
2940 r
= sd_bus_call_method(
2942 "org.freedesktop.systemd1",
2943 "/org/freedesktop/systemd1",
2944 "org.freedesktop.systemd1.Manager",
2952 r
= sd_bus_message_read(reply
, "o", &path
);
2954 return bus_log_parse_error(r
);
2957 if (need_daemon_reload(bus
, name
) > 0)
2958 warn_unit_file_changed(name
);
2961 log_debug("Adding %s to the set", path
);
2962 r
= bus_wait_for_jobs_add(w
, path
);
2964 return log_error_errno(r
, "Failed to watch job for %s: %m", name
);
2968 r
= bus_wait_for_units_add_unit(wu
, name
, BUS_WAIT_FOR_INACTIVE
|BUS_WAIT_NO_JOB
, NULL
, NULL
);
2970 return log_error_errno(r
, "Failed to watch unit %s: %m", name
);
2976 /* There's always a fallback possible for legacy actions. */
2977 if (arg_action
!= ACTION_SYSTEMCTL
)
2980 log_error_errno(r
, "Failed to %s %s: %s", job_type
, name
, bus_error_message(error
, r
));
2982 if (!sd_bus_error_has_name(error
, BUS_ERROR_NO_SUCH_UNIT
) &&
2983 !sd_bus_error_has_name(error
, BUS_ERROR_UNIT_MASKED
) &&
2984 !sd_bus_error_has_name(error
, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE
))
2985 log_error("See %s logs and 'systemctl%s status%s %s' for details.",
2986 arg_scope
== UNIT_FILE_SYSTEM
? "system" : "user",
2987 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user",
2988 name
[0] == '-' ? " --" : "",
2994 static const struct {
2998 } action_table
[_ACTION_MAX
] = {
2999 [ACTION_HALT
] = { SPECIAL_HALT_TARGET
, "halt", "replace-irreversibly" },
3000 [ACTION_POWEROFF
] = { SPECIAL_POWEROFF_TARGET
, "poweroff", "replace-irreversibly" },
3001 [ACTION_REBOOT
] = { SPECIAL_REBOOT_TARGET
, "reboot", "replace-irreversibly" },
3002 [ACTION_KEXEC
] = { SPECIAL_KEXEC_TARGET
, "kexec", "replace-irreversibly" },
3003 [ACTION_RUNLEVEL2
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
3004 [ACTION_RUNLEVEL3
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
3005 [ACTION_RUNLEVEL4
] = { SPECIAL_MULTI_USER_TARGET
, NULL
, "isolate" },
3006 [ACTION_RUNLEVEL5
] = { SPECIAL_GRAPHICAL_TARGET
, NULL
, "isolate" },
3007 [ACTION_RESCUE
] = { SPECIAL_RESCUE_TARGET
, "rescue", "isolate" },
3008 [ACTION_EMERGENCY
] = { SPECIAL_EMERGENCY_TARGET
, "emergency", "isolate" },
3009 [ACTION_DEFAULT
] = { SPECIAL_DEFAULT_TARGET
, "default", "isolate" },
3010 [ACTION_EXIT
] = { SPECIAL_EXIT_TARGET
, "exit", "replace-irreversibly" },
3011 [ACTION_SUSPEND
] = { SPECIAL_SUSPEND_TARGET
, "suspend", "replace-irreversibly" },
3012 [ACTION_HIBERNATE
] = { SPECIAL_HIBERNATE_TARGET
, "hibernate", "replace-irreversibly" },
3013 [ACTION_HYBRID_SLEEP
] = { SPECIAL_HYBRID_SLEEP_TARGET
, "hybrid-sleep", "replace-irreversibly" },
3014 [ACTION_SUSPEND_THEN_HIBERNATE
] = { SPECIAL_SUSPEND_THEN_HIBERNATE_TARGET
, "suspend-then-hibernate", "replace-irreversibly" },
3017 static enum action
verb_to_action(const char *verb
) {
3020 for (i
= 0; i
< _ACTION_MAX
; i
++)
3021 if (streq_ptr(action_table
[i
].verb
, verb
))
3024 return _ACTION_INVALID
;
3027 static const char** make_extra_args(const char *extra_args
[static 4]) {
3032 if (arg_scope
!= UNIT_FILE_SYSTEM
)
3033 extra_args
[n
++] = "--user";
3035 if (arg_transport
== BUS_TRANSPORT_REMOTE
) {
3036 extra_args
[n
++] = "-H";
3037 extra_args
[n
++] = arg_host
;
3038 } else if (arg_transport
== BUS_TRANSPORT_MACHINE
) {
3039 extra_args
[n
++] = "-M";
3040 extra_args
[n
++] = arg_host
;
3042 assert(arg_transport
== BUS_TRANSPORT_LOCAL
);
3044 extra_args
[n
] = NULL
;
3048 static int start_unit(int argc
, char *argv
[], void *userdata
) {
3049 _cleanup_(bus_wait_for_units_freep
) BusWaitForUnits
*wu
= NULL
;
3050 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
3051 const char *method
, *job_type
, *mode
, *one_name
, *suffix
= NULL
;
3052 _cleanup_free_
char **stopped_units
= NULL
; /* Do not use _cleanup_strv_free_ */
3053 _cleanup_strv_free_
char **names
= NULL
;
3054 int r
, ret
= EXIT_SUCCESS
;
3058 if (arg_wait
&& !STR_IN_SET(argv
[0], "start", "restart"))
3059 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3060 "--wait may only be used with the 'start' or 'restart' commands.");
3062 /* we cannot do sender tracking on the private bus, so we need the full
3063 * one for RefUnit to implement --wait */
3064 r
= acquire_bus(arg_wait
? BUS_FULL
: BUS_MANAGER
, &bus
);
3068 ask_password_agent_open_maybe();
3069 polkit_agent_open_maybe();
3071 if (arg_action
== ACTION_SYSTEMCTL
) {
3074 action
= verb_to_action(argv
[0]);
3076 if (action
!= _ACTION_INVALID
) {
3077 /* A command in style "systemctl reboot", "systemctl poweroff", … */
3078 method
= "StartUnit";
3080 mode
= action_table
[action
].mode
;
3081 one_name
= action_table
[action
].target
;
3083 if (streq(argv
[0], "isolate")) {
3084 /* A "systemctl isolate <unit1> <unit2> …" command */
3085 method
= "StartUnit";
3090 /* A command in style of "systemctl start <unit1> <unit2> …", "sysemctl stop <unit1> <unit2> …" and so on */
3091 method
= verb_to_method(argv
[0]);
3092 job_type
= verb_to_job_type(argv
[0]);
3093 mode
= arg_job_mode
;
3098 /* A SysV legacy command such as "halt", "reboot", "poweroff", … */
3099 assert(arg_action
>= 0 && arg_action
< _ACTION_MAX
);
3100 assert(action_table
[arg_action
].target
);
3101 assert(action_table
[arg_action
].mode
);
3103 method
= "StartUnit";
3105 mode
= action_table
[arg_action
].mode
;
3106 one_name
= action_table
[arg_action
].target
;
3110 names
= strv_new(one_name
);
3116 r
= expand_names(bus
, strv_skip(argv
, 1), suffix
, &names
, &expanded
);
3118 return log_error_errno(r
, "Failed to expand names: %m");
3120 if (!arg_all
&& expanded
&& streq(job_type
, "start") && !arg_quiet
) {
3121 log_warning("Warning: %ssystemctl start called with a glob pattern.%s",
3122 ansi_highlight_red(),
3124 log_notice("Hint: unit globs expand to loaded units, so start will usually have no effect.\n"
3125 " Passing --all will also load units which are pulled in by other units.\n"
3126 " See systemctl(1) for more details.");
3130 if (!arg_no_block
) {
3131 r
= bus_wait_for_jobs_new(bus
, &w
);
3133 return log_error_errno(r
, "Could not watch jobs: %m");
3137 r
= sd_bus_call_method_async(
3140 "org.freedesktop.systemd1",
3141 "/org/freedesktop/systemd1",
3142 "org.freedesktop.systemd1.Manager",
3147 return log_error_errno(r
, "Failed to enable subscription: %m");
3149 r
= bus_wait_for_units_new(bus
, &wu
);
3151 return log_error_errno(r
, "Failed to allocate unit watch context: %m");
3154 STRV_FOREACH(name
, names
) {
3155 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3157 r
= start_unit_one(bus
, method
, job_type
, *name
, mode
, &error
, w
, wu
);
3158 if (ret
== EXIT_SUCCESS
&& r
< 0)
3159 ret
= translate_bus_error_to_exit_status(r
, &error
);
3161 if (r
>= 0 && streq(method
, "StopUnit")) {
3162 r
= strv_push(&stopped_units
, *name
);
3168 if (!arg_no_block
) {
3169 const char* extra_args
[4];
3171 r
= bus_wait_for_jobs(w
, arg_quiet
, make_extra_args(extra_args
));
3175 /* When stopping units, warn if they can still be triggered by
3176 * another active unit (socket, path, timer) */
3178 STRV_FOREACH(name
, stopped_units
)
3179 (void) check_triggering_units(bus
, *name
);
3183 r
= bus_wait_for_units_run(wu
);
3185 return log_error_errno(r
, "Failed to wait for units: %m");
3186 if (r
== BUS_WAIT_FAILURE
&& ret
== EXIT_SUCCESS
)
3194 static int logind_set_wall_message(void) {
3195 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3197 _cleanup_free_
char *m
= NULL
;
3200 r
= acquire_bus(BUS_FULL
, &bus
);
3204 m
= strv_join(arg_wall
, " ");
3208 log_debug("%s wall message \"%s\".", arg_dry_run
? "Would set" : "Setting", m
);
3212 r
= sd_bus_call_method(
3214 "org.freedesktop.login1",
3215 "/org/freedesktop/login1",
3216 "org.freedesktop.login1.Manager",
3225 return log_warning_errno(r
, "Failed to set wall message, ignoring: %s", bus_error_message(&error
, r
));
3230 /* Ask systemd-logind, which might grant access to unprivileged users through polkit */
3231 static int logind_reboot(enum action a
) {
3233 static const struct {
3235 const char *description
;
3236 } actions
[_ACTION_MAX
] = {
3237 [ACTION_POWEROFF
] = { "PowerOff", "power off system" },
3238 [ACTION_REBOOT
] = { "Reboot", "reboot system" },
3239 [ACTION_HALT
] = { "Halt", "halt system" },
3240 [ACTION_SUSPEND
] = { "Suspend", "suspend system" },
3241 [ACTION_HIBERNATE
] = { "Hibernate", "hibernate system" },
3242 [ACTION_HYBRID_SLEEP
] = { "HybridSleep", "put system into hybrid sleep" },
3243 [ACTION_SUSPEND_THEN_HIBERNATE
] = { "SuspendThenHibernate", "suspend system, hibernate later" },
3246 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3250 if (a
< 0 || a
>= _ACTION_MAX
|| !actions
[a
].method
)
3253 r
= acquire_bus(BUS_FULL
, &bus
);
3257 polkit_agent_open_maybe();
3258 (void) logind_set_wall_message();
3260 log_debug("%s org.freedesktop.login1.Manager %s dbus call.", arg_dry_run
? "Would execute" : "Executing", actions
[a
].method
);
3265 r
= sd_bus_call_method(
3267 "org.freedesktop.login1",
3268 "/org/freedesktop/login1",
3269 "org.freedesktop.login1.Manager",
3273 "b", arg_ask_password
);
3275 return log_error_errno(r
, "Failed to %s via logind: %s", actions
[a
].description
, bus_error_message(&error
, r
));
3283 static int logind_check_inhibitors(enum action a
) {
3285 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
3286 _cleanup_strv_free_
char **sessions
= NULL
;
3287 const char *what
, *who
, *why
, *mode
;
3294 if (arg_ignore_inhibitors
|| arg_force
> 0)
3306 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
3309 r
= acquire_bus(BUS_FULL
, &bus
);
3313 r
= sd_bus_call_method(
3315 "org.freedesktop.login1",
3316 "/org/freedesktop/login1",
3317 "org.freedesktop.login1.Manager",
3323 /* If logind is not around, then there are no inhibitors... */
3326 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssuu)");
3328 return bus_log_parse_error(r
);
3330 while ((r
= sd_bus_message_read(reply
, "(ssssuu)", &what
, &who
, &why
, &mode
, &uid
, &pid
)) > 0) {
3331 _cleanup_free_
char *comm
= NULL
, *user
= NULL
;
3332 _cleanup_strv_free_
char **sv
= NULL
;
3334 if (!streq(mode
, "block"))
3337 sv
= strv_split(what
, ":");
3341 if (!pid_is_valid((pid_t
) pid
))
3342 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Invalid PID "PID_FMT
".", (pid_t
) pid
);
3344 if (!strv_contains(sv
,
3349 ACTION_KEXEC
) ? "shutdown" : "sleep"))
3352 get_process_comm(pid
, &comm
);
3353 user
= uid_to_name(uid
);
3355 log_warning("Operation inhibited by \"%s\" (PID "PID_FMT
" \"%s\", user %s), reason is \"%s\".",
3356 who
, (pid_t
) pid
, strna(comm
), strna(user
), why
);
3361 return bus_log_parse_error(r
);
3363 r
= sd_bus_message_exit_container(reply
);
3365 return bus_log_parse_error(r
);
3367 /* Check for current sessions */
3368 sd_get_sessions(&sessions
);
3369 STRV_FOREACH(s
, sessions
) {
3370 _cleanup_free_
char *type
= NULL
, *tty
= NULL
, *seat
= NULL
, *user
= NULL
, *service
= NULL
, *class = NULL
;
3372 if (sd_session_get_uid(*s
, &uid
) < 0 || uid
== getuid())
3375 if (sd_session_get_class(*s
, &class) < 0 || !streq(class, "user"))
3378 if (sd_session_get_type(*s
, &type
) < 0 || !STR_IN_SET(type
, "x11", "wayland", "tty", "mir"))
3381 sd_session_get_tty(*s
, &tty
);
3382 sd_session_get_seat(*s
, &seat
);
3383 sd_session_get_service(*s
, &service
);
3384 user
= uid_to_name(uid
);
3386 log_warning("User %s is logged in on %s.", strna(user
), isempty(tty
) ? (isempty(seat
) ? strna(service
) : seat
) : tty
);
3393 log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'systemctl %s -i'.",
3394 action_table
[a
].verb
);
3402 static int prepare_firmware_setup(void) {
3404 if (!arg_firmware_setup
)
3408 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3412 r
= acquire_bus(BUS_FULL
, &bus
);
3416 r
= sd_bus_call_method(
3418 "org.freedesktop.login1",
3419 "/org/freedesktop/login1",
3420 "org.freedesktop.login1.Manager",
3421 "SetRebootToFirmwareSetup",
3426 return log_error_errno(r
, "Cannot indicate to EFI to boot into setup mode: %s", bus_error_message(&error
, r
));
3430 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3431 "Booting into firmware setup not supported.");
3435 static int prepare_boot_loader_menu(void) {
3437 if (arg_boot_loader_menu
== USEC_INFINITY
)
3441 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3445 r
= acquire_bus(BUS_FULL
, &bus
);
3449 r
= sd_bus_call_method(
3451 "org.freedesktop.login1",
3452 "/org/freedesktop/login1",
3453 "org.freedesktop.login1.Manager",
3454 "SetRebootToBootLoaderMenu",
3457 "t", arg_boot_loader_menu
);
3459 return log_error_errno(r
, "Cannot indicate to boot loader to enter boot loader entry menu: %s", bus_error_message(&error
, r
));
3463 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3464 "Booting into boot loader menu not supported.");
3468 static int prepare_boot_loader_entry(void) {
3470 if (!arg_boot_loader_entry
)
3474 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3478 r
= acquire_bus(BUS_FULL
, &bus
);
3482 r
= sd_bus_call_method(
3484 "org.freedesktop.login1",
3485 "/org/freedesktop/login1",
3486 "org.freedesktop.login1.Manager",
3487 "SetRebootToBootLoaderEntry",
3490 "s", arg_boot_loader_entry
);
3492 return log_error_errno(r
, "Cannot set boot into loader entry '%s': %s", arg_boot_loader_entry
, bus_error_message(&error
, r
));
3496 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
3497 "Booting into boot loader entry not supported.");
3501 static int load_kexec_kernel(void) {
3502 _cleanup_(boot_config_free
) BootConfig config
= {};
3503 _cleanup_free_
char *kernel
= NULL
, *initrd
= NULL
, *options
= NULL
;
3508 if (kexec_loaded()) {
3509 log_debug("Kexec kernel already loaded.");
3513 if (access(KEXEC
, X_OK
) < 0)
3514 return log_error_errno(errno
, KEXEC
" is not available: %m");
3516 r
= boot_entries_load_config_auto(NULL
, NULL
, &config
);
3517 if (r
== -ENOKEY
) /* The call doesn't log about ENOKEY, let's do so here. */
3518 return log_error_errno(r
, "Cannot find the ESP partition mount point.");
3522 e
= boot_config_default_entry(&config
);
3524 return log_error_errno(SYNTHETIC_ERRNO(ENOENT
),
3525 "No boot loader entry suitable as default, refusing to guess.");
3527 log_debug("Found default boot loader entry in file \"%s\"", e
->path
);
3530 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3531 "Boot entry does not refer to Linux kernel, which is not supported currently.");
3532 if (strv_length(e
->initrd
) > 1)
3533 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3534 "Boot entry specifies multiple initrds, which is not supported currently.");
3536 kernel
= path_join(e
->root
, e
->kernel
);
3540 if (!strv_isempty(e
->initrd
)) {
3541 initrd
= path_join(e
->root
, e
->initrd
[0]);
3546 options
= strv_join(e
->options
, " ");
3550 log_full(arg_quiet
? LOG_DEBUG
: LOG_INFO
,
3551 "%s "KEXEC
" --load \"%s\" --append \"%s\"%s%s%s",
3552 arg_dry_run
? "Would run" : "Running",
3555 initrd
? " --initrd \"" : NULL
, strempty(initrd
), initrd
? "\"" : "");
3559 r
= safe_fork("(kexec)", FORK_WAIT
|FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
, &pid
);
3563 const char* const args
[] = {
3566 "--append", options
,
3567 initrd
? "--initrd" : NULL
, initrd
,
3572 execv(args
[0], (char * const *) args
);
3573 _exit(EXIT_FAILURE
);
3579 static int set_exit_code(uint8_t code
) {
3580 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3584 r
= acquire_bus(BUS_MANAGER
, &bus
);
3588 r
= sd_bus_call_method(
3590 "org.freedesktop.systemd1",
3591 "/org/freedesktop/systemd1",
3592 "org.freedesktop.systemd1.Manager",
3598 return log_error_errno(r
, "Failed to set exit code: %s", bus_error_message(&error
, r
));
3603 static int start_special(int argc
, char *argv
[], void *userdata
) {
3606 bool termination_action
; /* an action that terminates the manager,
3607 * can be performed also by signal. */
3611 a
= verb_to_action(argv
[0]);
3613 r
= logind_check_inhibitors(a
);
3617 if (arg_force
>= 2) {
3623 r
= prepare_firmware_setup();
3627 r
= prepare_boot_loader_menu();
3631 r
= prepare_boot_loader_entry();
3635 if (a
== ACTION_REBOOT
&& argc
> 1) {
3636 r
= update_reboot_parameter_and_warn(argv
[1], false);
3640 } else if (a
== ACTION_KEXEC
) {
3641 r
= load_kexec_kernel();
3642 if (r
< 0 && arg_force
>= 1)
3643 log_notice("Failed to load kexec kernel, continuing without.");
3647 } else if (a
== ACTION_EXIT
&& argc
> 1) {
3650 /* If the exit code is not given on the command line,
3651 * don't reset it to zero: just keep it as it might
3652 * have been set previously. */
3654 r
= safe_atou8(argv
[1], &code
);
3656 return log_error_errno(r
, "Invalid exit code.");
3658 r
= set_exit_code(code
);
3663 termination_action
= IN_SET(a
,
3667 if (termination_action
&& arg_force
>= 2)
3670 if (arg_force
>= 1 &&
3671 (termination_action
|| IN_SET(a
, ACTION_KEXEC
, ACTION_EXIT
)))
3672 r
= trivial_method(argc
, argv
, userdata
);
3674 /* First try logind, to allow authentication with polkit */
3681 ACTION_HYBRID_SLEEP
,
3682 ACTION_SUSPEND_THEN_HIBERNATE
)) {
3684 r
= logind_reboot(a
);
3687 if (IN_SET(r
, -EOPNOTSUPP
, -EINPROGRESS
))
3688 /* requested operation is not supported or already in progress */
3691 /* On all other errors, try low-level operation. In order to minimize the difference between
3692 * operation with and without logind, we explicitly enable non-blocking mode for this, as
3693 * logind's shutdown operations are always non-blocking. */
3695 arg_no_block
= true;
3697 } else if (IN_SET(a
, ACTION_EXIT
, ACTION_KEXEC
))
3698 /* Since exit/kexec are so close in behaviour to power-off/reboot, let's also make them
3699 * asynchronous, in order to not confuse the user needlessly with unexpected behaviour. */
3700 arg_no_block
= true;
3702 r
= start_unit(argc
, argv
, userdata
);
3705 if (termination_action
&& arg_force
< 2 &&
3706 IN_SET(r
, -ENOENT
, -ETIMEDOUT
))
3707 log_notice("It is possible to perform action directly, see discussion of --force --force in man:systemctl(1).");
3712 static int start_system_special(int argc
, char *argv
[], void *userdata
) {
3713 /* Like start_special above, but raises an error when running in user mode */
3715 if (arg_scope
!= UNIT_FILE_SYSTEM
)
3716 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3717 "Bad action for %s mode.",
3718 arg_scope
== UNIT_FILE_GLOBAL
? "--global" : "--user");
3720 return start_special(argc
, argv
, userdata
);
3723 static int check_unit_generic(int code
, const UnitActiveState good_states
[], int nb_states
, char **args
) {
3724 _cleanup_strv_free_
char **names
= NULL
;
3725 UnitActiveState active_state
;
3731 r
= acquire_bus(BUS_MANAGER
, &bus
);
3735 r
= expand_names(bus
, args
, NULL
, &names
, NULL
);
3737 return log_error_errno(r
, "Failed to expand names: %m");
3739 STRV_FOREACH(name
, names
) {
3740 r
= get_state_one_unit(bus
, *name
, &active_state
);
3745 puts(unit_active_state_to_string(active_state
));
3747 for (i
= 0; i
< nb_states
; ++i
)
3748 if (good_states
[i
] == active_state
)
3752 /* use the given return code for the case that we won't find
3753 * any unit which matches the list */
3754 return found
? 0 : code
;
3757 static int check_unit_active(int argc
, char *argv
[], void *userdata
) {
3758 static const UnitActiveState states
[] = {
3763 /* According to LSB: 3, "program is not running" */
3764 return check_unit_generic(EXIT_PROGRAM_NOT_RUNNING
, states
, ELEMENTSOF(states
), strv_skip(argv
, 1));
3767 static int check_unit_failed(int argc
, char *argv
[], void *userdata
) {
3768 static const UnitActiveState states
[] = {
3772 return check_unit_generic(EXIT_PROGRAM_DEAD_AND_PID_EXISTS
, states
, ELEMENTSOF(states
), strv_skip(argv
, 1));
3775 static int kill_unit(int argc
, char *argv
[], void *userdata
) {
3776 _cleanup_strv_free_
char **names
= NULL
;
3777 char *kill_who
= NULL
, **name
;
3781 r
= acquire_bus(BUS_MANAGER
, &bus
);
3785 polkit_agent_open_maybe();
3788 arg_kill_who
= "all";
3790 /* --fail was specified */
3791 if (streq(arg_job_mode
, "fail"))
3792 kill_who
= strjoina(arg_kill_who
, "-fail");
3794 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
3796 return log_error_errno(r
, "Failed to expand names: %m");
3798 STRV_FOREACH(name
, names
) {
3799 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3801 q
= sd_bus_call_method(
3803 "org.freedesktop.systemd1",
3804 "/org/freedesktop/systemd1",
3805 "org.freedesktop.systemd1.Manager",
3809 "ssi", *name
, kill_who
? kill_who
: arg_kill_who
, arg_signal
);
3811 log_error_errno(q
, "Failed to kill unit %s: %s", *name
, bus_error_message(&error
, q
));
3820 static int clean_unit(int argc
, char *argv
[], void *userdata
) {
3821 _cleanup_(bus_wait_for_units_freep
) BusWaitForUnits
*w
= NULL
;
3822 _cleanup_strv_free_
char **names
= NULL
;
3823 int r
, ret
= EXIT_SUCCESS
;
3827 r
= acquire_bus(BUS_FULL
, &bus
);
3831 polkit_agent_open_maybe();
3833 if (!arg_clean_what
) {
3834 arg_clean_what
= strv_new("cache", "runtime");
3835 if (!arg_clean_what
)
3839 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
3841 return log_error_errno(r
, "Failed to expand names: %m");
3843 if (!arg_no_block
) {
3844 r
= bus_wait_for_units_new(bus
, &w
);
3846 return log_error_errno(r
, "Failed to allocate unit waiter: %m");
3849 STRV_FOREACH(name
, names
) {
3850 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
3851 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
3854 /* If we shall wait for the cleaning to complete, let's add a ref on the unit first */
3855 r
= sd_bus_call_method(
3857 "org.freedesktop.systemd1",
3858 "/org/freedesktop/systemd1",
3859 "org.freedesktop.systemd1.Manager",
3865 log_error_errno(r
, "Failed to add reference to unit %s: %s", *name
, bus_error_message(&error
, r
));
3866 if (ret
== EXIT_SUCCESS
)
3872 r
= sd_bus_message_new_method_call(
3875 "org.freedesktop.systemd1",
3876 "/org/freedesktop/systemd1",
3877 "org.freedesktop.systemd1.Manager",
3880 return bus_log_create_error(r
);
3882 r
= sd_bus_message_append(m
, "s", *name
);
3884 return bus_log_create_error(r
);
3886 r
= sd_bus_message_append_strv(m
, arg_clean_what
);
3888 return bus_log_create_error(r
);
3890 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
3892 log_error_errno(r
, "Failed to clean unit %s: %s", *name
, bus_error_message(&error
, r
));
3893 if (ret
== EXIT_SUCCESS
) {
3900 r
= bus_wait_for_units_add_unit(w
, *name
, BUS_WAIT_REFFED
|BUS_WAIT_FOR_MAINTENANCE_END
, NULL
, NULL
);
3902 return log_error_errno(r
, "Failed to watch unit %s: %m", *name
);
3906 r
= bus_wait_for_units_run(w
);
3908 return log_error_errno(r
, "Failed to wait for units: %m");
3909 if (r
== BUS_WAIT_FAILURE
)
3915 typedef struct ExecStatusInfo
{
3923 usec_t start_timestamp
;
3924 usec_t exit_timestamp
;
3929 ExecCommandFlags flags
;
3931 LIST_FIELDS(struct ExecStatusInfo
, exec
);
3934 static void exec_status_info_free(ExecStatusInfo
*i
) {
3943 static int exec_status_info_deserialize(sd_bus_message
*m
, ExecStatusInfo
*i
, bool is_ex_prop
) {
3944 _cleanup_strv_free_
char **ex_opts
= NULL
;
3945 uint64_t start_timestamp
, exit_timestamp
, start_timestamp_monotonic
, exit_timestamp_monotonic
;
3948 int32_t code
, status
;
3954 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_STRUCT
, is_ex_prop
? "sasasttttuii" : "sasbttttuii");
3956 return bus_log_parse_error(r
);
3960 r
= sd_bus_message_read(m
, "s", &path
);
3962 return bus_log_parse_error(r
);
3964 i
->path
= strdup(path
);
3968 r
= sd_bus_message_read_strv(m
, &i
->argv
);
3970 return bus_log_parse_error(r
);
3972 r
= is_ex_prop
? sd_bus_message_read_strv(m
, &ex_opts
) : sd_bus_message_read(m
, "b", &ignore
);
3974 return bus_log_parse_error(r
);
3976 r
= sd_bus_message_read(m
,
3978 &start_timestamp
, &start_timestamp_monotonic
,
3979 &exit_timestamp
, &exit_timestamp_monotonic
,
3983 return bus_log_parse_error(r
);
3986 r
= exec_command_flags_from_strv(ex_opts
, &i
->flags
);
3988 return log_error_errno(r
, "Failed to convert strv to ExecCommandFlags: %m");
3990 i
->ignore
= FLAGS_SET(i
->flags
, EXEC_COMMAND_IGNORE_FAILURE
);
3994 i
->start_timestamp
= (usec_t
) start_timestamp
;
3995 i
->exit_timestamp
= (usec_t
) exit_timestamp
;
3996 i
->pid
= (pid_t
) pid
;
4000 r
= sd_bus_message_exit_container(m
);
4002 return bus_log_parse_error(r
);
4007 typedef struct UnitCondition
{
4014 LIST_FIELDS(struct UnitCondition
, conditions
);
4017 static void unit_condition_free(UnitCondition
*c
) {
4026 DEFINE_TRIVIAL_CLEANUP_FUNC(UnitCondition
*, unit_condition_free
);
4028 typedef struct UnitStatusInfo
{
4030 const char *load_state
;
4031 const char *active_state
;
4032 const char *sub_state
;
4033 const char *unit_file_state
;
4034 const char *unit_file_preset
;
4036 const char *description
;
4037 const char *following
;
4039 char **documentation
;
4041 const char *fragment_path
;
4042 const char *source_path
;
4043 const char *control_group
;
4045 char **dropin_paths
;
4047 char **triggered_by
;
4050 const char *load_error
;
4053 usec_t inactive_exit_timestamp
;
4054 usec_t inactive_exit_timestamp_monotonic
;
4055 usec_t active_enter_timestamp
;
4056 usec_t active_exit_timestamp
;
4057 usec_t inactive_enter_timestamp
;
4059 bool need_daemon_reload
;
4065 const char *status_text
;
4066 const char *pid_file
;
4070 usec_t start_timestamp
;
4071 usec_t exit_timestamp
;
4073 int exit_code
, exit_status
;
4075 usec_t condition_timestamp
;
4076 bool condition_result
;
4077 LIST_HEAD(UnitCondition
, conditions
);
4079 usec_t assert_timestamp
;
4081 bool failed_assert_trigger
;
4082 bool failed_assert_negate
;
4083 const char *failed_assert
;
4084 const char *failed_assert_parameter
;
4085 usec_t next_elapse_real
;
4086 usec_t next_elapse_monotonic
;
4089 unsigned n_accepted
;
4090 unsigned n_connections
;
4094 /* Pairs of type, path */
4098 const char *sysfs_path
;
4100 /* Mount, Automount */
4107 uint64_t memory_current
;
4108 uint64_t memory_min
;
4109 uint64_t memory_low
;
4110 uint64_t memory_high
;
4111 uint64_t memory_max
;
4112 uint64_t memory_swap_max
;
4113 uint64_t memory_limit
;
4114 uint64_t cpu_usage_nsec
;
4115 uint64_t tasks_current
;
4117 uint64_t ip_ingress_bytes
;
4118 uint64_t ip_egress_bytes
;
4119 uint64_t io_read_bytes
;
4120 uint64_t io_write_bytes
;
4122 uint64_t default_memory_min
;
4123 uint64_t default_memory_low
;
4125 LIST_HEAD(ExecStatusInfo
, exec
);
4128 static void unit_status_info_free(UnitStatusInfo
*info
) {
4132 strv_free(info
->documentation
);
4133 strv_free(info
->dropin_paths
);
4134 strv_free(info
->triggered_by
);
4135 strv_free(info
->triggers
);
4136 strv_free(info
->listen
);
4138 while ((c
= info
->conditions
)) {
4139 LIST_REMOVE(conditions
, info
->conditions
, c
);
4140 unit_condition_free(c
);
4143 while ((p
= info
->exec
)) {
4144 LIST_REMOVE(exec
, info
->exec
, p
);
4145 exec_status_info_free(p
);
4149 static void format_active_state(const char *active_state
, const char **active_on
, const char **active_off
) {
4150 if (streq_ptr(active_state
, "failed")) {
4151 *active_on
= ansi_highlight_red();
4152 *active_off
= ansi_normal();
4153 } else if (STRPTR_IN_SET(active_state
, "active", "reloading")) {
4154 *active_on
= ansi_highlight_green();
4155 *active_off
= ansi_normal();
4157 *active_on
= *active_off
= "";
4160 static void print_status_info(
4165 char since1
[FORMAT_TIMESTAMP_RELATIVE_MAX
], since2
[FORMAT_TIMESTAMP_MAX
];
4166 const char *s1
, *s2
, *active_on
, *active_off
, *on
, *off
, *ss
;
4167 _cleanup_free_
char *formatted_path
= NULL
;
4176 /* This shows pretty information about a unit. See
4177 * print_property() for a low-level property printer */
4179 format_active_state(i
->active_state
, &active_on
, &active_off
);
4181 printf("%s%s%s %s", active_on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), active_off
, strna(i
->id
));
4183 if (i
->description
&& !streq_ptr(i
->id
, i
->description
))
4184 printf(" - %s", i
->description
);
4189 printf(" Follow: unit currently follows state of %s\n", i
->following
);
4191 if (STRPTR_IN_SET(i
->load_state
, "error", "not-found", "bad-setting")) {
4192 on
= ansi_highlight_red();
4193 off
= ansi_normal();
4197 path
= i
->source_path
?: i
->fragment_path
;
4198 if (path
&& terminal_urlify_path(path
, NULL
, &formatted_path
) >= 0)
4199 path
= formatted_path
;
4201 if (!isempty(i
->load_error
))
4202 printf(" Loaded: %s%s%s (Reason: %s)\n",
4203 on
, strna(i
->load_state
), off
, i
->load_error
);
4204 else if (path
&& !isempty(i
->unit_file_state
) && !isempty(i
->unit_file_preset
) &&
4205 !STR_IN_SET(i
->unit_file_state
, "generated", "transient"))
4206 printf(" Loaded: %s%s%s (%s; %s; vendor preset: %s)\n",
4207 on
, strna(i
->load_state
), off
, path
, i
->unit_file_state
, i
->unit_file_preset
);
4208 else if (path
&& !isempty(i
->unit_file_state
))
4209 printf(" Loaded: %s%s%s (%s; %s)\n",
4210 on
, strna(i
->load_state
), off
, path
, i
->unit_file_state
);
4212 printf(" Loaded: %s%s%s (%s)\n",
4213 on
, strna(i
->load_state
), off
, path
);
4215 printf(" Loaded: %s%s%s\n",
4216 on
, strna(i
->load_state
), off
);
4219 printf(" Transient: yes\n");
4221 if (!strv_isempty(i
->dropin_paths
)) {
4222 _cleanup_free_
char *dir
= NULL
;
4226 STRV_FOREACH(dropin
, i
->dropin_paths
) {
4227 _cleanup_free_
char *dropin_formatted
= NULL
;
4236 dir
= dirname_malloc(*dropin
);
4244 special_glyph(SPECIAL_GLYPH_TREE_RIGHT
));
4247 last
= ! (*(dropin
+ 1) && startswith(*(dropin
+ 1), dir
));
4249 if (terminal_urlify_path(*dropin
, basename(*dropin
), &dropin_formatted
) >= 0)
4250 df
= dropin_formatted
;
4254 printf("%s%s", df
, last
? "\n" : ", ");
4258 ss
= streq_ptr(i
->active_state
, i
->sub_state
) ? NULL
: i
->sub_state
;
4260 printf(" Active: %s%s (%s)%s",
4261 active_on
, strna(i
->active_state
), ss
, active_off
);
4263 printf(" Active: %s%s%s",
4264 active_on
, strna(i
->active_state
), active_off
);
4266 if (!isempty(i
->result
) && !streq(i
->result
, "success"))
4267 printf(" (Result: %s)", i
->result
);
4269 timestamp
= STRPTR_IN_SET(i
->active_state
, "active", "reloading") ? i
->active_enter_timestamp
:
4270 STRPTR_IN_SET(i
->active_state
, "inactive", "failed") ? i
->inactive_enter_timestamp
:
4271 STRPTR_IN_SET(i
->active_state
, "activating") ? i
->inactive_exit_timestamp
:
4272 i
->active_exit_timestamp
;
4274 s1
= format_timestamp_relative(since1
, sizeof(since1
), timestamp
);
4275 s2
= format_timestamp(since2
, sizeof(since2
), timestamp
);
4278 printf(" since %s; %s\n", s2
, s1
);
4280 printf(" since %s\n", s2
);
4284 STRV_FOREACH(t
, i
->triggered_by
) {
4285 UnitActiveState state
= _UNIT_ACTIVE_STATE_INVALID
;
4287 (void) get_state_one_unit(bus
, *t
, &state
);
4288 format_active_state(unit_active_state_to_string(state
), &on
, &off
);
4290 printf("%s %s%s%s %s\n",
4291 t
== i
->triggered_by
? "TriggeredBy:" : " ",
4292 on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
,
4296 if (endswith(i
->id
, ".timer")) {
4297 char tstamp1
[FORMAT_TIMESTAMP_RELATIVE_MAX
],
4298 tstamp2
[FORMAT_TIMESTAMP_MAX
];
4299 const char *next_rel_time
, *next_time
;
4300 dual_timestamp nw
, next
= {i
->next_elapse_real
,
4301 i
->next_elapse_monotonic
};
4304 printf(" Trigger: ");
4306 dual_timestamp_get(&nw
);
4307 next_elapse
= calc_next_elapse(&nw
, &next
);
4308 next_rel_time
= format_timestamp_relative(tstamp1
, sizeof tstamp1
, next_elapse
);
4309 next_time
= format_timestamp(tstamp2
, sizeof tstamp2
, next_elapse
);
4311 if (next_time
&& next_rel_time
)
4312 printf("%s; %s\n", next_time
, next_rel_time
);
4317 STRV_FOREACH(t
, i
->triggers
) {
4318 UnitActiveState state
= _UNIT_ACTIVE_STATE_INVALID
;
4320 (void) get_state_one_unit(bus
, *t
, &state
);
4321 format_active_state(unit_active_state_to_string(state
), &on
, &off
);
4323 printf("%s %s%s%s %s\n",
4324 t
== i
->triggers
? " Triggers:" : " ",
4325 on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
,
4329 if (!i
->condition_result
&& i
->condition_timestamp
> 0) {
4333 s1
= format_timestamp_relative(since1
, sizeof(since1
), i
->condition_timestamp
);
4334 s2
= format_timestamp(since2
, sizeof(since2
), i
->condition_timestamp
);
4336 printf(" Condition: start %scondition failed%s at %s%s%s\n",
4337 ansi_highlight_yellow(), ansi_normal(),
4338 s2
, s1
? "; " : "", strempty(s1
));
4340 LIST_FOREACH(conditions
, c
, i
->conditions
)
4341 if (c
->tristate
< 0)
4344 LIST_FOREACH(conditions
, c
, i
->conditions
)
4345 if (c
->tristate
< 0)
4346 printf(" %s %s=%s%s%s was not met\n",
4347 --n
? special_glyph(SPECIAL_GLYPH_TREE_BRANCH
) : special_glyph(SPECIAL_GLYPH_TREE_RIGHT
),
4349 c
->trigger
? "|" : "",
4350 c
->negate
? "!" : "",
4354 if (!i
->assert_result
&& i
->assert_timestamp
> 0) {
4355 s1
= format_timestamp_relative(since1
, sizeof(since1
), i
->assert_timestamp
);
4356 s2
= format_timestamp(since2
, sizeof(since2
), i
->assert_timestamp
);
4358 printf(" Assert: start %sassertion failed%s at %s%s%s\n",
4359 ansi_highlight_red(), ansi_normal(),
4360 s2
, s1
? "; " : "", strempty(s1
));
4361 if (i
->failed_assert_trigger
)
4362 printf(" none of the trigger assertions were met\n");
4363 else if (i
->failed_assert
)
4364 printf(" %s=%s%s was not met\n",
4366 i
->failed_assert_negate
? "!" : "",
4367 i
->failed_assert_parameter
);
4371 printf(" Device: %s\n", i
->sysfs_path
);
4373 printf(" Where: %s\n", i
->where
);
4375 printf(" What: %s\n", i
->what
);
4377 STRV_FOREACH(t
, i
->documentation
) {
4378 _cleanup_free_
char *formatted
= NULL
;
4381 if (terminal_urlify(*t
, NULL
, &formatted
) >= 0)
4386 printf(" %*s %s\n", 9, t
== i
->documentation
? "Docs:" : "", q
);
4389 STRV_FOREACH_PAIR(t
, t2
, i
->listen
)
4390 printf(" %*s %s (%s)\n", 9, t
== i
->listen
? "Listen:" : "", *t2
, *t
);
4393 printf(" Accepted: %u; Connected: %u;", i
->n_accepted
, i
->n_connections
);
4395 printf(" Refused: %u", i
->n_refused
);
4399 LIST_FOREACH(exec
, p
, i
->exec
) {
4400 _cleanup_free_
char *argv
= NULL
;
4403 /* Only show exited processes here */
4407 /* Don't print ExecXYZEx= properties here since it will appear as a
4408 * duplicate of the non-Ex= variant. */
4409 if (endswith(p
->name
, "Ex"))
4412 argv
= strv_join(p
->argv
, " ");
4413 printf(" Process: "PID_FMT
" %s=%s ", p
->pid
, p
->name
, strna(argv
));
4415 good
= is_clean_exit(p
->code
, p
->status
, EXIT_CLEAN_DAEMON
, NULL
);
4417 on
= ansi_highlight_red();
4418 off
= ansi_normal();
4422 printf("%s(code=%s, ", on
, sigchld_code_to_string(p
->code
));
4424 if (p
->code
== CLD_EXITED
) {
4427 printf("status=%i", p
->status
);
4429 c
= exit_status_to_string(p
->status
, EXIT_STATUS_LIBC
| EXIT_STATUS_SYSTEMD
);
4434 printf("signal=%s", signal_to_string(p
->status
));
4436 printf(")%s\n", off
);
4438 if (i
->main_pid
== p
->pid
&&
4439 i
->start_timestamp
== p
->start_timestamp
&&
4440 i
->exit_timestamp
== p
->start_timestamp
)
4441 /* Let's not show this twice */
4444 if (p
->pid
== i
->control_pid
)
4448 if (i
->main_pid
> 0 || i
->control_pid
> 0) {
4449 if (i
->main_pid
> 0) {
4450 printf(" Main PID: "PID_FMT
, i
->main_pid
);
4454 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
4455 _cleanup_free_
char *comm
= NULL
;
4457 (void) get_process_comm(i
->main_pid
, &comm
);
4459 printf(" (%s)", comm
);
4462 } else if (i
->exit_code
> 0) {
4463 printf(" (code=%s, ", sigchld_code_to_string(i
->exit_code
));
4465 if (i
->exit_code
== CLD_EXITED
) {
4468 printf("status=%i", i
->exit_status
);
4470 c
= exit_status_to_string(i
->exit_status
,
4471 EXIT_STATUS_LIBC
| EXIT_STATUS_SYSTEMD
);
4476 printf("signal=%s", signal_to_string(i
->exit_status
));
4481 if (i
->control_pid
> 0) {
4482 _cleanup_free_
char *c
= NULL
;
4484 if (i
->main_pid
> 0)
4485 fputs("; Control PID: ", stdout
);
4487 fputs("Cntrl PID: ", stdout
); /* if first in column, abbreviated so it fits alignment */
4489 printf(PID_FMT
, i
->control_pid
);
4491 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
4492 (void) get_process_comm(i
->control_pid
, &c
);
4502 printf(" Status: \"%s\"\n", i
->status_text
);
4503 if (i
->status_errno
> 0)
4504 printf(" Error: %i (%s)\n", i
->status_errno
, strerror_safe(i
->status_errno
));
4506 if (i
->ip_ingress_bytes
!= (uint64_t) -1 && i
->ip_egress_bytes
!= (uint64_t) -1) {
4507 char buf_in
[FORMAT_BYTES_MAX
], buf_out
[FORMAT_BYTES_MAX
];
4509 printf(" IP: %s in, %s out\n",
4510 format_bytes(buf_in
, sizeof(buf_in
), i
->ip_ingress_bytes
),
4511 format_bytes(buf_out
, sizeof(buf_out
), i
->ip_egress_bytes
));
4514 if (i
->io_read_bytes
!= UINT64_MAX
&& i
->io_write_bytes
!= UINT64_MAX
) {
4515 char buf_in
[FORMAT_BYTES_MAX
], buf_out
[FORMAT_BYTES_MAX
];
4517 printf(" IO: %s read, %s written\n",
4518 format_bytes(buf_in
, sizeof(buf_in
), i
->io_read_bytes
),
4519 format_bytes(buf_out
, sizeof(buf_out
), i
->io_write_bytes
));
4522 if (i
->tasks_current
!= (uint64_t) -1) {
4523 printf(" Tasks: %" PRIu64
, i
->tasks_current
);
4525 if (i
->tasks_max
!= (uint64_t) -1)
4526 printf(" (limit: %" PRIu64
")\n", i
->tasks_max
);
4531 if (i
->memory_current
!= (uint64_t) -1) {
4532 char buf
[FORMAT_BYTES_MAX
];
4534 printf(" Memory: %s", format_bytes(buf
, sizeof(buf
), i
->memory_current
));
4536 if (i
->memory_min
> 0 || i
->memory_low
> 0 ||
4537 i
->memory_high
!= CGROUP_LIMIT_MAX
|| i
->memory_max
!= CGROUP_LIMIT_MAX
||
4538 i
->memory_swap_max
!= CGROUP_LIMIT_MAX
||
4539 i
->memory_limit
!= CGROUP_LIMIT_MAX
) {
4540 const char *prefix
= "";
4543 if (i
->memory_min
> 0) {
4544 printf("%smin: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_min
));
4547 if (i
->memory_low
> 0) {
4548 printf("%slow: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_low
));
4551 if (i
->memory_high
!= CGROUP_LIMIT_MAX
) {
4552 printf("%shigh: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_high
));
4555 if (i
->memory_max
!= CGROUP_LIMIT_MAX
) {
4556 printf("%smax: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_max
));
4559 if (i
->memory_swap_max
!= CGROUP_LIMIT_MAX
) {
4560 printf("%sswap max: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_swap_max
));
4563 if (i
->memory_limit
!= CGROUP_LIMIT_MAX
) {
4564 printf("%slimit: %s", prefix
, format_bytes(buf
, sizeof(buf
), i
->memory_limit
));
4572 if (i
->cpu_usage_nsec
!= (uint64_t) -1) {
4573 char buf
[FORMAT_TIMESPAN_MAX
];
4574 printf(" CPU: %s\n", format_timespan(buf
, sizeof(buf
), i
->cpu_usage_nsec
/ NSEC_PER_USEC
, USEC_PER_MSEC
));
4577 if (i
->control_group
) {
4578 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
4579 static const char prefix
[] = " ";
4582 printf(" CGroup: %s\n", i
->control_group
);
4585 if (c
> sizeof(prefix
) - 1)
4586 c
-= sizeof(prefix
) - 1;
4590 r
= unit_show_processes(bus
, i
->id
, i
->control_group
, prefix
, c
, get_output_flags(), &error
);
4595 /* Fallback for older systemd versions where the GetUnitProcesses() call is not yet available */
4597 if (i
->main_pid
> 0)
4598 extra
[k
++] = i
->main_pid
;
4600 if (i
->control_pid
> 0)
4601 extra
[k
++] = i
->control_pid
;
4603 show_cgroup_and_extra(SYSTEMD_CGROUP_CONTROLLER
, i
->control_group
, prefix
, c
, extra
, k
, get_output_flags());
4605 log_warning_errno(r
, "Failed to dump process list for '%s', ignoring: %s",
4606 i
->id
, bus_error_message(&error
, r
));
4609 if (i
->id
&& arg_transport
== BUS_TRANSPORT_LOCAL
)
4610 show_journal_by_unit(
4615 i
->inactive_exit_timestamp_monotonic
,
4618 get_output_flags() | OUTPUT_BEGIN_NEWLINE
,
4619 SD_JOURNAL_LOCAL_ONLY
,
4620 arg_scope
== UNIT_FILE_SYSTEM
,
4623 if (i
->need_daemon_reload
)
4624 warn_unit_file_changed(i
->id
);
4627 static void show_unit_help(UnitStatusInfo
*i
) {
4632 if (!i
->documentation
) {
4633 log_info("Documentation for %s not known.", i
->id
);
4637 STRV_FOREACH(p
, i
->documentation
)
4638 if (startswith(*p
, "man:"))
4639 show_man_page(*p
+ 4, false);
4641 log_info("Can't show: %s", *p
);
4644 static int map_main_pid(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4645 UnitStatusInfo
*i
= userdata
;
4649 r
= sd_bus_message_read(m
, "u", &u
);
4653 i
->main_pid
= (pid_t
) u
;
4659 static int map_load_error(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4660 const char *message
, **p
= userdata
;
4663 r
= sd_bus_message_read(m
, "(ss)", NULL
, &message
);
4667 if (!isempty(message
))
4673 static int map_listen(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4674 const char *type
, *path
;
4675 char ***p
= userdata
;
4678 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
4682 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0) {
4684 r
= strv_extend(p
, type
);
4688 r
= strv_extend(p
, path
);
4695 r
= sd_bus_message_exit_container(m
);
4702 static int map_conditions(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4703 UnitStatusInfo
*i
= userdata
;
4704 const char *cond
, *param
;
4705 int trigger
, negate
;
4709 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sbbsi)");
4713 while ((r
= sd_bus_message_read(m
, "(sbbsi)", &cond
, &trigger
, &negate
, ¶m
, &state
)) > 0) {
4714 _cleanup_(unit_condition_freep
) UnitCondition
*c
= NULL
;
4716 c
= new(UnitCondition
, 1);
4720 *c
= (UnitCondition
) {
4721 .name
= strdup(cond
),
4722 .param
= strdup(param
),
4728 if (!c
->name
|| !c
->param
)
4731 LIST_PREPEND(conditions
, i
->conditions
, TAKE_PTR(c
));
4736 r
= sd_bus_message_exit_container(m
);
4743 static int map_asserts(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4744 UnitStatusInfo
*i
= userdata
;
4745 const char *cond
, *param
;
4746 int trigger
, negate
;
4750 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sbbsi)");
4754 while ((r
= sd_bus_message_read(m
, "(sbbsi)", &cond
, &trigger
, &negate
, ¶m
, &state
)) > 0) {
4755 if (state
< 0 && (!trigger
|| !i
->failed_assert
)) {
4756 i
->failed_assert
= cond
;
4757 i
->failed_assert_trigger
= trigger
;
4758 i
->failed_assert_negate
= negate
;
4759 i
->failed_assert_parameter
= param
;
4765 r
= sd_bus_message_exit_container(m
);
4772 static int map_exec(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
4773 _cleanup_free_ ExecStatusInfo
*info
= NULL
;
4774 ExecStatusInfo
*last
;
4775 UnitStatusInfo
*i
= userdata
;
4776 bool is_ex_prop
= endswith(member
, "Ex");
4779 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, is_ex_prop
? "(sasasttttuii)" : "(sasbttttuii)");
4783 info
= new0(ExecStatusInfo
, 1);
4787 LIST_FIND_TAIL(exec
, i
->exec
, last
);
4789 while ((r
= exec_status_info_deserialize(m
, info
, is_ex_prop
)) > 0) {
4791 info
->name
= strdup(member
);
4795 LIST_INSERT_AFTER(exec
, i
->exec
, last
, info
);
4798 info
= new0(ExecStatusInfo
, 1);
4805 r
= sd_bus_message_exit_container(m
);
4812 static int print_property(const char *name
, const char *expected_value
, sd_bus_message
*m
, bool value
, bool all
) {
4814 const char *contents
;
4820 /* This is a low-level property printer, see
4821 * print_status_info() for the nicer output */
4823 r
= sd_bus_message_peek_type(m
, &bus_type
, &contents
);
4829 case SD_BUS_TYPE_INT32
:
4830 if (endswith(name
, "ActionExitStatus")) {
4833 r
= sd_bus_message_read_basic(m
, bus_type
, &i
);
4837 if (i
>= 0 && i
<= 255)
4838 bus_print_property_valuef(name
, expected_value
, value
, "%"PRIi32
, i
);
4840 bus_print_property_value(name
, expected_value
, value
, "[not set]");
4843 } else if (streq(name
, "NUMAPolicy")) {
4846 r
= sd_bus_message_read_basic(m
, bus_type
, &i
);
4850 bus_print_property_valuef(name
, expected_value
, value
, "%s", strna(mpol_to_string(i
)));
4856 case SD_BUS_TYPE_STRUCT
:
4858 if (contents
[0] == SD_BUS_TYPE_UINT32
&& streq(name
, "Job")) {
4861 r
= sd_bus_message_read(m
, "(uo)", &u
, NULL
);
4863 return bus_log_parse_error(r
);
4866 bus_print_property_valuef(name
, expected_value
, value
, "%"PRIu32
, u
);
4868 bus_print_property_value(name
, expected_value
, value
, "");
4872 } else if (contents
[0] == SD_BUS_TYPE_STRING
&& streq(name
, "Unit")) {
4875 r
= sd_bus_message_read(m
, "(so)", &s
, NULL
);
4877 return bus_log_parse_error(r
);
4879 if (all
|| !isempty(s
))
4880 bus_print_property_value(name
, expected_value
, value
, s
);
4884 } else if (contents
[0] == SD_BUS_TYPE_STRING
&& streq(name
, "LoadError")) {
4885 const char *a
= NULL
, *b
= NULL
;
4887 r
= sd_bus_message_read(m
, "(ss)", &a
, &b
);
4889 return bus_log_parse_error(r
);
4891 if (!isempty(a
) || !isempty(b
))
4892 bus_print_property_valuef(name
, expected_value
, value
, "%s \"%s\"", strempty(a
), strempty(b
));
4894 bus_print_property_value(name
, expected_value
, value
, "");
4898 } else if (STR_IN_SET(name
, "SystemCallFilter", "RestrictAddressFamilies")) {
4899 _cleanup_strv_free_
char **l
= NULL
;
4902 r
= sd_bus_message_enter_container(m
, 'r', "bas");
4904 return bus_log_parse_error(r
);
4906 r
= sd_bus_message_read(m
, "b", &whitelist
);
4908 return bus_log_parse_error(r
);
4910 r
= sd_bus_message_read_strv(m
, &l
);
4912 return bus_log_parse_error(r
);
4914 r
= sd_bus_message_exit_container(m
);
4916 return bus_log_parse_error(r
);
4918 if (all
|| whitelist
|| !strv_isempty(l
)) {
4923 fputs(name
, stdout
);
4930 STRV_FOREACH(i
, l
) {
4938 fputc('\n', stdout
);
4943 } else if (STR_IN_SET(name
, "SELinuxContext", "AppArmorProfile", "SmackProcessLabel")) {
4947 r
= sd_bus_message_read(m
, "(bs)", &ignore
, &s
);
4949 return bus_log_parse_error(r
);
4952 bus_print_property_valuef(name
, expected_value
, value
, "%s%s", ignore
? "-" : "", s
);
4954 bus_print_property_value(name
, expected_value
, value
, "");
4958 } else if (endswith(name
, "ExitStatus") && streq(contents
, "aiai")) {
4959 const int32_t *status
, *signal
;
4960 size_t n_status
, n_signal
, i
;
4962 r
= sd_bus_message_enter_container(m
, 'r', "aiai");
4964 return bus_log_parse_error(r
);
4966 r
= sd_bus_message_read_array(m
, 'i', (const void **) &status
, &n_status
);
4968 return bus_log_parse_error(r
);
4970 r
= sd_bus_message_read_array(m
, 'i', (const void **) &signal
, &n_signal
);
4972 return bus_log_parse_error(r
);
4974 r
= sd_bus_message_exit_container(m
);
4976 return bus_log_parse_error(r
);
4978 n_status
/= sizeof(int32_t);
4979 n_signal
/= sizeof(int32_t);
4981 if (all
|| n_status
> 0 || n_signal
> 0) {
4985 fputs(name
, stdout
);
4989 for (i
= 0; i
< n_status
; i
++) {
4995 printf("%"PRIi32
, status
[i
]);
4998 for (i
= 0; i
< n_signal
; i
++) {
5001 str
= signal_to_string((int) signal
[i
]);
5011 printf("%"PRIi32
, status
[i
]);
5014 fputc('\n', stdout
);
5021 case SD_BUS_TYPE_ARRAY
:
5023 if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "EnvironmentFiles")) {
5027 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sb)");
5029 return bus_log_parse_error(r
);
5031 while ((r
= sd_bus_message_read(m
, "(sb)", &path
, &ignore
)) > 0)
5032 bus_print_property_valuef(name
, expected_value
, value
, "%s (ignore_errors=%s)", path
, yes_no(ignore
));
5035 return bus_log_parse_error(r
);
5037 r
= sd_bus_message_exit_container(m
);
5039 return bus_log_parse_error(r
);
5043 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "Paths")) {
5044 const char *type
, *path
;
5046 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5048 return bus_log_parse_error(r
);
5050 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0)
5051 bus_print_property_valuef(name
, expected_value
, value
, "%s (%s)", path
, type
);
5053 return bus_log_parse_error(r
);
5055 r
= sd_bus_message_exit_container(m
);
5057 return bus_log_parse_error(r
);
5061 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "Listen")) {
5062 const char *type
, *path
;
5064 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5066 return bus_log_parse_error(r
);
5068 while ((r
= sd_bus_message_read(m
, "(ss)", &type
, &path
)) > 0)
5069 bus_print_property_valuef(name
, expected_value
, value
, "%s (%s)", path
, type
);
5071 return bus_log_parse_error(r
);
5073 r
= sd_bus_message_exit_container(m
);
5075 return bus_log_parse_error(r
);
5079 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "TimersMonotonic")) {
5081 uint64_t v
, next_elapse
;
5083 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(stt)");
5085 return bus_log_parse_error(r
);
5087 while ((r
= sd_bus_message_read(m
, "(stt)", &base
, &v
, &next_elapse
)) > 0) {
5088 char timespan1
[FORMAT_TIMESPAN_MAX
] = "n/a", timespan2
[FORMAT_TIMESPAN_MAX
] = "n/a";
5090 (void) format_timespan(timespan1
, sizeof timespan1
, v
, 0);
5091 (void) format_timespan(timespan2
, sizeof timespan2
, next_elapse
, 0);
5093 bus_print_property_valuef(name
, expected_value
, value
,
5094 "{ %s=%s ; next_elapse=%s }", base
, timespan1
, timespan2
);
5097 return bus_log_parse_error(r
);
5099 r
= sd_bus_message_exit_container(m
);
5101 return bus_log_parse_error(r
);
5105 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "TimersCalendar")) {
5106 const char *base
, *spec
;
5107 uint64_t next_elapse
;
5109 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sst)");
5111 return bus_log_parse_error(r
);
5113 while ((r
= sd_bus_message_read(m
, "(sst)", &base
, &spec
, &next_elapse
)) > 0) {
5114 char timestamp
[FORMAT_TIMESTAMP_MAX
] = "n/a";
5116 (void) format_timestamp(timestamp
, sizeof(timestamp
), next_elapse
);
5117 bus_print_property_valuef(name
, expected_value
, value
,
5118 "{ %s=%s ; next_elapse=%s }", base
, spec
, timestamp
);
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
&& startswith(name
, "Exec")) {
5130 ExecStatusInfo info
= {};
5131 bool is_ex_prop
= endswith(name
, "Ex");
5133 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, is_ex_prop
? "(sasasttttuii)" : "(sasbttttuii)");
5135 return bus_log_parse_error(r
);
5137 while ((r
= exec_status_info_deserialize(m
, &info
, is_ex_prop
)) > 0) {
5138 char timestamp1
[FORMAT_TIMESTAMP_MAX
], timestamp2
[FORMAT_TIMESTAMP_MAX
];
5139 _cleanup_strv_free_
char **optv
= NULL
;
5140 _cleanup_free_
char *tt
, *o
= NULL
;
5142 tt
= strv_join(info
.argv
, " ");
5145 r
= exec_command_flags_to_strv(info
.flags
, &optv
);
5147 return log_error_errno(r
, "Failed to convert ExecCommandFlags to strv: %m");
5149 o
= strv_join(optv
, " ");
5151 bus_print_property_valuef(name
, expected_value
, value
,
5152 "{ path=%s ; argv[]=%s ; flags=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT
" ; code=%s ; status=%i%s%s }",
5156 strna(format_timestamp(timestamp1
, sizeof(timestamp1
), info
.start_timestamp
)),
5157 strna(format_timestamp(timestamp2
, sizeof(timestamp2
), info
.exit_timestamp
)),
5159 sigchld_code_to_string(info
.code
),
5161 info
.code
== CLD_EXITED
? "" : "/",
5162 strempty(info
.code
== CLD_EXITED
? NULL
: signal_to_string(info
.status
)));
5164 bus_print_property_valuef(name
, expected_value
, value
,
5165 "{ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT
" ; code=%s ; status=%i%s%s }",
5168 yes_no(info
.ignore
),
5169 strna(format_timestamp(timestamp1
, sizeof(timestamp1
), info
.start_timestamp
)),
5170 strna(format_timestamp(timestamp2
, sizeof(timestamp2
), info
.exit_timestamp
)),
5172 sigchld_code_to_string(info
.code
),
5174 info
.code
== CLD_EXITED
? "" : "/",
5175 strempty(info
.code
== CLD_EXITED
? NULL
: signal_to_string(info
.status
)));
5178 strv_free(info
.argv
);
5182 r
= sd_bus_message_exit_container(m
);
5184 return bus_log_parse_error(r
);
5188 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&& streq(name
, "DeviceAllow")) {
5189 const char *path
, *rwm
;
5191 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5193 return bus_log_parse_error(r
);
5195 while ((r
= sd_bus_message_read(m
, "(ss)", &path
, &rwm
)) > 0)
5196 bus_print_property_valuef(name
, expected_value
, value
, "%s %s", strna(path
), strna(rwm
));
5198 return bus_log_parse_error(r
);
5200 r
= sd_bus_message_exit_container(m
);
5202 return bus_log_parse_error(r
);
5206 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5207 STR_IN_SET(name
, "IODeviceWeight", "BlockIODeviceWeight")) {
5211 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5213 return bus_log_parse_error(r
);
5215 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &weight
)) > 0)
5216 bus_print_property_valuef(name
, expected_value
, value
, "%s %"PRIu64
, strna(path
), weight
);
5218 return bus_log_parse_error(r
);
5220 r
= sd_bus_message_exit_container(m
);
5222 return bus_log_parse_error(r
);
5226 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5227 (cgroup_io_limit_type_from_string(name
) >= 0 ||
5228 STR_IN_SET(name
, "BlockIOReadBandwidth", "BlockIOWriteBandwidth"))) {
5232 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5234 return bus_log_parse_error(r
);
5236 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &bandwidth
)) > 0)
5237 bus_print_property_valuef(name
, expected_value
, value
, "%s %"PRIu64
, strna(path
), bandwidth
);
5239 return bus_log_parse_error(r
);
5241 r
= sd_bus_message_exit_container(m
);
5243 return bus_log_parse_error(r
);
5247 } else if (contents
[0] == SD_BUS_TYPE_STRUCT_BEGIN
&&
5248 streq(name
, "IODeviceLatencyTargetUSec")) {
5249 char ts
[FORMAT_TIMESPAN_MAX
];
5253 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(st)");
5255 return bus_log_parse_error(r
);
5257 while ((r
= sd_bus_message_read(m
, "(st)", &path
, &target
)) > 0)
5258 bus_print_property_valuef(name
, expected_value
, value
, "%s %s", strna(path
),
5259 format_timespan(ts
, sizeof(ts
), target
, 1));
5261 return bus_log_parse_error(r
);
5263 r
= sd_bus_message_exit_container(m
);
5265 return bus_log_parse_error(r
);
5269 } else if (contents
[0] == SD_BUS_TYPE_BYTE
&& streq(name
, "StandardInputData")) {
5270 _cleanup_free_
char *h
= NULL
;
5275 r
= sd_bus_message_read_array(m
, 'y', &p
, &sz
);
5277 return bus_log_parse_error(r
);
5279 n
= base64mem(p
, sz
, &h
);
5283 bus_print_property_value(name
, expected_value
, value
, h
);
5287 } else if (STR_IN_SET(name
, "IPAddressAllow", "IPAddressDeny")) {
5288 _cleanup_free_
char *addresses
= NULL
;
5290 r
= sd_bus_message_enter_container(m
, 'a', "(iayu)");
5292 return bus_log_parse_error(r
);
5295 _cleanup_free_
char *str
= NULL
;
5301 r
= sd_bus_message_enter_container(m
, 'r', "iayu");
5303 return bus_log_parse_error(r
);
5307 r
= sd_bus_message_read(m
, "i", &family
);
5309 return bus_log_parse_error(r
);
5311 r
= sd_bus_message_read_array(m
, 'y', &ap
, &an
);
5313 return bus_log_parse_error(r
);
5315 r
= sd_bus_message_read(m
, "u", &prefixlen
);
5317 return bus_log_parse_error(r
);
5319 r
= sd_bus_message_exit_container(m
);
5321 return bus_log_parse_error(r
);
5323 if (!IN_SET(family
, AF_INET
, AF_INET6
))
5326 if (an
!= FAMILY_ADDRESS_SIZE(family
))
5329 if (prefixlen
> FAMILY_ADDRESS_SIZE(family
) * 8)
5332 if (in_addr_prefix_to_string(family
, (union in_addr_union
*) ap
, prefixlen
, &str
) < 0)
5335 if (!strextend_with_separator(&addresses
, " ", str
, NULL
))
5339 r
= sd_bus_message_exit_container(m
);
5341 return bus_log_parse_error(r
);
5343 if (all
|| !isempty(addresses
))
5344 bus_print_property_value(name
, expected_value
, value
, strempty(addresses
));
5348 } else if (STR_IN_SET(name
, "BindPaths", "BindReadOnlyPaths")) {
5349 _cleanup_free_
char *paths
= NULL
;
5350 const char *source
, *dest
;
5354 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ssbt)");
5356 return bus_log_parse_error(r
);
5358 while ((r
= sd_bus_message_read(m
, "(ssbt)", &source
, &dest
, &ignore_enoent
, &rbind
)) > 0) {
5359 _cleanup_free_
char *str
= NULL
;
5361 if (isempty(source
))
5364 if (asprintf(&str
, "%s%s%s%s%s",
5365 ignore_enoent
? "-" : "",
5367 isempty(dest
) ? "" : ":",
5369 rbind
== MS_REC
? ":rbind" : "") < 0)
5372 if (!strextend_with_separator(&paths
, " ", str
, NULL
))
5376 return bus_log_parse_error(r
);
5378 r
= sd_bus_message_exit_container(m
);
5380 return bus_log_parse_error(r
);
5382 if (all
|| !isempty(paths
))
5383 bus_print_property_value(name
, expected_value
, value
, strempty(paths
));
5387 } else if (streq(name
, "TemporaryFileSystem")) {
5388 _cleanup_free_
char *paths
= NULL
;
5389 const char *target
, *option
;
5391 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(ss)");
5393 return bus_log_parse_error(r
);
5395 while ((r
= sd_bus_message_read(m
, "(ss)", &target
, &option
)) > 0) {
5396 _cleanup_free_
char *str
= NULL
;
5398 if (isempty(target
))
5401 if (asprintf(&str
, "%s%s%s", target
, isempty(option
) ? "" : ":", strempty(option
)) < 0)
5404 if (!strextend_with_separator(&paths
, " ", str
, NULL
))
5408 return bus_log_parse_error(r
);
5410 r
= sd_bus_message_exit_container(m
);
5412 return bus_log_parse_error(r
);
5414 if (all
|| !isempty(paths
))
5415 bus_print_property_value(name
, expected_value
, value
, strempty(paths
));
5419 } else if (streq(name
, "LogExtraFields")) {
5420 _cleanup_free_
char *fields
= NULL
;
5424 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "ay");
5426 return bus_log_parse_error(r
);
5428 while ((r
= sd_bus_message_read_array(m
, 'y', &p
, &sz
)) > 0) {
5429 _cleanup_free_
char *str
= NULL
;
5432 if (memchr(p
, 0, sz
))
5435 eq
= memchr(p
, '=', sz
);
5439 if (!journal_field_valid(p
, eq
- (const char*) p
, false))
5442 str
= malloc(sz
+ 1);
5449 if (!utf8_is_valid(str
))
5452 if (!strextend_with_separator(&fields
, " ", str
, NULL
))
5456 return bus_log_parse_error(r
);
5458 r
= sd_bus_message_exit_container(m
);
5460 return bus_log_parse_error(r
);
5462 if (all
|| !isempty(fields
))
5463 bus_print_property_value(name
, expected_value
, value
, strempty(fields
));
5466 } else if (contents
[0] == SD_BUS_TYPE_BYTE
&& STR_IN_SET(name
, "CPUAffinity", "NUMAMask", "AllowedCPUs", "AllowedMemoryNodes", "EffectiveCPUs", "EffectiveMemoryNodes")) {
5467 _cleanup_free_
char *affinity
= NULL
;
5468 _cleanup_(cpu_set_reset
) CPUSet set
= {};
5472 r
= sd_bus_message_read_array(m
, 'y', &a
, &n
);
5474 return bus_log_parse_error(r
);
5476 r
= cpu_set_from_dbus(a
, n
, &set
);
5478 return log_error_errno(r
, "Failed to deserialize %s: %m", name
);
5480 affinity
= cpu_set_to_range_string(&set
);
5484 bus_print_property_value(name
, expected_value
, value
, affinity
);
5495 typedef enum SystemctlShowMode
{
5496 SYSTEMCTL_SHOW_PROPERTIES
,
5497 SYSTEMCTL_SHOW_STATUS
,
5498 SYSTEMCTL_SHOW_HELP
,
5499 _SYSTEMCTL_SHOW_MODE_MAX
,
5500 _SYSTEMCTL_SHOW_MODE_INVALID
= -1,
5501 } SystemctlShowMode
;
5503 static const char* const systemctl_show_mode_table
[_SYSTEMCTL_SHOW_MODE_MAX
] = {
5504 [SYSTEMCTL_SHOW_PROPERTIES
] = "show",
5505 [SYSTEMCTL_SHOW_STATUS
] = "status",
5506 [SYSTEMCTL_SHOW_HELP
] = "help",
5509 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(systemctl_show_mode
, SystemctlShowMode
);
5511 static int show_one(
5515 SystemctlShowMode show_mode
,
5519 static const struct bus_properties_map property_map
[] = {
5520 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
5521 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
) },
5522 { "Documentation", "as", NULL
, offsetof(UnitStatusInfo
, documentation
) },
5525 { "Id", "s", NULL
, offsetof(UnitStatusInfo
, id
) },
5526 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
5527 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
) },
5528 { "SubState", "s", NULL
, offsetof(UnitStatusInfo
, sub_state
) },
5529 { "UnitFileState", "s", NULL
, offsetof(UnitStatusInfo
, unit_file_state
) },
5530 { "UnitFilePreset", "s", NULL
, offsetof(UnitStatusInfo
, unit_file_preset
) },
5531 { "Description", "s", NULL
, offsetof(UnitStatusInfo
, description
) },
5532 { "Following", "s", NULL
, offsetof(UnitStatusInfo
, following
) },
5533 { "Documentation", "as", NULL
, offsetof(UnitStatusInfo
, documentation
) },
5534 { "FragmentPath", "s", NULL
, offsetof(UnitStatusInfo
, fragment_path
) },
5535 { "SourcePath", "s", NULL
, offsetof(UnitStatusInfo
, source_path
) },
5536 { "ControlGroup", "s", NULL
, offsetof(UnitStatusInfo
, control_group
) },
5537 { "DropInPaths", "as", NULL
, offsetof(UnitStatusInfo
, dropin_paths
) },
5538 { "LoadError", "(ss)", map_load_error
, offsetof(UnitStatusInfo
, load_error
) },
5539 { "Result", "s", NULL
, offsetof(UnitStatusInfo
, result
) },
5540 { "TriggeredBy", "as", NULL
, offsetof(UnitStatusInfo
, triggered_by
) },
5541 { "Triggers", "as", NULL
, offsetof(UnitStatusInfo
, triggers
) },
5542 { "InactiveExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, inactive_exit_timestamp
) },
5543 { "InactiveExitTimestampMonotonic", "t", NULL
, offsetof(UnitStatusInfo
, inactive_exit_timestamp_monotonic
) },
5544 { "ActiveEnterTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, active_enter_timestamp
) },
5545 { "ActiveExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, active_exit_timestamp
) },
5546 { "InactiveEnterTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, inactive_enter_timestamp
) },
5547 { "NeedDaemonReload", "b", NULL
, offsetof(UnitStatusInfo
, need_daemon_reload
) },
5548 { "Transient", "b", NULL
, offsetof(UnitStatusInfo
, transient
) },
5549 { "ExecMainPID", "u", NULL
, offsetof(UnitStatusInfo
, main_pid
) },
5550 { "MainPID", "u", map_main_pid
, 0 },
5551 { "ControlPID", "u", NULL
, offsetof(UnitStatusInfo
, control_pid
) },
5552 { "StatusText", "s", NULL
, offsetof(UnitStatusInfo
, status_text
) },
5553 { "PIDFile", "s", NULL
, offsetof(UnitStatusInfo
, pid_file
) },
5554 { "StatusErrno", "i", NULL
, offsetof(UnitStatusInfo
, status_errno
) },
5555 { "ExecMainStartTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, start_timestamp
) },
5556 { "ExecMainExitTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, exit_timestamp
) },
5557 { "ExecMainCode", "i", NULL
, offsetof(UnitStatusInfo
, exit_code
) },
5558 { "ExecMainStatus", "i", NULL
, offsetof(UnitStatusInfo
, exit_status
) },
5559 { "ConditionTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, condition_timestamp
) },
5560 { "ConditionResult", "b", NULL
, offsetof(UnitStatusInfo
, condition_result
) },
5561 { "Conditions", "a(sbbsi)", map_conditions
, 0 },
5562 { "AssertTimestamp", "t", NULL
, offsetof(UnitStatusInfo
, assert_timestamp
) },
5563 { "AssertResult", "b", NULL
, offsetof(UnitStatusInfo
, assert_result
) },
5564 { "Asserts", "a(sbbsi)", map_asserts
, 0 },
5565 { "NextElapseUSecRealtime", "t", NULL
, offsetof(UnitStatusInfo
, next_elapse_real
) },
5566 { "NextElapseUSecMonotonic", "t", NULL
, offsetof(UnitStatusInfo
, next_elapse_monotonic
) },
5567 { "NAccepted", "u", NULL
, offsetof(UnitStatusInfo
, n_accepted
) },
5568 { "NConnections", "u", NULL
, offsetof(UnitStatusInfo
, n_connections
) },
5569 { "NRefused", "u", NULL
, offsetof(UnitStatusInfo
, n_refused
) },
5570 { "Accept", "b", NULL
, offsetof(UnitStatusInfo
, accept
) },
5571 { "Listen", "a(ss)", map_listen
, offsetof(UnitStatusInfo
, listen
) },
5572 { "SysFSPath", "s", NULL
, offsetof(UnitStatusInfo
, sysfs_path
) },
5573 { "Where", "s", NULL
, offsetof(UnitStatusInfo
, where
) },
5574 { "What", "s", NULL
, offsetof(UnitStatusInfo
, what
) },
5575 { "MemoryCurrent", "t", NULL
, offsetof(UnitStatusInfo
, memory_current
) },
5576 { "DefaultMemoryMin", "t", NULL
, offsetof(UnitStatusInfo
, default_memory_min
) },
5577 { "DefaultMemoryLow", "t", NULL
, offsetof(UnitStatusInfo
, default_memory_low
) },
5578 { "MemoryMin", "t", NULL
, offsetof(UnitStatusInfo
, memory_min
) },
5579 { "MemoryLow", "t", NULL
, offsetof(UnitStatusInfo
, memory_low
) },
5580 { "MemoryHigh", "t", NULL
, offsetof(UnitStatusInfo
, memory_high
) },
5581 { "MemoryMax", "t", NULL
, offsetof(UnitStatusInfo
, memory_max
) },
5582 { "MemorySwapMax", "t", NULL
, offsetof(UnitStatusInfo
, memory_swap_max
) },
5583 { "MemoryLimit", "t", NULL
, offsetof(UnitStatusInfo
, memory_limit
) },
5584 { "CPUUsageNSec", "t", NULL
, offsetof(UnitStatusInfo
, cpu_usage_nsec
) },
5585 { "TasksCurrent", "t", NULL
, offsetof(UnitStatusInfo
, tasks_current
) },
5586 { "TasksMax", "t", NULL
, offsetof(UnitStatusInfo
, tasks_max
) },
5587 { "IPIngressBytes", "t", NULL
, offsetof(UnitStatusInfo
, ip_ingress_bytes
) },
5588 { "IPEgressBytes", "t", NULL
, offsetof(UnitStatusInfo
, ip_egress_bytes
) },
5589 { "IOReadBytes", "t", NULL
, offsetof(UnitStatusInfo
, io_read_bytes
) },
5590 { "IOWriteBytes", "t", NULL
, offsetof(UnitStatusInfo
, io_write_bytes
) },
5591 { "ExecCondition", "a(sasbttttuii)", map_exec
, 0 },
5592 { "ExecConditionEx", "a(sasasttttuii)", map_exec
, 0 },
5593 { "ExecStartPre", "a(sasbttttuii)", map_exec
, 0 },
5594 { "ExecStartPreEx", "a(sasasttttuii)", map_exec
, 0 },
5595 { "ExecStart", "a(sasbttttuii)", map_exec
, 0 },
5596 { "ExecStartEx", "a(sasasttttuii)", map_exec
, 0 },
5597 { "ExecStartPost", "a(sasbttttuii)", map_exec
, 0 },
5598 { "ExecStartPostEx", "a(sasasttttuii)", map_exec
, 0 },
5599 { "ExecReload", "a(sasbttttuii)", map_exec
, 0 },
5600 { "ExecReloadEx", "a(sasasttttuii)", map_exec
, 0 },
5601 { "ExecStopPre", "a(sasbttttuii)", map_exec
, 0 },
5602 { "ExecStop", "a(sasbttttuii)", map_exec
, 0 },
5603 { "ExecStopEx", "a(sasasttttuii)", map_exec
, 0 },
5604 { "ExecStopPost", "a(sasbttttuii)", map_exec
, 0 },
5605 { "ExecStopPostEx", "a(sasasttttuii)", map_exec
, 0 },
5609 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5610 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5611 _cleanup_set_free_ Set
*found_properties
= NULL
;
5612 _cleanup_(unit_status_info_free
) UnitStatusInfo info
= {
5613 .memory_current
= (uint64_t) -1,
5614 .memory_high
= CGROUP_LIMIT_MAX
,
5615 .memory_max
= CGROUP_LIMIT_MAX
,
5616 .memory_swap_max
= CGROUP_LIMIT_MAX
,
5617 .memory_limit
= (uint64_t) -1,
5618 .cpu_usage_nsec
= (uint64_t) -1,
5619 .tasks_current
= (uint64_t) -1,
5620 .tasks_max
= (uint64_t) -1,
5621 .ip_ingress_bytes
= (uint64_t) -1,
5622 .ip_egress_bytes
= (uint64_t) -1,
5623 .io_read_bytes
= UINT64_MAX
,
5624 .io_write_bytes
= UINT64_MAX
,
5632 log_debug("Showing one %s", path
);
5634 r
= bus_map_all_properties(
5636 "org.freedesktop.systemd1",
5638 show_mode
== SYSTEMCTL_SHOW_STATUS
? status_map
: property_map
,
5639 BUS_MAP_BOOLEAN_AS_BOOL
,
5644 return log_error_errno(r
, "Failed to get properties: %s", bus_error_message(&error
, r
));
5646 if (unit
&& streq_ptr(info
.load_state
, "not-found") && streq_ptr(info
.active_state
, "inactive")) {
5647 log_full(show_mode
== SYSTEMCTL_SHOW_STATUS
? LOG_ERR
: LOG_DEBUG
,
5648 "Unit %s could not be found.", unit
);
5650 if (show_mode
== SYSTEMCTL_SHOW_STATUS
)
5651 return EXIT_PROGRAM_OR_SERVICES_STATUS_UNKNOWN
;
5652 else if (show_mode
== SYSTEMCTL_SHOW_HELP
)
5661 if (show_mode
== SYSTEMCTL_SHOW_STATUS
) {
5662 print_status_info(bus
, &info
, ellipsized
);
5664 if (info
.active_state
&& !STR_IN_SET(info
.active_state
, "active", "reloading"))
5665 return EXIT_PROGRAM_NOT_RUNNING
;
5667 return EXIT_PROGRAM_RUNNING_OR_SERVICE_OK
;
5669 } else if (show_mode
== SYSTEMCTL_SHOW_HELP
) {
5670 show_unit_help(&info
);
5674 r
= sd_bus_message_rewind(reply
, true);
5676 return log_error_errno(r
, "Failed to rewind: %s", bus_error_message(&error
, r
));
5678 r
= bus_message_print_all_properties(reply
, print_property
, arg_properties
, arg_value
, arg_all
, &found_properties
);
5680 return bus_log_parse_error(r
);
5682 STRV_FOREACH(pp
, arg_properties
)
5683 if (!set_contains(found_properties
, *pp
))
5684 log_debug("Property %s does not exist.", *pp
);
5689 static int get_unit_dbus_path_by_pid(
5694 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5695 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5699 r
= sd_bus_call_method(
5701 "org.freedesktop.systemd1",
5702 "/org/freedesktop/systemd1",
5703 "org.freedesktop.systemd1.Manager",
5709 return log_error_errno(r
, "Failed to get unit for PID %"PRIu32
": %s", pid
, bus_error_message(&error
, r
));
5711 r
= sd_bus_message_read(reply
, "o", &u
);
5713 return bus_log_parse_error(r
);
5723 static int show_all(
5728 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
5729 _cleanup_free_ UnitInfo
*unit_infos
= NULL
;
5734 r
= get_unit_list(bus
, NULL
, NULL
, &unit_infos
, 0, &reply
);
5738 (void) pager_open(arg_pager_flags
);
5742 typesafe_qsort(unit_infos
, c
, compare_unit_info
);
5744 for (u
= unit_infos
; u
< unit_infos
+ c
; u
++) {
5745 _cleanup_free_
char *p
= NULL
;
5747 p
= unit_dbus_path_from_name(u
->id
);
5751 r
= show_one(bus
, p
, u
->id
, SYSTEMCTL_SHOW_STATUS
, new_line
, ellipsized
);
5754 else if (r
> 0 && ret
== 0)
5761 static int show_system_status(sd_bus
*bus
) {
5762 char since1
[FORMAT_TIMESTAMP_RELATIVE_MAX
], since2
[FORMAT_TIMESTAMP_MAX
];
5763 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
5764 _cleanup_(machine_info_clear
) struct machine_info mi
= {};
5765 _cleanup_free_
char *hn
= NULL
;
5766 const char *on
, *off
;
5769 hn
= gethostname_malloc();
5773 r
= bus_map_all_properties(
5775 "org.freedesktop.systemd1",
5776 "/org/freedesktop/systemd1",
5777 machine_info_property_map
,
5783 return log_error_errno(r
, "Failed to read server status: %s", bus_error_message(&error
, r
));
5785 if (streq_ptr(mi
.state
, "degraded")) {
5786 on
= ansi_highlight_red();
5787 off
= ansi_normal();
5788 } else if (streq_ptr(mi
.state
, "running")) {
5789 on
= ansi_highlight_green();
5790 off
= ansi_normal();
5792 on
= ansi_highlight_yellow();
5793 off
= ansi_normal();
5796 printf("%s%s%s %s\n", on
, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE
), off
, arg_host
? arg_host
: hn
);
5798 printf(" State: %s%s%s\n",
5799 on
, strna(mi
.state
), off
);
5801 printf(" Jobs: %" PRIu32
" queued\n", mi
.n_jobs
);
5802 printf(" Failed: %" PRIu32
" units\n", mi
.n_failed_units
);
5804 printf(" Since: %s; %s\n",
5805 format_timestamp(since2
, sizeof(since2
), mi
.timestamp
),
5806 format_timestamp_relative(since1
, sizeof(since1
), mi
.timestamp
));
5808 printf(" CGroup: %s\n", mi
.control_group
?: "/");
5809 if (IN_SET(arg_transport
,
5810 BUS_TRANSPORT_LOCAL
,
5811 BUS_TRANSPORT_MACHINE
)) {
5812 static const char prefix
[] = " ";
5816 if (c
> sizeof(prefix
) - 1)
5817 c
-= sizeof(prefix
) - 1;
5821 show_cgroup(SYSTEMD_CGROUP_CONTROLLER
, strempty(mi
.control_group
), prefix
, c
, get_output_flags());
5827 static int show(int argc
, char *argv
[], void *userdata
) {
5828 bool new_line
= false, ellipsized
= false;
5829 SystemctlShowMode show_mode
;
5835 show_mode
= systemctl_show_mode_from_string(argv
[0]);
5837 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
5838 "Invalid argument.");
5840 if (show_mode
== SYSTEMCTL_SHOW_HELP
&& argc
<= 1)
5841 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
5842 "This command expects one or more unit names. Did you mean --help?");
5844 r
= acquire_bus(BUS_MANAGER
, &bus
);
5848 (void) pager_open(arg_pager_flags
);
5850 /* If no argument is specified inspect the manager itself */
5851 if (show_mode
== SYSTEMCTL_SHOW_PROPERTIES
&& argc
<= 1)
5852 return show_one(bus
, "/org/freedesktop/systemd1", NULL
, show_mode
, &new_line
, &ellipsized
);
5854 if (show_mode
== SYSTEMCTL_SHOW_STATUS
&& argc
<= 1) {
5856 show_system_status(bus
);
5860 ret
= show_all(bus
, &new_line
, &ellipsized
);
5862 _cleanup_free_
char **patterns
= NULL
;
5865 STRV_FOREACH(name
, strv_skip(argv
, 1)) {
5866 _cleanup_free_
char *path
= NULL
, *unit
= NULL
;
5869 if (safe_atou32(*name
, &id
) < 0) {
5870 if (strv_push(&patterns
, *name
) < 0)
5874 } else if (show_mode
== SYSTEMCTL_SHOW_PROPERTIES
) {
5875 /* Interpret as job id */
5876 if (asprintf(&path
, "/org/freedesktop/systemd1/job/%u", id
) < 0)
5880 /* Interpret as PID */
5881 r
= get_unit_dbus_path_by_pid(bus
, id
, &path
);
5887 r
= unit_name_from_dbus_path(path
, &unit
);
5892 r
= show_one(bus
, path
, unit
, show_mode
, &new_line
, &ellipsized
);
5895 else if (r
> 0 && ret
== 0)
5899 if (!strv_isempty(patterns
)) {
5900 _cleanup_strv_free_
char **names
= NULL
;
5902 r
= expand_names(bus
, patterns
, NULL
, &names
, NULL
);
5904 return log_error_errno(r
, "Failed to expand names: %m");
5906 STRV_FOREACH(name
, names
) {
5907 _cleanup_free_
char *path
;
5909 path
= unit_dbus_path_from_name(*name
);
5913 r
= show_one(bus
, path
, *name
, show_mode
, &new_line
, &ellipsized
);
5916 if (r
> 0 && ret
== 0)
5922 if (ellipsized
&& !arg_quiet
)
5923 printf("Hint: Some lines were ellipsized, use -l to show in full.\n");
5928 static int cat(int argc
, char *argv
[], void *userdata
) {
5929 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
5930 _cleanup_strv_free_
char **names
= NULL
;
5936 /* Include all units by default — i.e. continue as if the --all
5937 * option was used */
5938 if (strv_isempty(arg_states
))
5941 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
5942 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot remotely cat units.");
5944 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
5946 return log_error_errno(r
, "Failed to determine unit paths: %m");
5948 r
= acquire_bus(BUS_MANAGER
, &bus
);
5952 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
5954 return log_error_errno(r
, "Failed to expand names: %m");
5956 (void) pager_open(arg_pager_flags
);
5958 STRV_FOREACH(name
, names
) {
5959 _cleanup_free_
char *fragment_path
= NULL
;
5960 _cleanup_strv_free_
char **dropin_paths
= NULL
;
5962 r
= unit_find_paths(bus
, *name
, &lp
, false, &fragment_path
, &dropin_paths
);
5963 if (r
== -ERFKILL
) {
5964 printf("%s# Unit %s is masked%s.\n",
5965 ansi_highlight_magenta(),
5970 if (r
== -EKEYREJECTED
) {
5971 printf("%s# Unit %s could not be loaded.%s\n",
5972 ansi_highlight_magenta(),
5987 if (need_daemon_reload(bus
, *name
) > 0) /* ignore errors (<0), this is informational output */
5989 "%s# Warning: %s changed on disk, the version systemd has loaded is outdated.\n"
5990 "%s# This output shows the current version of the unit's original fragment and drop-in files.\n"
5991 "%s# If fragments or drop-ins were added or removed, they are not properly reflected in this output.\n"
5992 "%s# Run 'systemctl%s daemon-reload' to reload units.%s\n",
5993 ansi_highlight_red(),
5995 ansi_highlight_red(),
5996 ansi_highlight_red(),
5997 ansi_highlight_red(),
5998 arg_scope
== UNIT_FILE_SYSTEM
? "" : " --user",
6001 r
= cat_files(fragment_path
, dropin_paths
, 0);
6009 static int set_property(int argc
, char *argv
[], void *userdata
) {
6010 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6011 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6012 _cleanup_free_
char *n
= NULL
;
6017 r
= acquire_bus(BUS_MANAGER
, &bus
);
6021 polkit_agent_open_maybe();
6023 r
= sd_bus_message_new_method_call(
6026 "org.freedesktop.systemd1",
6027 "/org/freedesktop/systemd1",
6028 "org.freedesktop.systemd1.Manager",
6029 "SetUnitProperties");
6031 return bus_log_create_error(r
);
6033 r
= unit_name_mangle(argv
[1], arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, &n
);
6035 return log_error_errno(r
, "Failed to mangle unit name: %m");
6037 t
= unit_name_to_type(n
);
6039 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid unit type: %s", n
);
6041 r
= sd_bus_message_append(m
, "sb", n
, arg_runtime
);
6043 return bus_log_create_error(r
);
6045 r
= sd_bus_message_open_container(m
, SD_BUS_TYPE_ARRAY
, "(sv)");
6047 return bus_log_create_error(r
);
6049 r
= bus_append_unit_property_assignment_many(m
, t
, strv_skip(argv
, 2));
6053 r
= sd_bus_message_close_container(m
);
6055 return bus_log_create_error(r
);
6057 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6059 return log_error_errno(r
, "Failed to set unit properties on %s: %s", n
, bus_error_message(&error
, r
));
6064 static int daemon_reload(int argc
, char *argv
[], void *userdata
) {
6065 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6066 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6071 r
= acquire_bus(BUS_MANAGER
, &bus
);
6075 polkit_agent_open_maybe();
6077 switch (arg_action
) {
6084 method
= "Reexecute";
6087 case ACTION_SYSTEMCTL
:
6088 method
= streq(argv
[0], "daemon-reexec") ? "Reexecute" :
6089 /* "daemon-reload" */ "Reload";
6093 assert_not_reached("Unexpected action");
6096 r
= sd_bus_message_new_method_call(
6099 "org.freedesktop.systemd1",
6100 "/org/freedesktop/systemd1",
6101 "org.freedesktop.systemd1.Manager",
6104 return bus_log_create_error(r
);
6106 /* Note we use an extra-long timeout here. This is because a reload or reexec means generators are rerun which
6107 * are timed out after DEFAULT_TIMEOUT_USEC. Let's use twice that time here, so that the generators can have
6108 * their timeout, and for everything else there's the same time budget in place. */
6110 r
= sd_bus_call(bus
, m
, DEFAULT_TIMEOUT_USEC
* 2, &error
, NULL
);
6112 /* On reexecution, we expect a disconnect, not a reply */
6113 if (IN_SET(r
, -ETIMEDOUT
, -ECONNRESET
) && streq(method
, "Reexecute"))
6116 if (r
< 0 && arg_action
== ACTION_SYSTEMCTL
)
6117 return log_error_errno(r
, "Failed to reload daemon: %s", bus_error_message(&error
, r
));
6119 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
6120 * old ways of doing things, hence don't log any error in that case here. */
6122 return r
< 0 ? r
: 0;
6125 static int trivial_method(int argc
, char *argv
[], void *userdata
) {
6126 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6134 r
= acquire_bus(BUS_MANAGER
, &bus
);
6138 polkit_agent_open_maybe();
6141 streq(argv
[0], "clear-jobs") ||
6142 streq(argv
[0], "cancel") ? "ClearJobs" :
6143 streq(argv
[0], "reset-failed") ? "ResetFailed" :
6144 streq(argv
[0], "halt") ? "Halt" :
6145 streq(argv
[0], "reboot") ? "Reboot" :
6146 streq(argv
[0], "kexec") ? "KExec" :
6147 streq(argv
[0], "exit") ? "Exit" :
6148 /* poweroff */ "PowerOff";
6150 r
= sd_bus_call_method(
6152 "org.freedesktop.systemd1",
6153 "/org/freedesktop/systemd1",
6154 "org.freedesktop.systemd1.Manager",
6159 if (r
< 0 && arg_action
== ACTION_SYSTEMCTL
)
6160 return log_error_errno(r
, "Failed to execute operation: %s", bus_error_message(&error
, r
));
6162 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
6163 * old ways of doing things, hence don't log any error in that case here. */
6165 return r
< 0 ? r
: 0;
6168 static int reset_failed(int argc
, char *argv
[], void *userdata
) {
6169 _cleanup_strv_free_
char **names
= NULL
;
6175 return trivial_method(argc
, argv
, userdata
);
6177 r
= acquire_bus(BUS_MANAGER
, &bus
);
6181 polkit_agent_open_maybe();
6183 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
6185 return log_error_errno(r
, "Failed to expand names: %m");
6187 STRV_FOREACH(name
, names
) {
6188 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6190 q
= sd_bus_call_method(
6192 "org.freedesktop.systemd1",
6193 "/org/freedesktop/systemd1",
6194 "org.freedesktop.systemd1.Manager",
6200 log_error_errno(q
, "Failed to reset failed state of unit %s: %s", *name
, bus_error_message(&error
, q
));
6209 static int print_variable(const char *s
) {
6211 _cleanup_free_
char *esc
= NULL
;
6213 sep
= strchr(s
, '=');
6215 return log_error_errno(SYNTHETIC_ERRNO(EUCLEAN
),
6216 "Invalid environment block");
6218 esc
= shell_maybe_quote(sep
+ 1, ESCAPE_POSIX
);
6222 printf("%.*s=%s\n", (int)(sep
-s
), s
, esc
);
6226 static int show_environment(int argc
, char *argv
[], void *userdata
) {
6227 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6228 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
6233 r
= acquire_bus(BUS_MANAGER
, &bus
);
6237 (void) pager_open(arg_pager_flags
);
6239 r
= sd_bus_get_property(
6241 "org.freedesktop.systemd1",
6242 "/org/freedesktop/systemd1",
6243 "org.freedesktop.systemd1.Manager",
6249 return log_error_errno(r
, "Failed to get environment: %s", bus_error_message(&error
, r
));
6251 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "s");
6253 return bus_log_parse_error(r
);
6255 while ((r
= sd_bus_message_read_basic(reply
, SD_BUS_TYPE_STRING
, &text
)) > 0) {
6256 r
= print_variable(text
);
6261 return bus_log_parse_error(r
);
6263 r
= sd_bus_message_exit_container(reply
);
6265 return bus_log_parse_error(r
);
6270 static int switch_root(int argc
, char *argv
[], void *userdata
) {
6271 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6272 _cleanup_free_
char *cmdline_init
= NULL
;
6273 const char *root
, *init
;
6277 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
6278 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot switch root remotely.");
6280 if (argc
< 2 || argc
> 3)
6281 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Wrong number of arguments.");
6288 r
= proc_cmdline_get_key("init", 0, &cmdline_init
);
6290 log_debug_errno(r
, "Failed to parse /proc/cmdline: %m");
6292 init
= cmdline_init
;
6295 init
= empty_to_null(init
);
6297 const char *root_systemd_path
= NULL
, *root_init_path
= NULL
;
6299 root_systemd_path
= prefix_roota(root
, "/" SYSTEMD_BINARY_PATH
);
6300 root_init_path
= prefix_roota(root
, init
);
6302 /* If the passed init is actually the same as the
6303 * systemd binary, then let's suppress it. */
6304 if (files_same(root_init_path
, root_systemd_path
, 0) > 0)
6308 /* Instruct PID1 to exclude us from its killing spree applied during the transition. Otherwise we
6309 * would exit with a failure status even though the switch to the new root has succeed. */
6311 assert(saved_argv
[0]);
6312 saved_argv
[0][0] = '@';
6314 r
= acquire_bus(BUS_MANAGER
, &bus
);
6318 /* If we are slow to exit after the root switch, the new systemd instance
6319 * will send us a signal to terminate. Just ignore it and exit normally.
6320 * This way the unit does not end up as failed.
6322 r
= ignore_signals(SIGTERM
, -1);
6324 log_warning_errno(r
, "Failed to change disposition of SIGTERM to ignore: %m");
6326 log_debug("Switching root - root: %s; init: %s", root
, strna(init
));
6328 r
= sd_bus_call_method(
6330 "org.freedesktop.systemd1",
6331 "/org/freedesktop/systemd1",
6332 "org.freedesktop.systemd1.Manager",
6338 (void) default_signals(SIGTERM
, -1);
6340 return log_error_errno(r
, "Failed to switch root: %s", bus_error_message(&error
, r
));
6346 static int log_level(int argc
, char *argv
[], void *userdata
) {
6348 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6351 r
= acquire_bus(BUS_MANAGER
, &bus
);
6356 _cleanup_free_
char *level
= NULL
;
6358 r
= sd_bus_get_property_string(
6360 "org.freedesktop.systemd1",
6361 "/org/freedesktop/systemd1",
6362 "org.freedesktop.systemd1.Manager",
6367 return log_error_errno(r
, "Failed to get log level: %s", bus_error_message(&error
, r
));
6374 r
= sd_bus_set_property(
6376 "org.freedesktop.systemd1",
6377 "/org/freedesktop/systemd1",
6378 "org.freedesktop.systemd1.Manager",
6384 return log_error_errno(r
, "Failed to set log level: %s", bus_error_message(&error
, r
));
6390 static int log_target(int argc
, char *argv
[], void *userdata
) {
6392 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6395 r
= acquire_bus(BUS_MANAGER
, &bus
);
6400 _cleanup_free_
char *target
= NULL
;
6402 r
= sd_bus_get_property_string(
6404 "org.freedesktop.systemd1",
6405 "/org/freedesktop/systemd1",
6406 "org.freedesktop.systemd1.Manager",
6411 return log_error_errno(r
, "Failed to get log target: %s", bus_error_message(&error
, r
));
6418 r
= sd_bus_set_property(
6420 "org.freedesktop.systemd1",
6421 "/org/freedesktop/systemd1",
6422 "org.freedesktop.systemd1.Manager",
6428 return log_error_errno(r
, "Failed to set log target: %s", bus_error_message(&error
, r
));
6434 static int service_watchdogs(int argc
, char *argv
[], void *userdata
) {
6436 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6441 r
= acquire_bus(BUS_MANAGER
, &bus
);
6446 /* get ServiceWatchdogs */
6447 r
= sd_bus_get_property_trivial(
6449 "org.freedesktop.systemd1",
6450 "/org/freedesktop/systemd1",
6451 "org.freedesktop.systemd1.Manager",
6457 return log_error_errno(r
, "Failed to get service-watchdog state: %s", bus_error_message(&error
, r
));
6459 printf("%s\n", yes_no(!!b
));
6462 /* set ServiceWatchdogs */
6465 b
= parse_boolean(argv
[1]);
6467 return log_error_errno(b
, "Failed to parse service-watchdogs argument: %m");
6469 r
= sd_bus_set_property(
6471 "org.freedesktop.systemd1",
6472 "/org/freedesktop/systemd1",
6473 "org.freedesktop.systemd1.Manager",
6479 return log_error_errno(r
, "Failed to set service-watchdog state: %s", bus_error_message(&error
, r
));
6485 static int set_environment(int argc
, char *argv
[], void *userdata
) {
6486 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6487 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6495 r
= acquire_bus(BUS_MANAGER
, &bus
);
6499 polkit_agent_open_maybe();
6501 method
= streq(argv
[0], "set-environment")
6503 : "UnsetEnvironment";
6505 r
= sd_bus_message_new_method_call(
6508 "org.freedesktop.systemd1",
6509 "/org/freedesktop/systemd1",
6510 "org.freedesktop.systemd1.Manager",
6513 return bus_log_create_error(r
);
6515 r
= sd_bus_message_append_strv(m
, strv_skip(argv
, 1));
6517 return bus_log_create_error(r
);
6519 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6521 return log_error_errno(r
, "Failed to set environment: %s", bus_error_message(&error
, r
));
6526 static int import_environment(int argc
, char *argv
[], void *userdata
) {
6527 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6528 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6532 r
= acquire_bus(BUS_MANAGER
, &bus
);
6536 polkit_agent_open_maybe();
6538 r
= sd_bus_message_new_method_call(
6541 "org.freedesktop.systemd1",
6542 "/org/freedesktop/systemd1",
6543 "org.freedesktop.systemd1.Manager",
6546 return bus_log_create_error(r
);
6549 r
= sd_bus_message_append_strv(m
, environ
);
6553 r
= sd_bus_message_open_container(m
, 'a', "s");
6555 return bus_log_create_error(r
);
6557 STRV_FOREACH(a
, strv_skip(argv
, 1)) {
6559 if (!env_name_is_valid(*a
))
6560 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Not a valid environment variable name: %s", *a
);
6562 STRV_FOREACH(b
, environ
) {
6565 eq
= startswith(*b
, *a
);
6566 if (eq
&& *eq
== '=') {
6568 r
= sd_bus_message_append(m
, "s", *b
);
6570 return bus_log_create_error(r
);
6577 r
= sd_bus_message_close_container(m
);
6580 return bus_log_create_error(r
);
6582 r
= sd_bus_call(bus
, m
, 0, &error
, NULL
);
6584 return log_error_errno(r
, "Failed to import environment: %s", bus_error_message(&error
, r
));
6589 static int enable_sysv_units(const char *verb
, char **args
) {
6592 #if HAVE_SYSV_COMPAT
6593 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
6596 /* Processes all SysV units, and reshuffles the array so that afterwards only the native units remain */
6598 if (arg_scope
!= UNIT_FILE_SYSTEM
)
6601 if (getenv_bool("SYSTEMCTL_SKIP_SYSV") > 0)
6604 if (!STR_IN_SET(verb
,
6610 r
= lookup_paths_init(&paths
, arg_scope
, LOOKUP_PATHS_EXCLUDE_GENERATED
, arg_root
);
6617 const char *argv
[] = {
6618 ROOTLIBEXECDIR
"/systemd-sysv-install",
6625 _cleanup_free_
char *p
= NULL
, *q
= NULL
, *l
= NULL
, *v
= NULL
;
6626 bool found_native
= false, found_sysv
;
6634 if (!endswith(name
, ".service"))
6637 if (path_is_absolute(name
))
6640 j
= unit_file_exists(arg_scope
, &paths
, name
);
6641 if (j
< 0 && !IN_SET(j
, -ELOOP
, -ERFKILL
, -EADDRNOTAVAIL
))
6642 return log_error_errno(j
, "Failed to lookup unit file state: %m");
6643 found_native
= j
!= 0;
6645 /* If we have both a native unit and a SysV script, enable/disable them both (below); for is-enabled,
6646 * prefer the native unit */
6647 if (found_native
&& streq(verb
, "is-enabled"))
6650 p
= path_join(arg_root
, SYSTEM_SYSVINIT_PATH
, name
);
6654 p
[strlen(p
) - STRLEN(".service")] = 0;
6655 found_sysv
= access(p
, F_OK
) >= 0;
6661 log_info("Synchronizing state of %s with SysV service script with %s.", name
, argv
[0]);
6663 log_info("%s is not a native service, redirecting to systemd-sysv-install.", name
);
6666 if (!isempty(arg_root
)) {
6667 q
= strjoin("--root=", arg_root
);
6674 /* Let's copy the verb, since it's still pointing directly into the original argv[] array we
6675 * got passed, but safe_fork() is likely going to rewrite that for the new child */
6681 argv
[c
++] = basename(p
);
6684 l
= strv_join((char**)argv
, " ");
6689 log_info("Executing: %s", l
);
6691 j
= safe_fork("(sysv-install)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
, &pid
);
6696 execv(argv
[0], (char**) argv
);
6697 log_error_errno(errno
, "Failed to execute %s: %m", argv
[0]);
6698 _exit(EXIT_FAILURE
);
6701 j
= wait_for_terminate_and_check("sysv-install", pid
, WAIT_LOG_ABNORMAL
);
6704 if (streq(verb
, "is-enabled")) {
6705 if (j
== EXIT_SUCCESS
) {
6714 } else if (j
!= EXIT_SUCCESS
)
6715 return -EBADE
; /* We don't warn here, under the assumption the script already showed an explanation */
6720 /* Remove this entry, so that we don't try enabling it as native unit */
6723 assert(args
[f
] == name
);
6724 strv_remove(args
+ f
, name
);
6731 static int mangle_names(const char *operation
, char **original_names
, char ***mangled_names
) {
6732 char **i
, **l
, **name
;
6735 l
= i
= new(char*, strv_length(original_names
) + 1);
6739 STRV_FOREACH(name
, original_names
) {
6741 /* When enabling units qualified path names are OK,
6742 * too, hence allow them explicitly. */
6744 if (is_path(*name
)) {
6751 r
= unit_name_mangle_with_suffix(*name
, operation
,
6752 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
6757 return log_error_errno(r
, "Failed to mangle unit name: %m");
6770 static int normalize_filenames(char **names
) {
6774 STRV_FOREACH(u
, names
)
6775 if (!path_is_absolute(*u
)) {
6776 char* normalized_path
;
6778 if (!isempty(arg_root
))
6779 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6780 "Non-absolute paths are not allowed when --root is used: %s",
6783 if (!strchr(*u
,'/'))
6784 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6785 "Link argument does contain at least one directory separator: %s",
6788 r
= path_make_absolute_cwd(*u
, &normalized_path
);
6792 free_and_replace(*u
, normalized_path
);
6798 static int normalize_names(char **names
, bool warn_if_path
) {
6800 bool was_path
= false;
6802 STRV_FOREACH(u
, names
) {
6808 r
= free_and_strdup(u
, basename(*u
));
6810 return log_error_errno(r
, "Failed to normalize unit file path: %m");
6815 if (warn_if_path
&& was_path
)
6816 log_warning("Warning: Can't execute disable on the unit file path. Proceeding with the unit name.");
6821 static int unit_exists(LookupPaths
*lp
, const char *unit
) {
6822 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6823 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
6824 _cleanup_free_
char *path
= NULL
;
6825 static const struct bus_properties_map property_map
[] = {
6826 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
6827 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
)},
6830 UnitStatusInfo info
= {};
6834 if (unit_name_is_valid(unit
, UNIT_NAME_TEMPLATE
))
6835 return unit_find_template_path(unit
, lp
, NULL
, NULL
);
6837 path
= unit_dbus_path_from_name(unit
);
6841 r
= acquire_bus(BUS_MANAGER
, &bus
);
6845 r
= bus_map_all_properties(bus
, "org.freedesktop.systemd1", path
, property_map
, 0, &error
, &m
, &info
);
6847 return log_error_errno(r
, "Failed to get properties: %s", bus_error_message(&error
, r
));
6849 return !streq_ptr(info
.load_state
, "not-found") || !streq_ptr(info
.active_state
, "inactive");
6852 static int enable_unit(int argc
, char *argv
[], void *userdata
) {
6853 _cleanup_strv_free_
char **names
= NULL
;
6854 const char *verb
= argv
[0];
6855 UnitFileChange
*changes
= NULL
;
6856 size_t n_changes
= 0;
6857 int carries_install_info
= -1;
6858 bool ignore_carries_install_info
= arg_quiet
;
6864 r
= mangle_names("to enable", strv_skip(argv
, 1), &names
);
6868 r
= enable_sysv_units(verb
, names
);
6872 /* If the operation was fully executed by the SysV compat, let's finish early */
6873 if (strv_isempty(names
)) {
6874 if (arg_no_reload
|| install_client_side())
6876 return daemon_reload(argc
, argv
, userdata
);
6879 if (streq(verb
, "disable")) {
6880 r
= normalize_names(names
, true);
6885 if (streq(verb
, "link")) {
6886 r
= normalize_filenames(names
);
6891 if (install_client_side()) {
6892 UnitFileFlags flags
;
6894 flags
= args_to_flags();
6895 if (streq(verb
, "enable")) {
6896 r
= unit_file_enable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6897 carries_install_info
= r
;
6898 } else if (streq(verb
, "disable"))
6899 r
= unit_file_disable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6900 else if (streq(verb
, "reenable")) {
6901 r
= unit_file_reenable(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6902 carries_install_info
= r
;
6903 } else if (streq(verb
, "link"))
6904 r
= unit_file_link(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6905 else if (streq(verb
, "preset")) {
6906 r
= unit_file_preset(arg_scope
, flags
, arg_root
, names
, arg_preset_mode
, &changes
, &n_changes
);
6907 } else if (streq(verb
, "mask"))
6908 r
= unit_file_mask(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6909 else if (streq(verb
, "unmask"))
6910 r
= unit_file_unmask(arg_scope
, flags
, arg_root
, names
, &changes
, &n_changes
);
6911 else if (streq(verb
, "revert"))
6912 r
= unit_file_revert(arg_scope
, arg_root
, names
, &changes
, &n_changes
);
6914 assert_not_reached("Unknown verb");
6916 unit_file_dump_changes(r
, verb
, changes
, n_changes
, arg_quiet
);
6921 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
, *m
= NULL
;
6922 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
6923 bool expect_carries_install_info
= false;
6924 bool send_runtime
= true, send_force
= true, send_preset_mode
= false;
6928 if (STR_IN_SET(verb
, "mask", "unmask")) {
6930 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
6932 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
6936 STRV_FOREACH(name
, names
) {
6937 r
= unit_exists(&lp
, *name
);
6941 log_notice("Unit %s does not exist, proceeding anyway.", *name
);
6945 r
= acquire_bus(BUS_MANAGER
, &bus
);
6949 polkit_agent_open_maybe();
6951 if (streq(verb
, "enable")) {
6952 method
= "EnableUnitFiles";
6953 expect_carries_install_info
= true;
6954 } else if (streq(verb
, "disable")) {
6955 method
= "DisableUnitFiles";
6957 } else if (streq(verb
, "reenable")) {
6958 method
= "ReenableUnitFiles";
6959 expect_carries_install_info
= true;
6960 } else if (streq(verb
, "link"))
6961 method
= "LinkUnitFiles";
6962 else if (streq(verb
, "preset")) {
6964 if (arg_preset_mode
!= UNIT_FILE_PRESET_FULL
) {
6965 method
= "PresetUnitFilesWithMode";
6966 send_preset_mode
= true;
6968 method
= "PresetUnitFiles";
6970 expect_carries_install_info
= true;
6971 ignore_carries_install_info
= true;
6972 } else if (streq(verb
, "mask"))
6973 method
= "MaskUnitFiles";
6974 else if (streq(verb
, "unmask")) {
6975 method
= "UnmaskUnitFiles";
6977 } else if (streq(verb
, "revert")) {
6978 method
= "RevertUnitFiles";
6979 send_runtime
= send_force
= false;
6981 assert_not_reached("Unknown verb");
6983 r
= sd_bus_message_new_method_call(
6986 "org.freedesktop.systemd1",
6987 "/org/freedesktop/systemd1",
6988 "org.freedesktop.systemd1.Manager",
6991 return bus_log_create_error(r
);
6993 r
= sd_bus_message_append_strv(m
, names
);
6995 return bus_log_create_error(r
);
6997 if (send_preset_mode
) {
6998 r
= sd_bus_message_append(m
, "s", unit_file_preset_mode_to_string(arg_preset_mode
));
7000 return bus_log_create_error(r
);
7004 r
= sd_bus_message_append(m
, "b", arg_runtime
);
7006 return bus_log_create_error(r
);
7010 r
= sd_bus_message_append(m
, "b", arg_force
);
7012 return bus_log_create_error(r
);
7015 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
7017 return log_error_errno(r
, "Failed to %s unit: %s", verb
, bus_error_message(&error
, r
));
7019 if (expect_carries_install_info
) {
7020 r
= sd_bus_message_read(reply
, "b", &carries_install_info
);
7022 return bus_log_parse_error(r
);
7025 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
7029 /* Try to reload if enabled */
7031 r
= daemon_reload(argc
, argv
, userdata
);
7036 if (carries_install_info
== 0 && !ignore_carries_install_info
)
7037 log_notice("The unit files have no installation config (WantedBy=, RequiredBy=, Also=,\n"
7038 "Alias= settings in the [Install] section, and DefaultInstance= for template\n"
7039 "units). This means they are not meant to be enabled using systemctl.\n"
7040 " \n" /* trick: the space is needed so that the line does not get stripped from output */
7041 "Possible reasons for having this kind of units are:\n"
7042 "%1$s A unit may be statically enabled by being symlinked from another unit's\n"
7043 " .wants/ or .requires/ directory.\n"
7044 "%1$s A unit's purpose may be to act as a helper for some other unit which has\n"
7045 " a requirement dependency on it.\n"
7046 "%1$s A unit may be started when needed via activation (socket, path, timer,\n"
7047 " D-Bus, udev, scripted systemctl call, ...).\n"
7048 "%1$s In case of template units, the unit is meant to be enabled with some\n"
7049 " instance name specified.",
7050 special_glyph(SPECIAL_GLYPH_BULLET
));
7052 if (arg_now
&& STR_IN_SET(argv
[0], "enable", "disable", "mask")) {
7056 r
= acquire_bus(BUS_MANAGER
, &bus
);
7060 len
= strv_length(names
);
7062 char *new_args
[len
+ 2];
7064 new_args
[0] = (char*) (streq(argv
[0], "enable") ? "start" : "stop");
7065 for (i
= 0; i
< len
; i
++)
7066 new_args
[i
+ 1] = basename(names
[i
]);
7067 new_args
[i
+ 1] = NULL
;
7069 r
= start_unit(len
+ 1, new_args
, userdata
);
7074 unit_file_changes_free(changes
, n_changes
);
7079 static int add_dependency(int argc
, char *argv
[], void *userdata
) {
7080 _cleanup_strv_free_
char **names
= NULL
;
7081 _cleanup_free_
char *target
= NULL
;
7082 const char *verb
= argv
[0];
7083 UnitFileChange
*changes
= NULL
;
7084 size_t n_changes
= 0;
7091 r
= unit_name_mangle_with_suffix(argv
[1], "as target",
7092 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
7093 ".target", &target
);
7095 return log_error_errno(r
, "Failed to mangle unit name: %m");
7097 r
= mangle_names("as dependency", strv_skip(argv
, 2), &names
);
7101 if (streq(verb
, "add-wants"))
7103 else if (streq(verb
, "add-requires"))
7104 dep
= UNIT_REQUIRES
;
7106 assert_not_reached("Unknown verb");
7108 if (install_client_side()) {
7109 r
= unit_file_add_dependency(arg_scope
, args_to_flags(), arg_root
, names
, target
, dep
, &changes
, &n_changes
);
7110 unit_file_dump_changes(r
, "add dependency on", changes
, n_changes
, arg_quiet
);
7115 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
, *m
= NULL
;
7116 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7119 r
= acquire_bus(BUS_MANAGER
, &bus
);
7123 polkit_agent_open_maybe();
7125 r
= sd_bus_message_new_method_call(
7128 "org.freedesktop.systemd1",
7129 "/org/freedesktop/systemd1",
7130 "org.freedesktop.systemd1.Manager",
7131 "AddDependencyUnitFiles");
7133 return bus_log_create_error(r
);
7135 r
= sd_bus_message_append_strv(m
, names
);
7137 return bus_log_create_error(r
);
7139 r
= sd_bus_message_append(m
, "ssbb", target
, unit_dependency_to_string(dep
), arg_runtime
, arg_force
);
7141 return bus_log_create_error(r
);
7143 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
7145 return log_error_errno(r
, "Failed to add dependency: %s", bus_error_message(&error
, r
));
7147 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
7151 if (arg_no_reload
) {
7156 r
= daemon_reload(argc
, argv
, userdata
);
7160 unit_file_changes_free(changes
, n_changes
);
7165 static int preset_all(int argc
, char *argv
[], void *userdata
) {
7166 UnitFileChange
*changes
= NULL
;
7167 size_t n_changes
= 0;
7170 if (install_client_side()) {
7171 r
= unit_file_preset_all(arg_scope
, args_to_flags(), arg_root
, arg_preset_mode
, &changes
, &n_changes
);
7172 unit_file_dump_changes(r
, "preset", changes
, n_changes
, arg_quiet
);
7177 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7178 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7181 r
= acquire_bus(BUS_MANAGER
, &bus
);
7185 polkit_agent_open_maybe();
7187 r
= sd_bus_call_method(
7189 "org.freedesktop.systemd1",
7190 "/org/freedesktop/systemd1",
7191 "org.freedesktop.systemd1.Manager",
7192 "PresetAllUnitFiles",
7196 unit_file_preset_mode_to_string(arg_preset_mode
),
7200 return log_error_errno(r
, "Failed to preset all units: %s", bus_error_message(&error
, r
));
7202 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
, &changes
, &n_changes
);
7206 if (arg_no_reload
) {
7211 r
= daemon_reload(argc
, argv
, userdata
);
7215 unit_file_changes_free(changes
, n_changes
);
7220 static int show_installation_targets_client_side(const char *name
) {
7221 UnitFileChange
*changes
= NULL
;
7222 size_t n_changes
= 0, i
;
7223 UnitFileFlags flags
;
7227 p
= STRV_MAKE(name
);
7228 flags
= UNIT_FILE_DRY_RUN
|
7229 (arg_runtime
? UNIT_FILE_RUNTIME
: 0);
7231 r
= unit_file_disable(UNIT_FILE_SYSTEM
, flags
, NULL
, p
, &changes
, &n_changes
);
7233 return log_error_errno(r
, "Failed to get file links for %s: %m", name
);
7235 for (i
= 0; i
< n_changes
; i
++)
7236 if (changes
[i
].type
== UNIT_FILE_UNLINK
)
7237 printf(" %s\n", changes
[i
].path
);
7242 static int show_installation_targets(sd_bus
*bus
, const char *name
) {
7243 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7244 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7248 r
= sd_bus_call_method(
7250 "org.freedesktop.systemd1",
7251 "/org/freedesktop/systemd1",
7252 "org.freedesktop.systemd1.Manager",
7256 "sb", name
, arg_runtime
);
7258 return log_error_errno(r
, "Failed to get unit file links for %s: %s", name
, bus_error_message(&error
, r
));
7260 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "s");
7262 return bus_log_parse_error(r
);
7264 while ((r
= sd_bus_message_read(reply
, "s", &link
)) > 0)
7265 printf(" %s\n", link
);
7268 return bus_log_parse_error(r
);
7270 r
= sd_bus_message_exit_container(reply
);
7272 return bus_log_parse_error(r
);
7277 static int unit_is_enabled(int argc
, char *argv
[], void *userdata
) {
7278 _cleanup_strv_free_
char **names
= NULL
;
7283 r
= mangle_names("to check", strv_skip(argv
, 1), &names
);
7287 r
= enable_sysv_units(argv
[0], names
);
7293 if (install_client_side()) {
7294 STRV_FOREACH(name
, names
) {
7295 UnitFileState state
;
7297 r
= unit_file_get_state(arg_scope
, arg_root
, *name
, &state
);
7299 return log_error_errno(r
, "Failed to get unit file state for %s: %m", *name
);
7303 UNIT_FILE_ENABLED_RUNTIME
,
7306 UNIT_FILE_GENERATED
))
7310 puts(unit_file_state_to_string(state
));
7312 r
= show_installation_targets_client_side(*name
);
7321 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7324 r
= acquire_bus(BUS_MANAGER
, &bus
);
7328 STRV_FOREACH(name
, names
) {
7329 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
7332 r
= sd_bus_call_method(
7334 "org.freedesktop.systemd1",
7335 "/org/freedesktop/systemd1",
7336 "org.freedesktop.systemd1.Manager",
7342 return log_error_errno(r
, "Failed to get unit file state for %s: %s", *name
, bus_error_message(&error
, r
));
7344 r
= sd_bus_message_read(reply
, "s", &s
);
7346 return bus_log_parse_error(r
);
7348 if (STR_IN_SET(s
, "enabled", "enabled-runtime", "static", "indirect", "generated"))
7354 r
= show_installation_targets(bus
, *name
);
7362 return enabled
? EXIT_SUCCESS
: EXIT_FAILURE
;
7365 static int match_startup_finished(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
7366 char **state
= userdata
;
7371 r
= sd_bus_get_property_string(
7372 sd_bus_message_get_bus(m
),
7373 "org.freedesktop.systemd1",
7374 "/org/freedesktop/systemd1",
7375 "org.freedesktop.systemd1.Manager",
7380 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m
)), r
);
7384 static int is_system_running(int argc
, char *argv
[], void *userdata
) {
7385 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
7386 _cleanup_(sd_bus_slot_unrefp
) sd_bus_slot
*slot_startup_finished
= NULL
;
7387 _cleanup_(sd_event_unrefp
) sd_event
* event
= NULL
;
7388 _cleanup_free_
char *state
= NULL
;
7392 if (running_in_chroot() > 0 || (arg_transport
== BUS_TRANSPORT_LOCAL
&& !sd_booted())) {
7395 return EXIT_FAILURE
;
7398 r
= acquire_bus(BUS_MANAGER
, &bus
);
7403 r
= sd_event_default(&event
);
7405 r
= sd_bus_attach_event(bus
, event
, 0);
7407 r
= sd_bus_match_signal_async(
7409 &slot_startup_finished
,
7410 "org.freedesktop.systemd1",
7411 "/org/freedesktop/systemd1",
7412 "org.freedesktop.systemd1.Manager",
7414 match_startup_finished
, NULL
, &state
);
7416 log_warning_errno(r
, "Failed to request match for StartupFinished: %m");
7421 r
= sd_bus_get_property_string(
7423 "org.freedesktop.systemd1",
7424 "/org/freedesktop/systemd1",
7425 "org.freedesktop.systemd1.Manager",
7430 log_warning_errno(r
, "Failed to query system state: %s", bus_error_message(&error
, r
));
7434 return EXIT_FAILURE
;
7437 if (arg_wait
&& STR_IN_SET(state
, "initializing", "starting")) {
7438 r
= sd_event_loop(event
);
7440 log_warning_errno(r
, "Failed to get property from event loop: %m");
7443 return EXIT_FAILURE
;
7450 return streq(state
, "running") ? EXIT_SUCCESS
: EXIT_FAILURE
;
7453 static int create_edit_temp_file(const char *new_path
, const char *original_path
, char **ret_tmp_fn
) {
7454 _cleanup_free_
char *t
= NULL
;
7458 assert(original_path
);
7461 r
= tempfn_random(new_path
, NULL
, &t
);
7463 return log_error_errno(r
, "Failed to determine temporary filename for \"%s\": %m", new_path
);
7465 r
= mkdir_parents(new_path
, 0755);
7467 return log_error_errno(r
, "Failed to create directories for \"%s\": %m", new_path
);
7469 r
= copy_file(original_path
, t
, 0, 0644, 0, 0, COPY_REFLINK
);
7474 return log_error_errno(r
, "Failed to create temporary file \"%s\": %m", t
);
7477 return log_error_errno(r
, "Failed to create temporary file for \"%s\": %m", new_path
);
7479 *ret_tmp_fn
= TAKE_PTR(t
);
7484 static int get_file_to_edit(
7485 const LookupPaths
*paths
,
7489 _cleanup_free_
char *path
= NULL
, *run
= NULL
;
7494 path
= path_join(paths
->persistent_config
, name
);
7499 run
= path_join(paths
->runtime_config
, name
);
7505 if (access(path
, F_OK
) >= 0)
7506 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
7507 "Refusing to create \"%s\" because it would be overridden by \"%s\" anyway.",
7510 *ret_path
= TAKE_PTR(run
);
7512 *ret_path
= TAKE_PTR(path
);
7517 static int unit_file_create_new(
7518 const LookupPaths
*paths
,
7519 const char *unit_name
,
7521 char **ret_new_path
,
7522 char **ret_tmp_path
) {
7524 _cleanup_free_
char *new_path
= NULL
, *tmp_path
= NULL
;
7529 assert(ret_new_path
);
7530 assert(ret_tmp_path
);
7532 ending
= strjoina(unit_name
, suffix
);
7533 r
= get_file_to_edit(paths
, ending
, &new_path
);
7537 r
= create_edit_temp_file(new_path
, new_path
, &tmp_path
);
7541 *ret_new_path
= TAKE_PTR(new_path
);
7542 *ret_tmp_path
= TAKE_PTR(tmp_path
);
7547 static int unit_file_create_copy(
7548 const LookupPaths
*paths
,
7549 const char *unit_name
,
7550 const char *fragment_path
,
7551 char **ret_new_path
,
7552 char **ret_tmp_path
) {
7554 _cleanup_free_
char *new_path
= NULL
, *tmp_path
= NULL
;
7557 assert(fragment_path
);
7559 assert(ret_new_path
);
7560 assert(ret_tmp_path
);
7562 r
= get_file_to_edit(paths
, unit_name
, &new_path
);
7566 if (!path_equal(fragment_path
, new_path
) && access(new_path
, F_OK
) >= 0) {
7569 r
= ask_char(&response
, "yn", "\"%s\" already exists. Overwrite with \"%s\"? [(y)es, (n)o] ", new_path
, fragment_path
);
7572 if (response
!= 'y')
7573 return log_warning_errno(SYNTHETIC_ERRNO(EKEYREJECTED
), "%s skipped.", unit_name
);
7576 r
= create_edit_temp_file(new_path
, fragment_path
, &tmp_path
);
7580 *ret_new_path
= TAKE_PTR(new_path
);
7581 *ret_tmp_path
= TAKE_PTR(tmp_path
);
7586 static int run_editor(char **paths
) {
7591 r
= safe_fork("(editor)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_LOG
|FORK_WAIT
, NULL
);
7595 char **editor_args
= NULL
, **tmp_path
, **original_path
;
7596 size_t n_editor_args
= 0, i
= 1, argc
;
7597 const char **args
, *editor
, *p
;
7599 argc
= strv_length(paths
)/2 + 1;
7601 /* SYSTEMD_EDITOR takes precedence over EDITOR which takes precedence over VISUAL
7602 * If neither SYSTEMD_EDITOR nor EDITOR nor VISUAL are present,
7603 * we try to execute well known editors
7605 editor
= getenv("SYSTEMD_EDITOR");
7607 editor
= getenv("EDITOR");
7609 editor
= getenv("VISUAL");
7611 if (!isempty(editor
)) {
7612 editor_args
= strv_split(editor
, WHITESPACE
);
7615 _exit(EXIT_FAILURE
);
7617 n_editor_args
= strv_length(editor_args
);
7618 argc
+= n_editor_args
- 1;
7621 args
= newa(const char*, argc
+ 1);
7623 if (n_editor_args
> 0) {
7624 args
[0] = editor_args
[0];
7625 for (; i
< n_editor_args
; i
++)
7626 args
[i
] = editor_args
[i
];
7629 STRV_FOREACH_PAIR(original_path
, tmp_path
, paths
)
7630 args
[i
++] = *tmp_path
;
7633 if (n_editor_args
> 0)
7634 execvp(args
[0], (char* const*) args
);
7636 FOREACH_STRING(p
, "editor", "nano", "vim", "vi") {
7638 execvp(p
, (char* const*) args
);
7639 /* We do not fail if the editor doesn't exist
7640 * because we want to try each one of them before
7643 if (errno
!= ENOENT
) {
7644 log_error_errno(errno
, "Failed to execute %s: %m", editor
);
7645 _exit(EXIT_FAILURE
);
7649 log_error("Cannot edit unit(s), no editor available. Please set either $SYSTEMD_EDITOR, $EDITOR or $VISUAL.");
7650 _exit(EXIT_FAILURE
);
7656 static int find_paths_to_edit(sd_bus
*bus
, char **names
, char ***paths
) {
7657 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
7664 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
7668 STRV_FOREACH(name
, names
) {
7669 _cleanup_free_
char *path
= NULL
, *new_path
= NULL
, *tmp_path
= NULL
, *tmp_name
= NULL
;
7670 const char *unit_name
;
7672 r
= unit_find_paths(bus
, *name
, &lp
, false, &path
, NULL
);
7673 if (r
== -EKEYREJECTED
) {
7674 /* If loading of the unit failed server side complete, then the server won't tell us the unit
7675 * file path. In that case, find the file client side. */
7676 log_debug_errno(r
, "Unit '%s' was not loaded correctly, retrying client-side.", *name
);
7677 r
= unit_find_paths(bus
, *name
, &lp
, true, &path
, NULL
);
7680 return log_error_errno(r
, "Unit '%s' masked, cannot edit.", *name
);
7688 log_info("Run 'systemctl edit%s --force --full %s' to create a new unit.",
7689 arg_scope
== UNIT_FILE_GLOBAL
? " --global" :
7690 arg_scope
== UNIT_FILE_USER
? " --user" : "",
7695 /* Create a new unit from scratch */
7697 r
= unit_file_create_new(&lp
, unit_name
,
7698 arg_full
? NULL
: ".d/override.conf",
7699 &new_path
, &tmp_path
);
7703 unit_name
= basename(path
);
7704 /* We follow unit aliases, but we need to propagate the instance */
7705 if (unit_name_is_valid(*name
, UNIT_NAME_INSTANCE
) &&
7706 unit_name_is_valid(unit_name
, UNIT_NAME_TEMPLATE
)) {
7707 _cleanup_free_
char *instance
= NULL
;
7709 r
= unit_name_to_instance(*name
, &instance
);
7713 r
= unit_name_replace_instance(unit_name
, instance
, &tmp_name
);
7717 unit_name
= tmp_name
;
7721 r
= unit_file_create_copy(&lp
, unit_name
, path
, &new_path
, &tmp_path
);
7723 r
= unit_file_create_new(&lp
, unit_name
, ".d/override.conf", &new_path
, &tmp_path
);
7728 r
= strv_push_pair(paths
, new_path
, tmp_path
);
7732 new_path
= tmp_path
= NULL
;
7738 static int edit(int argc
, char *argv
[], void *userdata
) {
7739 _cleanup_(lookup_paths_free
) LookupPaths lp
= {};
7740 _cleanup_strv_free_
char **names
= NULL
;
7741 _cleanup_strv_free_
char **paths
= NULL
;
7742 char **original
, **tmp
;
7747 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit units if not on a tty.");
7749 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
7750 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit units remotely.");
7752 r
= lookup_paths_init(&lp
, arg_scope
, 0, arg_root
);
7754 return log_error_errno(r
, "Failed to determine unit paths: %m");
7756 r
= acquire_bus(BUS_MANAGER
, &bus
);
7760 r
= expand_names(bus
, strv_skip(argv
, 1), NULL
, &names
, NULL
);
7762 return log_error_errno(r
, "Failed to expand names: %m");
7764 STRV_FOREACH(tmp
, names
) {
7765 r
= unit_is_masked(bus
, &lp
, *tmp
);
7769 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit %s: unit is masked.", *tmp
);
7772 r
= find_paths_to_edit(bus
, names
, &paths
);
7776 if (strv_isempty(paths
))
7779 r
= run_editor(paths
);
7783 STRV_FOREACH_PAIR(original
, tmp
, paths
) {
7784 /* If the temporary file is empty we ignore it.
7785 * This allows the user to cancel the modification.
7787 if (null_or_empty_path(*tmp
)) {
7788 log_warning("Editing \"%s\" canceled: temporary file is empty.", *original
);
7792 r
= rename(*tmp
, *original
);
7794 r
= log_error_errno(errno
, "Failed to rename \"%s\" to \"%s\": %m", *tmp
, *original
);
7801 if (!arg_no_reload
&& !install_client_side())
7802 r
= daemon_reload(argc
, argv
, userdata
);
7805 STRV_FOREACH_PAIR(original
, tmp
, paths
) {
7806 (void) unlink(*tmp
);
7808 /* Removing empty dropin dirs */
7810 _cleanup_free_
char *dir
;
7812 dir
= dirname_malloc(*original
);
7816 /* no need to check if the dir is empty, rmdir
7817 * does nothing if it is not the case.
7826 static int systemctl_help(void) {
7827 _cleanup_free_
char *link
= NULL
;
7830 (void) pager_open(arg_pager_flags
);
7832 r
= terminal_urlify_man("systemctl", "1", &link
);
7836 printf("%1$s [OPTIONS...] COMMAND ...\n\n"
7837 "%5$sQuery or send control commands to the system manager.%6$s\n"
7838 "\n%3$sUnit Commands:%4$s\n"
7839 " list-units [PATTERN...] List units currently in memory\n"
7840 " list-sockets [PATTERN...] List socket units currently in memory,\n"
7841 " ordered by address\n"
7842 " list-timers [PATTERN...] List timer units currently in memory,\n"
7843 " ordered by next elapse\n"
7844 " start UNIT... Start (activate) one or more units\n"
7845 " stop UNIT... Stop (deactivate) one or more units\n"
7846 " reload UNIT... Reload one or more units\n"
7847 " restart UNIT... Start or restart one or more units\n"
7848 " try-restart UNIT... Restart one or more units if active\n"
7849 " reload-or-restart UNIT... Reload one or more units if possible,\n"
7850 " otherwise start or restart\n"
7851 " try-reload-or-restart UNIT... If active, reload one or more units,\n"
7852 " if supported, otherwise restart\n"
7853 " isolate UNIT Start one unit and stop all others\n"
7854 " kill UNIT... Send signal to processes of a unit\n"
7855 " clean UNIT... Clean runtime, cache, state, logs or\n"
7856 " or configuration of unit\n"
7857 " is-active PATTERN... Check whether units are active\n"
7858 " is-failed PATTERN... Check whether units are failed\n"
7859 " status [PATTERN...|PID...] Show runtime status of one or more units\n"
7860 " show [PATTERN...|JOB...] Show properties of one or more\n"
7861 " units/jobs or the manager\n"
7862 " cat PATTERN... Show files and drop-ins of specified units\n"
7863 " set-property UNIT PROPERTY=VALUE... Sets one or more properties of a unit\n"
7864 " help PATTERN...|PID... Show manual for one or more units\n"
7865 " reset-failed [PATTERN...] Reset failed state for all, one, or more\n"
7867 " list-dependencies [UNIT] Recursively show units which are required\n"
7868 " or wanted by this unit or by which this\n"
7869 " unit is required or wanted"
7870 "\n%3$sUnit File Commands:%4$s\n"
7871 " list-unit-files [PATTERN...] List installed unit files\n"
7872 " enable [UNIT...|PATH...] Enable one or more unit files\n"
7873 " disable UNIT... Disable one or more unit files\n"
7874 " reenable UNIT... Reenable one or more unit files\n"
7875 " preset UNIT... Enable/disable one or more unit files\n"
7876 " based on preset configuration\n"
7877 " preset-all Enable/disable all unit files based on\n"
7878 " preset configuration\n"
7879 " is-enabled UNIT... Check whether unit files are enabled\n"
7880 " mask UNIT... Mask one or more units\n"
7881 " unmask UNIT... Unmask one or more units\n"
7882 " link PATH... Link one or more units files into\n"
7883 " the search path\n"
7884 " revert UNIT... Revert one or more unit files to vendor\n"
7886 " add-wants TARGET UNIT... Add 'Wants' dependency for the target\n"
7887 " on specified one or more units\n"
7888 " add-requires TARGET UNIT... Add 'Requires' dependency for the target\n"
7889 " on specified one or more units\n"
7890 " edit UNIT... Edit one or more unit files\n"
7891 " get-default Get the name of the default target\n"
7892 " set-default TARGET Set the default target\n"
7893 "\n%3$sMachine Commands:%4$s\n"
7894 " list-machines [PATTERN...] List local containers and host\n"
7895 "\n%3$sJob Commands:%4$s\n"
7896 " list-jobs [PATTERN...] List jobs\n"
7897 " cancel [JOB...] Cancel all, one, or more jobs\n"
7898 "\n%3$sEnvironment Commands:%4$s\n"
7899 " show-environment Dump environment\n"
7900 " set-environment VARIABLE=VALUE... Set one or more environment variables\n"
7901 " unset-environment VARIABLE... Unset one or more environment variables\n"
7902 " import-environment [VARIABLE...] Import all or some environment variables\n"
7903 "\n%3$sManager State Commands:%4$s\n"
7904 " daemon-reload Reload systemd manager configuration\n"
7905 " daemon-reexec Reexecute systemd manager\n"
7906 " log-level [LEVEL] Get/set logging threshold for manager\n"
7907 " log-target [TARGET] Get/set logging target for manager\n"
7908 " service-watchdogs [BOOL] Get/set service watchdog state\n"
7909 "\n%3$sSystem Commands:%4$s\n"
7910 " is-system-running Check whether system is fully running\n"
7911 " default Enter system default mode\n"
7912 " rescue Enter system rescue mode\n"
7913 " emergency Enter system emergency mode\n"
7914 " halt Shut down and halt the system\n"
7915 " poweroff Shut down and power-off the system\n"
7916 " reboot [ARG] Shut down and reboot the system\n"
7917 " kexec Shut down and reboot the system with kexec\n"
7918 " exit [EXIT_CODE] Request user instance or container exit\n"
7919 " switch-root ROOT [INIT] Change to a different root file system\n"
7920 " suspend Suspend the system\n"
7921 " hibernate Hibernate the system\n"
7922 " hybrid-sleep Hibernate and suspend the system\n"
7923 " suspend-then-hibernate Suspend the system, wake after a period of\n"
7924 " time, and hibernate"
7925 "\n%3$sOptions:%4$s\n"
7926 " -h --help Show this help\n"
7927 " --version Show package version\n"
7928 " --system Connect to system manager\n"
7929 " --user Connect to user service manager\n"
7930 " -H --host=[USER@]HOST Operate on remote host\n"
7931 " -M --machine=CONTAINER Operate on a local container\n"
7932 " -t --type=TYPE List units of a particular type\n"
7933 " --state=STATE List units with particular LOAD or SUB or ACTIVE state\n"
7934 " --failed Shorcut for --state=failed\n"
7935 " -p --property=NAME Show only properties by this name\n"
7936 " -a --all Show all properties/all units currently in memory,\n"
7937 " including dead/empty ones. To list all units installed\n"
7938 " on the system, use 'list-unit-files' instead.\n"
7939 " -l --full Don't ellipsize unit names on output\n"
7940 " -r --recursive Show unit list of host and local containers\n"
7941 " --reverse Show reverse dependencies with 'list-dependencies'\n"
7942 " --job-mode=MODE Specify how to deal with already queued jobs, when\n"
7943 " queueing a new job\n"
7944 " -T --show-transaction When enqueuing a unit job, show full transaction\n"
7945 " --show-types When showing sockets, explicitly show their type\n"
7946 " --value When showing properties, only print the value\n"
7947 " -i --ignore-inhibitors When shutting down or sleeping, ignore inhibitors\n"
7948 " --kill-who=WHO Whom to send signal to\n"
7949 " -s --signal=SIGNAL Which signal to send\n"
7950 " --what=RESOURCES Which types of resources to remove\n"
7951 " --now Start or stop unit after enabling or disabling it\n"
7952 " --dry-run Only print what would be done\n"
7953 " -q --quiet Suppress output\n"
7954 " --wait For (re)start, wait until service stopped again\n"
7955 " For is-system-running, wait until startup is completed\n"
7956 " --no-block Do not wait until operation finished\n"
7957 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7958 " --no-reload Don't reload daemon after en-/dis-abling unit files\n"
7959 " --no-legend Do not print a legend (column headers and hints)\n"
7960 " --no-pager Do not pipe output into a pager\n"
7961 " --no-ask-password Do not ask for system passwords\n"
7962 " --global Enable/disable/mask unit files globally\n"
7963 " --runtime Enable/disable/mask unit files temporarily until next\n"
7965 " -f --force When enabling unit files, override existing symlinks\n"
7966 " When shutting down, execute action immediately\n"
7967 " --preset-mode= Apply only enable, only disable, or all presets\n"
7968 " --root=PATH Enable/disable/mask unit files in the specified root\n"
7970 " -n --lines=INTEGER Number of journal entries to show\n"
7971 " -o --output=STRING Change journal output mode (short, short-precise,\n"
7972 " short-iso, short-iso-precise, short-full,\n"
7973 " short-monotonic, short-unix,\n"
7974 " verbose, export, json, json-pretty, json-sse, cat)\n"
7975 " --firmware-setup Tell the firmware to show the setup menu on next boot\n"
7976 " --boot-loader-menu=TIME\n"
7977 " Boot into boot loader menu on next boot\n"
7978 " --boot-loader-entry=NAME\n"
7979 " Boot into a specific boot loader entry on next boot\n"
7980 " --plain Print unit dependencies as a list instead of a tree\n"
7981 "\nSee the %2$s for details.\n"
7982 , program_invocation_short_name
7984 , ansi_underline(), ansi_normal()
7985 , ansi_highlight(), ansi_normal()
7991 static int halt_help(void) {
7992 _cleanup_free_
char *link
= NULL
;
7995 r
= terminal_urlify_man("halt", "8", &link
);
7999 printf("%s [OPTIONS...]%s\n"
8000 "\n%s%s the system.%s\n"
8002 " --help Show this help\n"
8003 " --halt Halt the machine\n"
8004 " -p --poweroff Switch off the machine\n"
8005 " --reboot Reboot the machine\n"
8006 " -f --force Force immediate halt/power-off/reboot\n"
8007 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
8008 " -d --no-wtmp Don't write wtmp record\n"
8009 " --no-wall Don't send wall message before halt/power-off/reboot\n"
8010 "\nSee the %s for details.\n"
8011 , program_invocation_short_name
8012 , arg_action
== ACTION_REBOOT
? " [ARG]" : ""
8014 , arg_action
== ACTION_REBOOT
? "Reboot" :
8015 arg_action
== ACTION_POWEROFF
? "Power off" :
8024 static int shutdown_help(void) {
8025 _cleanup_free_
char *link
= NULL
;
8028 r
= terminal_urlify_man("shutdown", "8", &link
);
8032 printf("%s [OPTIONS...] [TIME] [WALL...]\n"
8033 "\n%sShut down the system.%s\n"
8035 " --help Show this help\n"
8036 " -H --halt Halt the machine\n"
8037 " -P --poweroff Power-off the machine\n"
8038 " -r --reboot Reboot the machine\n"
8039 " -h Equivalent to --poweroff, overridden by --halt\n"
8040 " -k Don't halt/power-off/reboot, just send warnings\n"
8041 " --no-wall Don't send wall message before halt/power-off/reboot\n"
8042 " -c Cancel a pending shutdown\n"
8043 "\nSee the %s for details.\n"
8044 , program_invocation_short_name
8045 , ansi_highlight(), ansi_normal()
8052 static int telinit_help(void) {
8053 _cleanup_free_
char *link
= NULL
;
8056 r
= terminal_urlify_man("telinit", "8", &link
);
8060 printf("%s [OPTIONS...] COMMAND\n\n"
8061 "%sSend control commands to the init daemon.%s\n"
8063 " 0 Power-off the machine\n"
8064 " 6 Reboot the machine\n"
8065 " 2, 3, 4, 5 Start runlevelX.target unit\n"
8066 " 1, s, S Enter rescue mode\n"
8067 " q, Q Reload init daemon configuration\n"
8068 " u, U Reexecute init daemon\n"
8070 " --help Show this help\n"
8071 " --no-wall Don't send wall message before halt/power-off/reboot\n"
8072 "\nSee the %s for details.\n"
8073 , program_invocation_short_name
8074 , ansi_highlight(), ansi_normal()
8081 static int runlevel_help(void) {
8082 _cleanup_free_
char *link
= NULL
;
8085 r
= terminal_urlify_man("runlevel", "8", &link
);
8089 printf("%s [OPTIONS...]\n"
8090 "\n%sPrints the previous and current runlevel of the init system.%s\n"
8092 " --help Show this help\n"
8093 "\nSee the %s for details.\n"
8094 , program_invocation_short_name
8095 , ansi_highlight(), ansi_normal()
8102 static void help_types(void) {
8104 puts("Available unit types:");
8106 DUMP_STRING_TABLE(unit_type
, UnitType
, _UNIT_TYPE_MAX
);
8109 static void help_states(void) {
8111 puts("Available unit load states:");
8112 DUMP_STRING_TABLE(unit_load_state
, UnitLoadState
, _UNIT_LOAD_STATE_MAX
);
8115 puts("\nAvailable unit active states:");
8116 DUMP_STRING_TABLE(unit_active_state
, UnitActiveState
, _UNIT_ACTIVE_STATE_MAX
);
8119 puts("\nAvailable unit file states:");
8120 DUMP_STRING_TABLE(unit_file_state
, UnitFileState
, _UNIT_FILE_STATE_MAX
);
8123 puts("\nAvailable automount unit substates:");
8124 DUMP_STRING_TABLE(automount_state
, AutomountState
, _AUTOMOUNT_STATE_MAX
);
8127 puts("\nAvailable device unit substates:");
8128 DUMP_STRING_TABLE(device_state
, DeviceState
, _DEVICE_STATE_MAX
);
8131 puts("\nAvailable mount unit substates:");
8132 DUMP_STRING_TABLE(mount_state
, MountState
, _MOUNT_STATE_MAX
);
8135 puts("\nAvailable path unit substates:");
8136 DUMP_STRING_TABLE(path_state
, PathState
, _PATH_STATE_MAX
);
8139 puts("\nAvailable scope unit substates:");
8140 DUMP_STRING_TABLE(scope_state
, ScopeState
, _SCOPE_STATE_MAX
);
8143 puts("\nAvailable service unit substates:");
8144 DUMP_STRING_TABLE(service_state
, ServiceState
, _SERVICE_STATE_MAX
);
8147 puts("\nAvailable slice unit substates:");
8148 DUMP_STRING_TABLE(slice_state
, SliceState
, _SLICE_STATE_MAX
);
8151 puts("\nAvailable socket unit substates:");
8152 DUMP_STRING_TABLE(socket_state
, SocketState
, _SOCKET_STATE_MAX
);
8155 puts("\nAvailable swap unit substates:");
8156 DUMP_STRING_TABLE(swap_state
, SwapState
, _SWAP_STATE_MAX
);
8159 puts("\nAvailable target unit substates:");
8160 DUMP_STRING_TABLE(target_state
, TargetState
, _TARGET_STATE_MAX
);
8163 puts("\nAvailable timer unit substates:");
8164 DUMP_STRING_TABLE(timer_state
, TimerState
, _TIMER_STATE_MAX
);
8167 static int help_boot_loader_entry(void) {
8168 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
8169 _cleanup_strv_free_
char **l
= NULL
;
8174 r
= acquire_bus(BUS_FULL
, &bus
);
8178 r
= sd_bus_get_property_strv(
8180 "org.freedesktop.login1",
8181 "/org/freedesktop/login1",
8182 "org.freedesktop.login1.Manager",
8183 "BootLoaderEntries",
8187 return log_error_errno(r
, "Failed to enumerate boot loader entries: %s", bus_error_message(&error
, r
));
8189 if (strv_isempty(l
))
8190 return log_error_errno(SYNTHETIC_ERRNO(ENODATA
), "No boot loader entries discovered.");
8198 static int systemctl_parse_argv(int argc
, char *argv
[]) {
8207 ARG_IGNORE_DEPENDENCIES
,
8220 ARG_NO_ASK_PASSWORD
,
8228 ARG_BOOT_LOADER_MENU
,
8229 ARG_BOOT_LOADER_ENTRY
,
8236 static const struct option options
[] = {
8237 { "help", no_argument
, NULL
, 'h' },
8238 { "version", no_argument
, NULL
, ARG_VERSION
},
8239 { "type", required_argument
, NULL
, 't' },
8240 { "property", required_argument
, NULL
, 'p' },
8241 { "all", no_argument
, NULL
, 'a' },
8242 { "reverse", no_argument
, NULL
, ARG_REVERSE
},
8243 { "after", no_argument
, NULL
, ARG_AFTER
},
8244 { "before", no_argument
, NULL
, ARG_BEFORE
},
8245 { "show-types", no_argument
, NULL
, ARG_SHOW_TYPES
},
8246 { "failed", no_argument
, NULL
, ARG_FAILED
}, /* compatibility only */
8247 { "full", no_argument
, NULL
, 'l' },
8248 { "job-mode", required_argument
, NULL
, ARG_JOB_MODE
},
8249 { "fail", no_argument
, NULL
, ARG_FAIL
}, /* compatibility only */
8250 { "irreversible", no_argument
, NULL
, ARG_IRREVERSIBLE
}, /* compatibility only */
8251 { "ignore-dependencies", no_argument
, NULL
, ARG_IGNORE_DEPENDENCIES
}, /* compatibility only */
8252 { "ignore-inhibitors", no_argument
, NULL
, 'i' },
8253 { "value", no_argument
, NULL
, ARG_VALUE
},
8254 { "user", no_argument
, NULL
, ARG_USER
},
8255 { "system", no_argument
, NULL
, ARG_SYSTEM
},
8256 { "global", no_argument
, NULL
, ARG_GLOBAL
},
8257 { "wait", no_argument
, NULL
, ARG_WAIT
},
8258 { "no-block", no_argument
, NULL
, ARG_NO_BLOCK
},
8259 { "no-legend", no_argument
, NULL
, ARG_NO_LEGEND
},
8260 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
8261 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8262 { "dry-run", no_argument
, NULL
, ARG_DRY_RUN
},
8263 { "quiet", no_argument
, NULL
, 'q' },
8264 { "root", required_argument
, NULL
, ARG_ROOT
},
8265 { "force", no_argument
, NULL
, 'f' },
8266 { "no-reload", no_argument
, NULL
, ARG_NO_RELOAD
},
8267 { "kill-who", required_argument
, NULL
, ARG_KILL_WHO
},
8268 { "signal", required_argument
, NULL
, 's' },
8269 { "no-ask-password", no_argument
, NULL
, ARG_NO_ASK_PASSWORD
},
8270 { "host", required_argument
, NULL
, 'H' },
8271 { "machine", required_argument
, NULL
, 'M' },
8272 { "runtime", no_argument
, NULL
, ARG_RUNTIME
},
8273 { "lines", required_argument
, NULL
, 'n' },
8274 { "output", required_argument
, NULL
, 'o' },
8275 { "plain", no_argument
, NULL
, ARG_PLAIN
},
8276 { "state", required_argument
, NULL
, ARG_STATE
},
8277 { "recursive", no_argument
, NULL
, 'r' },
8278 { "preset-mode", required_argument
, NULL
, ARG_PRESET_MODE
},
8279 { "firmware-setup", no_argument
, NULL
, ARG_FIRMWARE_SETUP
},
8280 { "boot-loader-menu", required_argument
, NULL
, ARG_BOOT_LOADER_MENU
},
8281 { "boot-loader-entry", required_argument
, NULL
, ARG_BOOT_LOADER_ENTRY
},
8282 { "now", no_argument
, NULL
, ARG_NOW
},
8283 { "message", required_argument
, NULL
, ARG_MESSAGE
},
8284 { "show-transaction", no_argument
, NULL
, 'T' },
8285 { "what", required_argument
, NULL
, ARG_WHAT
},
8294 /* we default to allowing interactive authorization only in systemctl (not in the legacy commands) */
8295 arg_ask_password
= true;
8297 while ((c
= getopt_long(argc
, argv
, "ht:p:alqfs:H:M:n:o:iTr.::", options
, NULL
)) >= 0)
8302 return systemctl_help();
8310 if (isempty(optarg
))
8311 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8312 "--type= requires arguments.");
8314 for (p
= optarg
;;) {
8315 _cleanup_free_
char *type
= NULL
;
8317 r
= extract_first_word(&p
, &type
, ",", 0);
8319 return log_error_errno(r
, "Failed to parse type: %s", optarg
);
8323 if (streq(type
, "help")) {
8328 if (unit_type_from_string(type
) >= 0) {
8329 if (strv_consume(&arg_types
, TAKE_PTR(type
)) < 0)
8334 /* It's much nicer to use --state= for
8335 * load states, but let's support this
8336 * in --types= too for compatibility
8337 * with old versions */
8338 if (unit_load_state_from_string(type
) >= 0) {
8339 if (strv_consume(&arg_states
, TAKE_PTR(type
)) < 0)
8344 log_error("Unknown unit type or load state '%s'.", type
);
8345 return log_info_errno(SYNTHETIC_ERRNO(EINVAL
),
8346 "Use -t help to see a list of allowed values.");
8353 /* Make sure that if the empty property list was specified, we won't show any
8355 if (isempty(optarg
) && !arg_properties
) {
8356 arg_properties
= new0(char*, 1);
8357 if (!arg_properties
)
8362 for (p
= optarg
;;) {
8363 _cleanup_free_
char *prop
= NULL
;
8365 r
= extract_first_word(&p
, &prop
, ",", 0);
8367 return log_error_errno(r
, "Failed to parse property: %s", optarg
);
8371 if (strv_consume(&arg_properties
, TAKE_PTR(prop
)) < 0)
8376 /* If the user asked for a particular
8377 * property, show it to him, even if it is
8388 arg_dependency
= DEPENDENCY_REVERSE
;
8392 arg_dependency
= DEPENDENCY_AFTER
;
8393 arg_jobs_after
= true;
8397 arg_dependency
= DEPENDENCY_BEFORE
;
8398 arg_jobs_before
= true;
8401 case ARG_SHOW_TYPES
:
8402 arg_show_types
= true;
8410 arg_job_mode
= optarg
;
8414 arg_job_mode
= "fail";
8417 case ARG_IRREVERSIBLE
:
8418 arg_job_mode
= "replace-irreversibly";
8421 case ARG_IGNORE_DEPENDENCIES
:
8422 arg_job_mode
= "ignore-dependencies";
8426 arg_scope
= UNIT_FILE_USER
;
8430 arg_scope
= UNIT_FILE_SYSTEM
;
8434 arg_scope
= UNIT_FILE_GLOBAL
;
8442 arg_no_block
= true;
8446 arg_no_legend
= true;
8450 arg_pager_flags
|= PAGER_DISABLE
;
8458 r
= parse_path_argument_and_warn(optarg
, false, &arg_root
);
8468 if (strv_extend(&arg_states
, "failed") < 0)
8486 arg_no_reload
= true;
8490 arg_kill_who
= optarg
;
8494 if (streq(optarg
, "help")) {
8495 DUMP_STRING_TABLE(signal
, int, _NSIG
);
8499 arg_signal
= signal_from_string(optarg
);
8501 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8502 "Failed to parse signal string %s.",
8506 case ARG_NO_ASK_PASSWORD
:
8507 arg_ask_password
= false;
8511 arg_transport
= BUS_TRANSPORT_REMOTE
;
8516 arg_transport
= BUS_TRANSPORT_MACHINE
;
8525 if (safe_atou(optarg
, &arg_lines
) < 0)
8526 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8527 "Failed to parse lines '%s'",
8532 if (streq(optarg
, "help")) {
8533 DUMP_STRING_TABLE(output_mode
, OutputMode
, _OUTPUT_MODE_MAX
);
8537 arg_output
= output_mode_from_string(optarg
);
8539 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8540 "Unknown output '%s'.",
8545 arg_ignore_inhibitors
= true;
8552 case ARG_FIRMWARE_SETUP
:
8553 arg_firmware_setup
= true;
8556 case ARG_BOOT_LOADER_MENU
:
8558 r
= parse_sec(optarg
, &arg_boot_loader_menu
);
8560 return log_error_errno(r
, "Failed to parse --boot-loader-menu= argument '%s': %m", optarg
);
8564 case ARG_BOOT_LOADER_ENTRY
:
8566 if (streq(optarg
, "help")) { /* Yes, this means, "help" is not a valid boot loader entry name we can deal with */
8567 r
= help_boot_loader_entry();
8574 arg_boot_loader_entry
= empty_to_null(optarg
);
8580 if (isempty(optarg
))
8581 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8582 "--state= requires arguments.");
8584 for (p
= optarg
;;) {
8585 _cleanup_free_
char *s
= NULL
;
8587 r
= extract_first_word(&p
, &s
, ",", 0);
8589 return log_error_errno(r
, "Failed to parse state: %s", optarg
);
8593 if (streq(s
, "help")) {
8598 if (strv_consume(&arg_states
, TAKE_PTR(s
)) < 0)
8606 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
8607 "--recursive requires root privileges.");
8609 arg_recursive
= true;
8612 case ARG_PRESET_MODE
:
8613 if (streq(optarg
, "help")) {
8614 DUMP_STRING_TABLE(unit_file_preset_mode
, UnitFilePresetMode
, _UNIT_FILE_PRESET_MAX
);
8618 arg_preset_mode
= unit_file_preset_mode_from_string(optarg
);
8619 if (arg_preset_mode
< 0)
8620 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8621 "Failed to parse preset mode: %s.", optarg
);
8630 if (strv_extend(&arg_wall
, optarg
) < 0)
8635 arg_show_transaction
= true;
8641 if (isempty(optarg
))
8642 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "--what= requires arguments.");
8644 for (p
= optarg
;;) {
8645 _cleanup_free_
char *k
= NULL
;
8647 r
= extract_first_word(&p
, &k
, ",", 0);
8649 return log_error_errno(r
, "Failed to parse directory type: %s", optarg
);
8653 if (streq(k
, "help")) {
8662 r
= strv_consume(&arg_clean_what
, TAKE_PTR(k
));
8671 /* Output an error mimicking getopt, and print a hint afterwards */
8672 log_error("%s: invalid option -- '.'", program_invocation_name
);
8673 log_notice("Hint: to specify units starting with a dash, use \"--\":\n"
8674 " %s [OPTIONS...] COMMAND -- -.%s ...",
8675 program_invocation_name
, optarg
?: "mount");
8682 assert_not_reached("Unhandled option");
8685 if (arg_transport
!= BUS_TRANSPORT_LOCAL
&& arg_scope
!= UNIT_FILE_SYSTEM
)
8686 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8687 "Cannot access user instance remotely.");
8689 if (arg_wait
&& arg_no_block
)
8690 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8691 "--wait may not be combined with --no-block.");
8696 static int halt_parse_argv(int argc
, char *argv
[]) {
8704 static const struct option options
[] = {
8705 { "help", no_argument
, NULL
, ARG_HELP
},
8706 { "halt", no_argument
, NULL
, ARG_HALT
},
8707 { "poweroff", no_argument
, NULL
, 'p' },
8708 { "reboot", no_argument
, NULL
, ARG_REBOOT
},
8709 { "force", no_argument
, NULL
, 'f' },
8710 { "wtmp-only", no_argument
, NULL
, 'w' },
8711 { "no-wtmp", no_argument
, NULL
, 'd' },
8712 { "no-sync", no_argument
, NULL
, 'n' },
8713 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8722 if (utmp_get_runlevel(&runlevel
, NULL
) >= 0)
8723 if (IN_SET(runlevel
, '0', '6'))
8726 while ((c
= getopt_long(argc
, argv
, "pfwdnih", options
, NULL
)) >= 0)
8733 arg_action
= ACTION_HALT
;
8737 if (arg_action
!= ACTION_REBOOT
)
8738 arg_action
= ACTION_POWEROFF
;
8742 arg_action
= ACTION_REBOOT
;
8767 /* Compatibility nops */
8774 assert_not_reached("Unhandled option");
8777 if (arg_action
== ACTION_REBOOT
&& (argc
== optind
|| argc
== optind
+ 1)) {
8778 r
= update_reboot_parameter_and_warn(argc
== optind
+ 1 ? argv
[optind
] : NULL
, false);
8781 } else if (optind
< argc
)
8782 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8783 "Too many arguments.");
8788 static int shutdown_parse_argv(int argc
, char *argv
[]) {
8794 static const struct option options
[] = {
8795 { "help", no_argument
, NULL
, ARG_HELP
},
8796 { "halt", no_argument
, NULL
, 'H' },
8797 { "poweroff", no_argument
, NULL
, 'P' },
8798 { "reboot", no_argument
, NULL
, 'r' },
8799 { "kexec", no_argument
, NULL
, 'K' }, /* not documented extension */
8800 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8810 while ((c
= getopt_long(argc
, argv
, "HPrhkKat:fFc", options
, NULL
)) >= 0)
8814 return shutdown_help();
8817 arg_action
= ACTION_HALT
;
8821 arg_action
= ACTION_POWEROFF
;
8826 arg_action
= ACTION_KEXEC
;
8828 arg_action
= ACTION_REBOOT
;
8832 arg_action
= ACTION_KEXEC
;
8836 if (arg_action
!= ACTION_HALT
)
8837 arg_action
= ACTION_POWEROFF
;
8849 case 't': /* Note that we also ignore any passed argument to -t, not just the -t itself */
8852 /* Compatibility nops */
8856 arg_action
= ACTION_CANCEL_SHUTDOWN
;
8863 assert_not_reached("Unhandled option");
8866 if (argc
> optind
&& arg_action
!= ACTION_CANCEL_SHUTDOWN
) {
8867 r
= parse_shutdown_time_spec(argv
[optind
], &arg_when
);
8869 log_error("Failed to parse time specification: %s", argv
[optind
]);
8873 arg_when
= now(CLOCK_REALTIME
) + USEC_PER_MINUTE
;
8875 if (argc
> optind
&& arg_action
== ACTION_CANCEL_SHUTDOWN
)
8876 /* No time argument for shutdown cancel */
8877 wall
= argv
+ optind
;
8878 else if (argc
> optind
+ 1)
8879 /* We skip the time argument */
8880 wall
= argv
+ optind
+ 1;
8883 arg_wall
= strv_copy(wall
);
8893 static int telinit_parse_argv(int argc
, char *argv
[]) {
8899 static const struct option options
[] = {
8900 { "help", no_argument
, NULL
, ARG_HELP
},
8901 { "no-wall", no_argument
, NULL
, ARG_NO_WALL
},
8905 static const struct {
8909 { '0', ACTION_POWEROFF
},
8910 { '6', ACTION_REBOOT
},
8911 { '1', ACTION_RESCUE
},
8912 { '2', ACTION_RUNLEVEL2
},
8913 { '3', ACTION_RUNLEVEL3
},
8914 { '4', ACTION_RUNLEVEL4
},
8915 { '5', ACTION_RUNLEVEL5
},
8916 { 's', ACTION_RESCUE
},
8917 { 'S', ACTION_RESCUE
},
8918 { 'q', ACTION_RELOAD
},
8919 { 'Q', ACTION_RELOAD
},
8920 { 'u', ACTION_REEXEC
},
8921 { 'U', ACTION_REEXEC
}
8930 while ((c
= getopt_long(argc
, argv
, "", options
, NULL
)) >= 0)
8934 return telinit_help();
8944 assert_not_reached("Unhandled option");
8948 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8949 "%s: required argument missing.",
8950 program_invocation_short_name
);
8952 if (optind
+ 1 < argc
)
8953 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8954 "Too many arguments.");
8956 if (strlen(argv
[optind
]) != 1)
8957 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8958 "Expected single character argument.");
8960 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
8961 if (table
[i
].from
== argv
[optind
][0])
8964 if (i
>= ELEMENTSOF(table
))
8965 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
8966 "Unknown command '%s'.", argv
[optind
]);
8968 arg_action
= table
[i
].to
;
8975 static int runlevel_parse_argv(int argc
, char *argv
[]) {
8980 static const struct option options
[] = {
8981 { "help", no_argument
, NULL
, ARG_HELP
},
8990 while ((c
= getopt_long(argc
, argv
, "", options
, NULL
)) >= 0)
8994 return runlevel_help();
9000 assert_not_reached("Unhandled option");
9004 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
9005 "Too many arguments.");
9010 static int parse_argv(int argc
, char *argv
[]) {
9014 if (program_invocation_short_name
) {
9016 if (strstr(program_invocation_short_name
, "halt")) {
9017 arg_action
= ACTION_HALT
;
9018 return halt_parse_argv(argc
, argv
);
9020 } else if (strstr(program_invocation_short_name
, "poweroff")) {
9021 arg_action
= ACTION_POWEROFF
;
9022 return halt_parse_argv(argc
, argv
);
9024 } else if (strstr(program_invocation_short_name
, "reboot")) {
9026 arg_action
= ACTION_KEXEC
;
9028 arg_action
= ACTION_REBOOT
;
9029 return halt_parse_argv(argc
, argv
);
9031 } else if (strstr(program_invocation_short_name
, "shutdown")) {
9032 arg_action
= ACTION_POWEROFF
;
9033 return shutdown_parse_argv(argc
, argv
);
9035 } else if (strstr(program_invocation_short_name
, "init")) {
9037 /* Matches invocations as "init" as well as "telinit", which are synonymous when run as PID !=
9040 * On SysV "telinit" was the official command to communicate with PID 1, but "init" would
9041 * redirect itself to "telinit" if called with PID != 1. We follow the same logic here still,
9042 * though we add one level of indirection, as we implement "telinit" in "systemctl". Hence, for
9043 * us if you invoke "init" you get "systemd", but it will execve() "systemctl" immediately with
9044 * argv[] unmodified if PID is != 1. If you invoke "telinit" you directly get "systemctl". In
9045 * both cases we shall do the same thing, which is why we do strstr(p_i_s_n, "init") here, as a
9046 * quick way to match both.
9048 * Also see redirect_telinit() in src/core/main.c. */
9050 if (sd_booted() > 0) {
9051 arg_action
= _ACTION_INVALID
;
9052 return telinit_parse_argv(argc
, argv
);
9054 /* Hmm, so some other init system is running, we need to forward this request to
9055 * it. For now we simply guess that it is Upstart. */
9057 (void) rlimit_nofile_safe();
9058 execv(TELINIT
, argv
);
9060 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
9061 "Couldn't find an alternative telinit implementation to spawn.");
9064 } else if (strstr(program_invocation_short_name
, "runlevel")) {
9065 arg_action
= ACTION_RUNLEVEL
;
9066 return runlevel_parse_argv(argc
, argv
);
9070 arg_action
= ACTION_SYSTEMCTL
;
9071 return systemctl_parse_argv(argc
, argv
);
9074 #if HAVE_SYSV_COMPAT
9075 _pure_
static int action_to_runlevel(void) {
9076 static const char table
[_ACTION_MAX
] = {
9077 [ACTION_HALT
] = '0',
9078 [ACTION_POWEROFF
] = '0',
9079 [ACTION_REBOOT
] = '6',
9080 [ACTION_RUNLEVEL2
] = '2',
9081 [ACTION_RUNLEVEL3
] = '3',
9082 [ACTION_RUNLEVEL4
] = '4',
9083 [ACTION_RUNLEVEL5
] = '5',
9084 [ACTION_RESCUE
] = '1'
9087 assert(arg_action
>= 0 && arg_action
< _ACTION_MAX
);
9088 return table
[arg_action
];
9092 static int systemctl_main(int argc
, char *argv
[]) {
9093 static const Verb verbs
[] = {
9094 { "list-units", VERB_ANY
, VERB_ANY
, VERB_DEFAULT
|VERB_ONLINE_ONLY
, list_units
},
9095 { "list-unit-files", VERB_ANY
, VERB_ANY
, 0, list_unit_files
},
9096 { "list-sockets", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_sockets
},
9097 { "list-timers", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_timers
},
9098 { "list-jobs", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_jobs
},
9099 { "list-machines", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, list_machines
},
9100 { "clear-jobs", VERB_ANY
, 1, VERB_ONLINE_ONLY
, trivial_method
},
9101 { "cancel", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, cancel_job
},
9102 { "start", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9103 { "stop", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9104 { "condstop", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with ALTLinux */
9105 { "reload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9106 { "restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9107 { "try-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9108 { "reload-or-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9109 { "reload-or-try-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with old systemctl <= 228 */
9110 { "try-reload-or-restart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
},
9111 { "force-reload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with SysV */
9112 { "condreload", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with ALTLinux */
9113 { "condrestart", 2, VERB_ANY
, VERB_ONLINE_ONLY
, start_unit
}, /* For compatibility with RH */
9114 { "isolate", 2, 2, VERB_ONLINE_ONLY
, start_unit
},
9115 { "kill", 2, VERB_ANY
, VERB_ONLINE_ONLY
, kill_unit
},
9116 { "clean", 2, VERB_ANY
, VERB_ONLINE_ONLY
, clean_unit
},
9117 { "is-active", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_active
},
9118 { "check", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_active
}, /* deprecated alias of is-active */
9119 { "is-failed", 2, VERB_ANY
, VERB_ONLINE_ONLY
, check_unit_failed
},
9120 { "show", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
9121 { "cat", 2, VERB_ANY
, VERB_ONLINE_ONLY
, cat
},
9122 { "status", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
9123 { "help", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, show
},
9124 { "daemon-reload", VERB_ANY
, 1, VERB_ONLINE_ONLY
, daemon_reload
},
9125 { "daemon-reexec", VERB_ANY
, 1, VERB_ONLINE_ONLY
, daemon_reload
},
9126 { "log-level", VERB_ANY
, 2, 0, log_level
},
9127 { "log-target", VERB_ANY
, 2, 0, log_target
},
9128 { "service-watchdogs", VERB_ANY
, 2, 0, service_watchdogs
},
9129 { "show-environment", VERB_ANY
, 1, VERB_ONLINE_ONLY
, show_environment
},
9130 { "set-environment", 2, VERB_ANY
, VERB_ONLINE_ONLY
, set_environment
},
9131 { "unset-environment", 2, VERB_ANY
, VERB_ONLINE_ONLY
, set_environment
},
9132 { "import-environment", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, import_environment
},
9133 { "halt", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9134 { "poweroff", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9135 { "reboot", VERB_ANY
, 2, VERB_ONLINE_ONLY
, start_system_special
},
9136 { "kexec", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9137 { "suspend", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9138 { "hibernate", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9139 { "hybrid-sleep", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9140 { "suspend-then-hibernate",VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9141 { "default", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_special
},
9142 { "rescue", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9143 { "emergency", VERB_ANY
, 1, VERB_ONLINE_ONLY
, start_system_special
},
9144 { "exit", VERB_ANY
, 2, VERB_ONLINE_ONLY
, start_special
},
9145 { "reset-failed", VERB_ANY
, VERB_ANY
, VERB_ONLINE_ONLY
, reset_failed
},
9146 { "enable", 2, VERB_ANY
, 0, enable_unit
},
9147 { "disable", 2, VERB_ANY
, 0, enable_unit
},
9148 { "is-enabled", 2, VERB_ANY
, 0, unit_is_enabled
},
9149 { "reenable", 2, VERB_ANY
, 0, enable_unit
},
9150 { "preset", 2, VERB_ANY
, 0, enable_unit
},
9151 { "preset-all", VERB_ANY
, 1, 0, preset_all
},
9152 { "mask", 2, VERB_ANY
, 0, enable_unit
},
9153 { "unmask", 2, VERB_ANY
, 0, enable_unit
},
9154 { "link", 2, VERB_ANY
, 0, enable_unit
},
9155 { "revert", 2, VERB_ANY
, 0, enable_unit
},
9156 { "switch-root", 2, VERB_ANY
, VERB_ONLINE_ONLY
, switch_root
},
9157 { "list-dependencies", VERB_ANY
, 2, VERB_ONLINE_ONLY
, list_dependencies
},
9158 { "set-default", 2, 2, 0, set_default
},
9159 { "get-default", VERB_ANY
, 1, 0, get_default
},
9160 { "set-property", 3, VERB_ANY
, VERB_ONLINE_ONLY
, set_property
},
9161 { "is-system-running", VERB_ANY
, 1, 0, is_system_running
},
9162 { "add-wants", 3, VERB_ANY
, 0, add_dependency
},
9163 { "add-requires", 3, VERB_ANY
, 0, add_dependency
},
9164 { "edit", 2, VERB_ANY
, VERB_ONLINE_ONLY
, edit
},
9168 return dispatch_verb(argc
, argv
, verbs
, NULL
);
9171 static int reload_with_fallback(void) {
9172 /* First, try systemd via D-Bus. */
9173 if (daemon_reload(0, NULL
, NULL
) >= 0)
9176 /* Nothing else worked, so let's try signals */
9177 assert(IN_SET(arg_action
, ACTION_RELOAD
, ACTION_REEXEC
));
9179 if (kill(1, arg_action
== ACTION_RELOAD
? SIGHUP
: SIGTERM
) < 0)
9180 return log_error_errno(errno
, "kill() failed: %m");
9185 static int start_with_fallback(void) {
9186 /* First, try systemd via D-Bus. */
9187 if (start_unit(0, NULL
, NULL
) == 0)
9190 #if HAVE_SYSV_COMPAT
9191 /* Nothing else worked, so let's try /dev/initctl */
9192 if (talk_initctl(action_to_runlevel()) > 0)
9196 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
9197 "Failed to talk to init daemon.");
9200 static int halt_now(enum action a
) {
9201 /* The kernel will automatically flush ATA disks and suchlike on reboot(), but the file systems need to be
9202 * synced explicitly in advance. */
9203 if (!arg_no_sync
&& !arg_dry_run
)
9206 /* Make sure C-A-D is handled by the kernel from this point on... */
9208 (void) reboot(RB_ENABLE_CAD
);
9214 log_info("Halting.");
9217 (void) reboot(RB_HALT_SYSTEM
);
9220 case ACTION_POWEROFF
:
9222 log_info("Powering off.");
9225 (void) reboot(RB_POWER_OFF
);
9230 return reboot_with_parameter(REBOOT_FALLBACK
|
9231 (arg_quiet
? 0 : REBOOT_LOG
) |
9232 (arg_dry_run
? REBOOT_DRY_RUN
: 0));
9235 assert_not_reached("Unknown action.");
9239 static int logind_schedule_shutdown(void) {
9242 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
9243 char date
[FORMAT_TIMESTAMP_MAX
];
9248 r
= acquire_bus(BUS_FULL
, &bus
);
9252 switch (arg_action
) {
9256 case ACTION_POWEROFF
:
9257 action
= "poweroff";
9272 action
= strjoina("dry-", action
);
9274 (void) logind_set_wall_message();
9276 r
= sd_bus_call_method(
9278 "org.freedesktop.login1",
9279 "/org/freedesktop/login1",
9280 "org.freedesktop.login1.Manager",
9288 return log_warning_errno(r
, "Failed to call ScheduleShutdown in logind, proceeding with immediate shutdown: %s", bus_error_message(&error
, r
));
9291 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.", format_timestamp(date
, sizeof(date
), arg_when
));
9294 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
9295 "Cannot schedule shutdown without logind support, proceeding with immediate shutdown.");
9299 static int halt_main(void) {
9302 r
= logind_check_inhibitors(arg_action
);
9306 /* Delayed shutdown requested, and was successful */
9307 if (arg_when
> 0 && logind_schedule_shutdown() == 0)
9309 /* no delay, or logind failed or is not at all available */
9311 if (geteuid() != 0) {
9312 if (arg_dry_run
|| arg_force
> 0) {
9313 (void) must_be_root();
9317 /* Try logind if we are a normal user and no special
9318 * mode applies. Maybe polkit allows us to shutdown
9320 if (IN_SET(arg_action
, ACTION_POWEROFF
, ACTION_REBOOT
, ACTION_HALT
)) {
9321 r
= logind_reboot(arg_action
);
9324 if (IN_SET(r
, -EOPNOTSUPP
, -EINPROGRESS
))
9325 /* requested operation is not
9326 * supported on the local system or
9327 * already in progress */
9329 /* on all other errors, try low-level operation */
9333 /* In order to minimize the difference between operation with and
9334 * without logind, we explicitly enable non-blocking mode for this,
9335 * as logind's shutdown operations are always non-blocking. */
9336 arg_no_block
= true;
9338 if (!arg_dry_run
&& !arg_force
)
9339 return start_with_fallback();
9341 assert(geteuid() == 0);
9344 if (sd_booted() > 0)
9345 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
9347 r
= utmp_put_shutdown();
9349 log_warning_errno(r
, "Failed to write utmp record: %m");
9356 r
= halt_now(arg_action
);
9357 return log_error_errno(r
, "Failed to reboot: %m");
9360 static int runlevel_main(void) {
9361 int r
, runlevel
, previous
;
9363 r
= utmp_get_runlevel(&runlevel
, &previous
);
9370 previous
<= 0 ? 'N' : previous
,
9371 runlevel
<= 0 ? 'N' : runlevel
);
9376 static int logind_cancel_shutdown(void) {
9378 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
9382 r
= acquire_bus(BUS_FULL
, &bus
);
9386 (void) logind_set_wall_message();
9388 r
= sd_bus_call_method(
9390 "org.freedesktop.login1",
9391 "/org/freedesktop/login1",
9392 "org.freedesktop.login1.Manager",
9393 "CancelScheduledShutdown",
9397 return log_warning_errno(r
, "Failed to talk to logind, shutdown hasn't been cancelled: %s", bus_error_message(&error
, r
));
9401 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
9402 "Not compiled with logind support, cannot cancel scheduled shutdowns.");
9406 static int run(int argc
, char *argv
[]) {
9409 setlocale(LC_ALL
, "");
9410 log_parse_environment();
9413 /* The journal merging logic potentially needs a lot of fds. */
9414 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE
);
9418 /* Explicitly not on_tty() to avoid setting cached value.
9419 * This becomes relevant for piping output which might be
9421 original_stdout_is_tty
= isatty(STDOUT_FILENO
);
9423 r
= parse_argv(argc
, argv
);
9427 if (arg_action
!= ACTION_SYSTEMCTL
&& running_in_chroot() > 0) {
9429 log_info("Running in chroot, ignoring request.");
9434 /* systemctl_main() will print an error message for the bus
9435 * connection, but only if it needs to */
9437 switch (arg_action
) {
9439 case ACTION_SYSTEMCTL
:
9440 r
= systemctl_main(argc
, argv
);
9443 /* Legacy command aliases set arg_action. They provide some fallbacks,
9444 * e.g. to tell sysvinit to reboot after you have installed systemd
9448 case ACTION_POWEROFF
:
9454 case ACTION_RUNLEVEL2
:
9455 case ACTION_RUNLEVEL3
:
9456 case ACTION_RUNLEVEL4
:
9457 case ACTION_RUNLEVEL5
:
9459 r
= start_with_fallback();
9464 r
= reload_with_fallback();
9467 case ACTION_CANCEL_SHUTDOWN
:
9468 r
= logind_cancel_shutdown();
9471 case ACTION_RUNLEVEL
:
9472 r
= runlevel_main();
9476 case ACTION_SUSPEND
:
9477 case ACTION_HIBERNATE
:
9478 case ACTION_HYBRID_SLEEP
:
9479 case ACTION_SUSPEND_THEN_HIBERNATE
:
9480 case ACTION_EMERGENCY
:
9481 case ACTION_DEFAULT
:
9482 /* systemctl verbs with no equivalent in the legacy commands.
9483 * These cannot appear in arg_action. Fall through. */
9485 case _ACTION_INVALID
:
9487 assert_not_reached("Unknown action");
9493 /* Note that we return r here, not 0, so that we can implement the LSB-like return codes */
9497 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);