]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/systemctl/systemctl.c
Introduce strcasecmp_ptr() and use it in a few places
[thirdparty/systemd.git] / src / systemctl / systemctl.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <getopt.h>
6 #include <stdbool.h>
7 #include <stddef.h>
8 #include <stdio.h>
9 #include <sys/mount.h>
10 #include <sys/prctl.h>
11 #include <sys/reboot.h>
12 #include <unistd.h>
13
14 #include "sd-bus.h"
15 #include "sd-daemon.h"
16 #include "sd-event.h"
17 #include "sd-login.h"
18
19 #include "alloc-util.h"
20 #include "bootspec.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"
26 #include "bus-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"
31 #include "copy.h"
32 #include "cpu-set-util.h"
33 #include "dirent-util.h"
34 #include "dropin.h"
35 #include "efi-loader.h"
36 #include "efivars.h"
37 #include "env-util.h"
38 #include "escape.h"
39 #include "exec-util.h"
40 #include "exit-status.h"
41 #include "fd-util.h"
42 #include "format-table.h"
43 #include "format-util.h"
44 #include "fs-util.h"
45 #include "glob-util.h"
46 #include "hexdecoct.h"
47 #include "hostname-util.h"
48 #include "in-addr-util.h"
49 #include "initreq.h"
50 #include "install.h"
51 #include "io-util.h"
52 #include "journal-util.h"
53 #include "list.h"
54 #include "locale-util.h"
55 #include "log.h"
56 #include "logs-show.h"
57 #include "macro.h"
58 #include "main-func.h"
59 #include "memory-util.h"
60 #include "mkdir.h"
61 #include "numa-util.h"
62 #include "pager.h"
63 #include "parse-util.h"
64 #include "path-lookup.h"
65 #include "path-util.h"
66 #include "pretty-print.h"
67 #include "proc-cmdline.h"
68 #include "process-util.h"
69 #include "reboot-util.h"
70 #include "rlimit-util.h"
71 #include "set.h"
72 #include "sigbus.h"
73 #include "signal-util.h"
74 #include "socket-util.h"
75 #include "sort-util.h"
76 #include "spawn-ask-password-agent.h"
77 #include "spawn-polkit-agent.h"
78 #include "special.h"
79 #include "stat-util.h"
80 #include "string-table.h"
81 #include "strv.h"
82 #include "sysv-compat.h"
83 #include "terminal-util.h"
84 #include "tmpfile-util.h"
85 #include "unit-def.h"
86 #include "unit-file.h"
87 #include "unit-name.h"
88 #include "user-util.h"
89 #include "utf8.h"
90 #include "utmp-wtmp.h"
91 #include "verbs.h"
92 #include "virt.h"
93
94 static char **arg_types = NULL;
95 static char **arg_states = NULL;
96 static char **arg_properties = NULL;
97 static bool arg_all = false;
98 static enum dependency {
99 DEPENDENCY_FORWARD,
100 DEPENDENCY_REVERSE,
101 DEPENDENCY_AFTER,
102 DEPENDENCY_BEFORE,
103 _DEPENDENCY_MAX
104 } arg_dependency = DEPENDENCY_FORWARD;
105 static const char *arg_job_mode = "replace";
106 static UnitFileScope arg_scope = UNIT_FILE_SYSTEM;
107 static bool arg_wait = false;
108 static bool arg_no_block = false;
109 static bool arg_no_legend = false;
110 static PagerFlags arg_pager_flags = 0;
111 static bool arg_no_wtmp = false;
112 static bool arg_no_sync = false;
113 static bool arg_no_wall = false;
114 static bool arg_no_reload = false;
115 static bool arg_value = false;
116 static bool arg_show_types = false;
117 static bool arg_ignore_inhibitors = false;
118 static bool arg_dry_run = false;
119 static bool arg_quiet = false;
120 static bool arg_full = false;
121 static bool arg_recursive = false;
122 static bool arg_with_dependencies = false;
123 static bool arg_show_transaction = false;
124 static int arg_force = 0;
125 static bool arg_ask_password = false;
126 static bool arg_runtime = false;
127 static UnitFilePresetMode arg_preset_mode = UNIT_FILE_PRESET_FULL;
128 static char **arg_wall = NULL;
129 static const char *arg_kill_who = NULL;
130 static int arg_signal = SIGTERM;
131 static char *arg_root = NULL;
132 static usec_t arg_when = 0;
133 static const char *arg_reboot_argument = NULL;
134 static enum action {
135 ACTION_SYSTEMCTL,
136 ACTION_HALT,
137 ACTION_POWEROFF,
138 ACTION_REBOOT,
139 ACTION_KEXEC,
140 ACTION_EXIT,
141 ACTION_SUSPEND,
142 ACTION_HIBERNATE,
143 ACTION_HYBRID_SLEEP,
144 ACTION_SUSPEND_THEN_HIBERNATE,
145 ACTION_RUNLEVEL2,
146 ACTION_RUNLEVEL3,
147 ACTION_RUNLEVEL4,
148 ACTION_RUNLEVEL5,
149 ACTION_RESCUE,
150 ACTION_EMERGENCY,
151 ACTION_DEFAULT,
152 ACTION_RELOAD,
153 ACTION_REEXEC,
154 ACTION_RUNLEVEL,
155 ACTION_CANCEL_SHUTDOWN,
156 _ACTION_MAX,
157 _ACTION_INVALID = -1
158 } arg_action = ACTION_SYSTEMCTL;
159 static BusTransport arg_transport = BUS_TRANSPORT_LOCAL;
160 static const char *arg_host = NULL;
161 static unsigned arg_lines = 10;
162 static OutputMode arg_output = OUTPUT_SHORT;
163 static bool arg_plain = false;
164 static bool arg_firmware_setup = false;
165 static usec_t arg_boot_loader_menu = USEC_INFINITY;
166 static const char *arg_boot_loader_entry = NULL;
167 static bool arg_now = false;
168 static bool arg_jobs_before = false;
169 static bool arg_jobs_after = false;
170 static char **arg_clean_what = NULL;
171
172 /* This is a global cache that will be constructed on first use. */
173 static Hashmap *cached_id_map = NULL;
174 static Hashmap *cached_name_map = NULL;
175
176 STATIC_DESTRUCTOR_REGISTER(arg_wall, strv_freep);
177 STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
178 STATIC_DESTRUCTOR_REGISTER(arg_types, strv_freep);
179 STATIC_DESTRUCTOR_REGISTER(arg_states, strv_freep);
180 STATIC_DESTRUCTOR_REGISTER(arg_properties, strv_freep);
181 STATIC_DESTRUCTOR_REGISTER(arg_clean_what, strv_freep);
182 STATIC_DESTRUCTOR_REGISTER(cached_id_map, hashmap_freep);
183 STATIC_DESTRUCTOR_REGISTER(cached_name_map, hashmap_freep);
184
185 static int daemon_reload(int argc, char *argv[], void* userdata);
186 static int trivial_method(int argc, char *argv[], void *userdata);
187 static int halt_now(enum action a);
188 static int get_state_one_unit(sd_bus *bus, const char *name, UnitActiveState *active_state);
189
190 static bool original_stdout_is_tty;
191
192 typedef enum BusFocus {
193 BUS_FULL, /* The full bus indicated via --system or --user */
194 BUS_MANAGER, /* The manager itself, possibly directly, possibly via the bus */
195 _BUS_FOCUS_MAX
196 } BusFocus;
197
198 static sd_bus *buses[_BUS_FOCUS_MAX] = {};
199
200 static UnitFileFlags args_to_flags(void) {
201 return (arg_runtime ? UNIT_FILE_RUNTIME : 0) |
202 (arg_force ? UNIT_FILE_FORCE : 0);
203 }
204
205 static int acquire_bus(BusFocus focus, sd_bus **ret) {
206 int r;
207
208 assert(focus < _BUS_FOCUS_MAX);
209 assert(ret);
210
211 /* We only go directly to the manager, if we are using a local transport */
212 if (arg_transport != BUS_TRANSPORT_LOCAL)
213 focus = BUS_FULL;
214
215 if (getenv_bool("SYSTEMCTL_FORCE_BUS") > 0)
216 focus = BUS_FULL;
217
218 if (!buses[focus]) {
219 bool user;
220
221 user = arg_scope != UNIT_FILE_SYSTEM;
222
223 if (focus == BUS_MANAGER)
224 r = bus_connect_transport_systemd(arg_transport, arg_host, user, &buses[focus]);
225 else
226 r = bus_connect_transport(arg_transport, arg_host, user, &buses[focus]);
227 if (r < 0)
228 return log_error_errno(r, "Failed to connect to bus: %m");
229
230 (void) sd_bus_set_allow_interactive_authorization(buses[focus], arg_ask_password);
231 }
232
233 *ret = buses[focus];
234 return 0;
235 }
236
237 static void release_busses(void) {
238 BusFocus w;
239
240 for (w = 0; w < _BUS_FOCUS_MAX; w++)
241 buses[w] = sd_bus_flush_close_unref(buses[w]);
242 }
243
244 static void ask_password_agent_open_maybe(void) {
245 /* Open the password agent as a child process if necessary */
246
247 if (arg_dry_run)
248 return;
249
250 if (arg_scope != UNIT_FILE_SYSTEM)
251 return;
252
253 ask_password_agent_open_if_enabled(arg_transport, arg_ask_password);
254 }
255
256 static void polkit_agent_open_maybe(void) {
257 /* Open the polkit agent as a child process if necessary */
258
259 if (arg_scope != UNIT_FILE_SYSTEM)
260 return;
261
262 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
263 }
264
265 static OutputFlags get_output_flags(void) {
266 return
267 arg_all * OUTPUT_SHOW_ALL |
268 (arg_full || !on_tty() || pager_have()) * OUTPUT_FULL_WIDTH |
269 colors_enabled() * OUTPUT_COLOR |
270 !arg_quiet * OUTPUT_WARN_CUTOFF;
271 }
272
273 static int translate_bus_error_to_exit_status(int r, const sd_bus_error *error) {
274 assert(error);
275
276 if (!sd_bus_error_is_set(error))
277 return r;
278
279 if (sd_bus_error_has_name(error, SD_BUS_ERROR_ACCESS_DENIED) ||
280 sd_bus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
281 sd_bus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
282 sd_bus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
283 return EXIT_NOPERMISSION;
284
285 if (sd_bus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
286 return EXIT_NOTINSTALLED;
287
288 if (sd_bus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
289 sd_bus_error_has_name(error, SD_BUS_ERROR_NOT_SUPPORTED))
290 return EXIT_NOTIMPLEMENTED;
291
292 if (sd_bus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
293 return EXIT_NOTCONFIGURED;
294
295 if (r != 0)
296 return r;
297
298 return EXIT_FAILURE;
299 }
300
301 static bool install_client_side(void) {
302 /* Decides when to execute enable/disable/... operations
303 * client-side rather than server-side. */
304
305 if (running_in_chroot_or_offline())
306 return true;
307
308 if (sd_booted() <= 0)
309 return true;
310
311 if (!isempty(arg_root))
312 return true;
313
314 if (arg_scope == UNIT_FILE_GLOBAL)
315 return true;
316
317 /* Unsupported environment variable, mostly for debugging purposes */
318 if (getenv_bool("SYSTEMCTL_INSTALL_CLIENT_SIDE") > 0)
319 return true;
320
321 return false;
322 }
323
324 static int compare_unit_info(const UnitInfo *a, const UnitInfo *b) {
325 int r;
326
327 /* First, order by machine */
328 r = strcasecmp_ptr(a->machine, b->machine);
329 if (r != 0)
330 return r;
331
332 /* Second, order by unit type */
333 r = strcasecmp_ptr(strrchr(a->id, '.'), strrchr(b->id, '.'));
334 if (r != 0)
335 return r;
336
337 /* Third, order by name */
338 return strcasecmp(a->id, b->id);
339 }
340
341 static const char* unit_type_suffix(const char *name) {
342 const char *dot;
343
344 dot = strrchr(name, '.');
345 if (!dot)
346 return "";
347
348 return dot + 1;
349 }
350
351 static bool output_show_unit(const UnitInfo *u, char **patterns) {
352 assert(u);
353
354 if (!strv_fnmatch_or_empty(patterns, u->id, FNM_NOESCAPE))
355 return false;
356
357 if (arg_types && !strv_find(arg_types, unit_type_suffix(u->id)))
358 return false;
359
360 if (arg_all)
361 return true;
362
363 /* Note that '--all' is not purely a state filter, but also a
364 * filter that hides units that "follow" other units (which is
365 * used for device units that appear under different names). */
366 if (!isempty(u->following))
367 return false;
368
369 if (!strv_isempty(arg_states))
370 return true;
371
372 /* By default show all units except the ones in inactive
373 * state and with no pending job */
374 if (u->job_id > 0)
375 return true;
376
377 if (streq(u->active_state, "inactive"))
378 return false;
379
380 return true;
381 }
382
383 static int output_table(Table *table) {
384 int r;
385
386 assert(table);
387
388 if (OUTPUT_MODE_IS_JSON(arg_output))
389 r = table_print_json(table, NULL, output_mode_to_json_format_flags(arg_output) | JSON_FORMAT_COLOR_AUTO);
390 else
391 r = table_print(table, NULL);
392 if (r < 0)
393 return log_error_errno(r, "Failed to show table: %m");
394
395 return 0;
396 }
397
398 static int output_units_list(const UnitInfo *unit_infos, unsigned c) {
399 _cleanup_(table_unrefp) Table *table = NULL;
400 const UnitInfo *u;
401 int job_count = 0;
402 int r;
403
404 table = table_new("", "unit", "load", "active", "sub", "job", "description");
405 if (!table)
406 return log_oom();
407
408 table_set_header(table, !arg_no_legend);
409 if (arg_plain) {
410 /* Hide the 'glyph' column when --plain is requested */
411 r = table_hide_column_from_display(table, 0);
412 if (r < 0)
413 return log_error_errno(r, "Failed to hide column: %m");
414 }
415 if (arg_full)
416 table_set_width(table, 0);
417
418 (void) table_set_empty_string(table, "-");
419
420 for (u = unit_infos; unit_infos && u < unit_infos + c; u++) {
421 _cleanup_free_ char *j = NULL;
422 const char *on_underline = "", *on_loaded = "", *on_active = "";
423 const char *on_circle = "", *id;
424 bool circle = false, underline = false;
425
426 if (u + 1 < unit_infos + c &&
427 !streq(unit_type_suffix(u->id), unit_type_suffix((u + 1)->id))) {
428 on_underline = ansi_underline();
429 underline = true;
430 }
431
432 if (STR_IN_SET(u->load_state, "error", "not-found", "bad-setting", "masked") && !arg_plain) {
433 on_circle = underline ? ansi_highlight_yellow_underline() : ansi_highlight_yellow();
434 circle = true;
435 on_loaded = underline ? ansi_highlight_red_underline() : ansi_highlight_red();
436 } else if (streq(u->active_state, "failed") && !arg_plain) {
437 on_circle = underline ? ansi_highlight_red_underline() : ansi_highlight_red();
438 circle = true;
439 on_active = underline ? ansi_highlight_red_underline() : ansi_highlight_red();
440 } else {
441 on_circle = on_underline;
442 on_active = on_underline;
443 on_loaded = on_underline;
444 }
445
446 if (u->machine) {
447 j = strjoin(u->machine, ":", u->id);
448 if (!j)
449 return log_oom();
450
451 id = j;
452 } else
453 id = u->id;
454
455 r = table_add_many(table,
456 TABLE_STRING, circle ? special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE) : " ",
457 TABLE_SET_BOTH_COLORS, on_circle,
458 TABLE_STRING, id,
459 TABLE_SET_BOTH_COLORS, on_active,
460 TABLE_STRING, u->load_state,
461 TABLE_SET_BOTH_COLORS, on_loaded,
462 TABLE_STRING, u->active_state,
463 TABLE_SET_BOTH_COLORS, on_active,
464 TABLE_STRING, u->sub_state,
465 TABLE_SET_BOTH_COLORS, on_active,
466 TABLE_STRING, u->job_id ? u->job_type: "",
467 TABLE_SET_BOTH_COLORS, u->job_id ? on_underline : "",
468 TABLE_STRING, u->description,
469 TABLE_SET_BOTH_COLORS, on_underline);
470 if (r < 0)
471 return table_log_add_error(r);
472
473 if (u->job_id != 0)
474 job_count++;
475 }
476
477 if (job_count == 0) {
478 /* There's no data in the JOB column, so let's hide it */
479 r = table_hide_column_from_display(table, 5);
480 if (r < 0)
481 return log_error_errno(r, "Failed to hide column: %m");
482 }
483
484 r = output_table(table);
485 if (r < 0)
486 return r;
487
488 if (!arg_no_legend) {
489 const char *on, *off;
490 size_t records = table_get_rows(table) - 1;
491
492 if (records > 0) {
493 puts("\n"
494 "LOAD = Reflects whether the unit definition was properly loaded.\n"
495 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
496 "SUB = The low-level unit activation state, values depend on unit type.");
497 puts(job_count ? "JOB = Pending job for the unit.\n" : "");
498 on = ansi_highlight();
499 off = ansi_normal();
500 } else {
501 on = ansi_highlight_red();
502 off = ansi_normal();
503 }
504
505 if (arg_all || strv_contains(arg_states, "inactive"))
506 printf("%s%zu loaded units listed.%s\n"
507 "To show all installed unit files use 'systemctl list-unit-files'.\n",
508 on, records, off);
509 else if (!arg_states)
510 printf("%s%zu loaded units listed.%s Pass --all to see loaded but inactive units, too.\n"
511 "To show all installed unit files use 'systemctl list-unit-files'.\n",
512 on, records, off);
513 else
514 printf("%zu loaded units listed.\n", records);
515 }
516
517 return 0;
518 }
519
520 static int get_unit_list(
521 sd_bus *bus,
522 const char *machine,
523 char **patterns,
524 UnitInfo **unit_infos,
525 int c,
526 sd_bus_message **_reply) {
527
528 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
529 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
530 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
531 size_t size = c;
532 int r;
533 UnitInfo u;
534 bool fallback = false;
535
536 assert(bus);
537 assert(unit_infos);
538 assert(_reply);
539
540 r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "ListUnitsByPatterns");
541 if (r < 0)
542 return bus_log_create_error(r);
543
544 r = sd_bus_message_append_strv(m, arg_states);
545 if (r < 0)
546 return bus_log_create_error(r);
547
548 r = sd_bus_message_append_strv(m, patterns);
549 if (r < 0)
550 return bus_log_create_error(r);
551
552 r = sd_bus_call(bus, m, 0, &error, &reply);
553 if (r < 0 && (sd_bus_error_has_name(&error, SD_BUS_ERROR_UNKNOWN_METHOD) ||
554 sd_bus_error_has_name(&error, SD_BUS_ERROR_ACCESS_DENIED))) {
555 /* Fallback to legacy ListUnitsFiltered method */
556 fallback = true;
557 log_debug_errno(r, "Failed to list units: %s Falling back to ListUnitsFiltered method.", bus_error_message(&error, r));
558 m = sd_bus_message_unref(m);
559 sd_bus_error_free(&error);
560
561 r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "ListUnitsFiltered");
562 if (r < 0)
563 return bus_log_create_error(r);
564
565 r = sd_bus_message_append_strv(m, arg_states);
566 if (r < 0)
567 return bus_log_create_error(r);
568
569 r = sd_bus_call(bus, m, 0, &error, &reply);
570 }
571 if (r < 0)
572 return log_error_errno(r, "Failed to list units: %s", bus_error_message(&error, r));
573
574 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssssouso)");
575 if (r < 0)
576 return bus_log_parse_error(r);
577
578 while ((r = bus_parse_unit_info(reply, &u)) > 0) {
579 u.machine = machine;
580
581 if (!output_show_unit(&u, fallback ? patterns : NULL))
582 continue;
583
584 if (!GREEDY_REALLOC(*unit_infos, size, c+1))
585 return log_oom();
586
587 (*unit_infos)[c++] = u;
588 }
589 if (r < 0)
590 return bus_log_parse_error(r);
591
592 r = sd_bus_message_exit_container(reply);
593 if (r < 0)
594 return bus_log_parse_error(r);
595
596 *_reply = TAKE_PTR(reply);
597
598 return c;
599 }
600
601 static void message_set_freep(Set **set) {
602 set_free_with_destructor(*set, sd_bus_message_unref);
603 }
604
605 static int get_unit_list_recursive(
606 sd_bus *bus,
607 char **patterns,
608 UnitInfo **_unit_infos,
609 Set **_replies,
610 char ***_machines) {
611
612 _cleanup_free_ UnitInfo *unit_infos = NULL;
613 _cleanup_(message_set_freep) Set *replies;
614 sd_bus_message *reply;
615 int c, r;
616
617 assert(bus);
618 assert(_replies);
619 assert(_unit_infos);
620 assert(_machines);
621
622 replies = set_new(NULL);
623 if (!replies)
624 return log_oom();
625
626 c = get_unit_list(bus, NULL, patterns, &unit_infos, 0, &reply);
627 if (c < 0)
628 return c;
629
630 r = set_put(replies, reply);
631 if (r < 0) {
632 sd_bus_message_unref(reply);
633 return log_oom();
634 }
635
636 if (arg_recursive) {
637 _cleanup_strv_free_ char **machines = NULL;
638 char **i;
639
640 r = sd_get_machine_names(&machines);
641 if (r < 0)
642 return log_error_errno(r, "Failed to get machine names: %m");
643
644 STRV_FOREACH(i, machines) {
645 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *container = NULL;
646 int k;
647
648 r = sd_bus_open_system_machine(&container, *i);
649 if (r < 0) {
650 log_warning_errno(r, "Failed to connect to container %s, ignoring: %m", *i);
651 continue;
652 }
653
654 k = get_unit_list(container, *i, patterns, &unit_infos, c, &reply);
655 if (k < 0)
656 return k;
657
658 c = k;
659
660 r = set_put(replies, reply);
661 if (r < 0) {
662 sd_bus_message_unref(reply);
663 return log_oom();
664 }
665 }
666
667 *_machines = TAKE_PTR(machines);
668 } else
669 *_machines = NULL;
670
671 *_unit_infos = TAKE_PTR(unit_infos);
672 *_replies = TAKE_PTR(replies);
673
674 return c;
675 }
676
677 static int expand_names(sd_bus *bus, char **names, const char* suffix, char ***ret, bool *ret_expanded) {
678 _cleanup_strv_free_ char **mangled = NULL, **globs = NULL;
679 char **name;
680 int r, i;
681
682 assert(bus);
683 assert(ret);
684
685 STRV_FOREACH(name, names) {
686 char *t;
687 UnitNameMangle options = UNIT_NAME_MANGLE_GLOB | (arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN);
688
689 r = unit_name_mangle_with_suffix(*name, NULL, options, suffix ?: ".service", &t);
690 if (r < 0)
691 return log_error_errno(r, "Failed to mangle name: %m");
692
693 if (string_is_glob(t))
694 r = strv_consume(&globs, t);
695 else
696 r = strv_consume(&mangled, t);
697 if (r < 0)
698 return log_oom();
699 }
700
701 /* Query the manager only if any of the names are a glob, since
702 * this is fairly expensive */
703 bool expanded = !strv_isempty(globs);
704 if (expanded) {
705 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
706 _cleanup_free_ UnitInfo *unit_infos = NULL;
707 size_t allocated, n;
708
709 r = get_unit_list(bus, NULL, globs, &unit_infos, 0, &reply);
710 if (r < 0)
711 return r;
712
713 n = strv_length(mangled);
714 allocated = n + 1;
715
716 for (i = 0; i < r; i++) {
717 if (!GREEDY_REALLOC(mangled, allocated, n+2))
718 return log_oom();
719
720 mangled[n] = strdup(unit_infos[i].id);
721 if (!mangled[n])
722 return log_oom();
723
724 mangled[++n] = NULL;
725 }
726 }
727
728 if (ret_expanded)
729 *ret_expanded = expanded;
730
731 *ret = TAKE_PTR(mangled);
732 return 0;
733 }
734
735 static int list_dependencies_get_dependencies(sd_bus *bus, const char *name, char ***ret) {
736 _cleanup_strv_free_ char **deps = NULL;
737
738 static const struct bus_properties_map map[_DEPENDENCY_MAX][6] = {
739 [DEPENDENCY_FORWARD] = {
740 { "Requires", "as", NULL, 0 },
741 { "Requisite", "as", NULL, 0 },
742 { "Wants", "as", NULL, 0 },
743 { "ConsistsOf", "as", NULL, 0 },
744 { "BindsTo", "as", NULL, 0 },
745 {}
746 },
747 [DEPENDENCY_REVERSE] = {
748 { "RequiredBy", "as", NULL, 0 },
749 { "RequisiteOf", "as", NULL, 0 },
750 { "WantedBy", "as", NULL, 0 },
751 { "PartOf", "as", NULL, 0 },
752 { "BoundBy", "as", NULL, 0 },
753 {}
754 },
755 [DEPENDENCY_AFTER] = {
756 { "After", "as", NULL, 0 },
757 {}
758 },
759 [DEPENDENCY_BEFORE] = {
760 { "Before", "as", NULL, 0 },
761 {}
762 },
763 };
764
765 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
766 _cleanup_free_ char *dbus_path = NULL;
767 int r;
768
769 assert(bus);
770 assert(name);
771 assert(ret);
772
773 dbus_path = unit_dbus_path_from_name(name);
774 if (!dbus_path)
775 return log_oom();
776
777 r = bus_map_all_properties(bus,
778 "org.freedesktop.systemd1",
779 dbus_path,
780 map[arg_dependency],
781 BUS_MAP_STRDUP,
782 &error,
783 NULL,
784 &deps);
785 if (r < 0)
786 return log_error_errno(r, "Failed to get properties of %s: %s", name, bus_error_message(&error, r));
787
788 strv_uniq(deps); /* Sometimes a unit might have multiple deps on the other unit,
789 * but we still want to show it just once. */
790 *ret = TAKE_PTR(deps);
791
792 return 0;
793 }
794
795 static int append_unit_dependencies(sd_bus *bus, char **names, char ***ret) {
796 _cleanup_strv_free_ char **with_deps = NULL;
797 char **name;
798
799 assert(bus);
800 assert(ret);
801
802 STRV_FOREACH(name, names) {
803 _cleanup_strv_free_ char **deps = NULL;
804
805 if (strv_extend(&with_deps, *name) < 0)
806 return log_oom();
807
808 (void) list_dependencies_get_dependencies(bus, *name, &deps);
809
810 if (strv_extend_strv(&with_deps, deps, true) < 0)
811 return log_oom();
812 }
813
814 *ret = TAKE_PTR(with_deps);
815
816 return 0;
817 }
818
819 static int maybe_extend_with_unit_dependencies(sd_bus *bus, char ***list) {
820 assert(bus);
821 assert(list);
822
823 if (arg_with_dependencies) {
824 int r;
825 _cleanup_strv_free_ char **list_with_deps = NULL;
826
827 r = append_unit_dependencies(bus, *list, &list_with_deps);
828 if (r < 0)
829 return log_error_errno(r, "Failed to append unit dependencies: %m");
830
831 strv_free(*list);
832 *list = TAKE_PTR(list_with_deps);
833 }
834
835 return 0;
836 }
837
838 static int list_units(int argc, char *argv[], void *userdata) {
839 _cleanup_free_ UnitInfo *unit_infos = NULL;
840 _cleanup_(message_set_freep) Set *replies = NULL;
841 _cleanup_strv_free_ char **machines = NULL;
842 sd_bus *bus;
843 int r;
844
845 r = acquire_bus(BUS_MANAGER, &bus);
846 if (r < 0)
847 return r;
848
849 (void) pager_open(arg_pager_flags);
850
851 if (arg_with_dependencies) {
852 _cleanup_strv_free_ char **names = NULL;
853
854 r = append_unit_dependencies(bus, strv_skip(argv, 1), &names);
855 if (r < 0)
856 return r;
857
858 r = get_unit_list_recursive(bus, names, &unit_infos, &replies, &machines);
859 if (r < 0)
860 return r;
861 } else {
862 r = get_unit_list_recursive(bus, strv_skip(argv, 1), &unit_infos, &replies, &machines);
863 if (r < 0)
864 return r;
865 }
866
867 typesafe_qsort(unit_infos, r, compare_unit_info);
868 return output_units_list(unit_infos, r);
869 }
870
871 static int get_triggered_units(
872 sd_bus *bus,
873 const char* path,
874 char*** ret) {
875
876 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
877 int r;
878
879 assert(bus);
880 assert(path);
881 assert(ret);
882
883 r = sd_bus_get_property_strv(
884 bus,
885 "org.freedesktop.systemd1",
886 path,
887 "org.freedesktop.systemd1.Unit",
888 "Triggers",
889 &error,
890 ret);
891 if (r < 0)
892 return log_error_errno(r, "Failed to determine triggers: %s", bus_error_message(&error, r));
893
894 return 0;
895 }
896
897 static int get_listening(
898 sd_bus *bus,
899 const char* unit_path,
900 char*** listening) {
901
902 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
903 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
904 const char *type, *path;
905 int r, n = 0;
906
907 r = sd_bus_get_property(
908 bus,
909 "org.freedesktop.systemd1",
910 unit_path,
911 "org.freedesktop.systemd1.Socket",
912 "Listen",
913 &error,
914 &reply,
915 "a(ss)");
916 if (r < 0)
917 return log_error_errno(r, "Failed to get list of listening sockets: %s", bus_error_message(&error, r));
918
919 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ss)");
920 if (r < 0)
921 return bus_log_parse_error(r);
922
923 while ((r = sd_bus_message_read(reply, "(ss)", &type, &path)) > 0) {
924
925 r = strv_extend(listening, type);
926 if (r < 0)
927 return log_oom();
928
929 r = strv_extend(listening, path);
930 if (r < 0)
931 return log_oom();
932
933 n++;
934 }
935 if (r < 0)
936 return bus_log_parse_error(r);
937
938 r = sd_bus_message_exit_container(reply);
939 if (r < 0)
940 return bus_log_parse_error(r);
941
942 return n;
943 }
944
945 struct socket_info {
946 const char *machine;
947 const char* id;
948
949 char* type;
950 char* path;
951
952 /* Note: triggered is a list here, although it almost certainly
953 * will always be one unit. Nevertheless, dbus API allows for multiple
954 * values, so let's follow that. */
955 char** triggered;
956
957 /* The strv above is shared. free is set only in the first one. */
958 bool own_triggered;
959 };
960
961 static int socket_info_compare(const struct socket_info *a, const struct socket_info *b) {
962 int r;
963
964 assert(a);
965 assert(b);
966
967 r = strcasecmp_ptr(a->machine, b->machine);
968 if (r != 0)
969 return r;
970
971 r = strcmp(a->path, b->path);
972 if (r != 0)
973 return r;
974
975 return strcmp(a->type, b->type);
976 }
977
978 static int output_sockets_list(struct socket_info *socket_infos, unsigned cs) {
979 _cleanup_(table_unrefp) Table *table = NULL;
980 struct socket_info *s;
981 const char *on, *off;
982 int r;
983
984 table = table_new("listen", "type", "unit", "activates");
985 if (!table)
986 return log_oom();
987
988 if (!arg_show_types) {
989 /* Hide the second (TYPE) column */
990 r = table_set_display(table, (size_t) 0, (size_t) 2, (size_t) 3, (size_t) -1);
991 if (r < 0)
992 return log_error_errno(r, "Failed to set columns to display: %m");
993 }
994
995 table_set_header(table, !arg_no_legend);
996 if (arg_full)
997 table_set_width(table, 0);
998
999 (void) table_set_empty_string(table, "-");
1000
1001 if (cs) {
1002 for (s = socket_infos; s < socket_infos + cs; s++) {
1003 _cleanup_free_ char *j = NULL;
1004 const char *path;
1005
1006 if (s->machine) {
1007 j = strjoin(s->machine, ":", s->path);
1008 if (!j)
1009 return log_oom();
1010 path = j;
1011 } else
1012 path = s->path;
1013
1014 r = table_add_many(table,
1015 TABLE_STRING, path,
1016 TABLE_STRING, s->type,
1017 TABLE_STRING, s->id);
1018 if (r < 0)
1019 return table_log_add_error(r);
1020
1021 if (strv_isempty(s->triggered))
1022 r = table_add_cell(table, NULL, TABLE_EMPTY, NULL);
1023 else if (strv_length(s->triggered) == 1)
1024 r = table_add_cell(table, NULL, TABLE_STRING, s->triggered[0]);
1025 else
1026 /* This should never happen, currently our socket units can only trigger a
1027 * single unit. But let's handle this anyway, who knows what the future
1028 * brings? */
1029 r = table_add_cell(table, NULL, TABLE_STRV, s->triggered);
1030 if (r < 0)
1031 return table_log_add_error(r);
1032
1033 }
1034
1035 on = ansi_highlight();
1036 off = ansi_normal();
1037 } else {
1038 on = ansi_highlight_red();
1039 off = ansi_normal();
1040 }
1041
1042 r = output_table(table);
1043 if (r < 0)
1044 return r;
1045
1046 if (!arg_no_legend) {
1047 printf("\n%s%u sockets listed.%s\n", on, cs, off);
1048 if (!arg_all)
1049 printf("Pass --all to see loaded but inactive sockets, too.\n");
1050 }
1051
1052 return 0;
1053 }
1054
1055 static int list_sockets(int argc, char *argv[], void *userdata) {
1056 _cleanup_(message_set_freep) Set *replies = NULL;
1057 _cleanup_strv_free_ char **machines = NULL;
1058 _cleanup_strv_free_ char **sockets_with_suffix = NULL;
1059 _cleanup_free_ UnitInfo *unit_infos = NULL;
1060 _cleanup_free_ struct socket_info *socket_infos = NULL;
1061 const UnitInfo *u;
1062 struct socket_info *s;
1063 unsigned cs = 0;
1064 size_t size = 0;
1065 int r = 0, n;
1066 sd_bus *bus;
1067
1068 r = acquire_bus(BUS_MANAGER, &bus);
1069 if (r < 0)
1070 return r;
1071
1072 (void) pager_open(arg_pager_flags);
1073
1074 r = expand_names(bus, strv_skip(argv, 1), ".socket", &sockets_with_suffix, NULL);
1075 if (r < 0)
1076 return r;
1077
1078 if (argc == 1 || sockets_with_suffix) {
1079 n = get_unit_list_recursive(bus, sockets_with_suffix, &unit_infos, &replies, &machines);
1080 if (n < 0)
1081 return n;
1082
1083 for (u = unit_infos; u < unit_infos + n; u++) {
1084 _cleanup_strv_free_ char **listening = NULL, **triggered = NULL;
1085 int i, c;
1086
1087 if (!endswith(u->id, ".socket"))
1088 continue;
1089
1090 r = get_triggered_units(bus, u->unit_path, &triggered);
1091 if (r < 0)
1092 goto cleanup;
1093
1094 c = get_listening(bus, u->unit_path, &listening);
1095 if (c < 0) {
1096 r = c;
1097 goto cleanup;
1098 }
1099
1100 if (!GREEDY_REALLOC(socket_infos, size, cs + c)) {
1101 r = log_oom();
1102 goto cleanup;
1103 }
1104
1105 for (i = 0; i < c; i++)
1106 socket_infos[cs + i] = (struct socket_info) {
1107 .machine = u->machine,
1108 .id = u->id,
1109 .type = listening[i*2],
1110 .path = listening[i*2 + 1],
1111 .triggered = triggered,
1112 .own_triggered = i==0,
1113 };
1114
1115 /* from this point on we will cleanup those socket_infos */
1116 cs += c;
1117 free(listening);
1118 listening = triggered = NULL; /* avoid cleanup */
1119 }
1120
1121 typesafe_qsort(socket_infos, cs, socket_info_compare);
1122 }
1123
1124 output_sockets_list(socket_infos, cs);
1125
1126 cleanup:
1127 assert(cs == 0 || socket_infos);
1128 for (s = socket_infos; s < socket_infos + cs; s++) {
1129 free(s->type);
1130 free(s->path);
1131 if (s->own_triggered)
1132 strv_free(s->triggered);
1133 }
1134
1135 return r;
1136 }
1137
1138 static int get_next_elapse(
1139 sd_bus *bus,
1140 const char *path,
1141 dual_timestamp *next) {
1142
1143 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1144 dual_timestamp t;
1145 int r;
1146
1147 assert(bus);
1148 assert(path);
1149 assert(next);
1150
1151 r = sd_bus_get_property_trivial(
1152 bus,
1153 "org.freedesktop.systemd1",
1154 path,
1155 "org.freedesktop.systemd1.Timer",
1156 "NextElapseUSecMonotonic",
1157 &error,
1158 't',
1159 &t.monotonic);
1160 if (r < 0)
1161 return log_error_errno(r, "Failed to get next elapse time: %s", bus_error_message(&error, r));
1162
1163 r = sd_bus_get_property_trivial(
1164 bus,
1165 "org.freedesktop.systemd1",
1166 path,
1167 "org.freedesktop.systemd1.Timer",
1168 "NextElapseUSecRealtime",
1169 &error,
1170 't',
1171 &t.realtime);
1172 if (r < 0)
1173 return log_error_errno(r, "Failed to get next elapse time: %s", bus_error_message(&error, r));
1174
1175 *next = t;
1176 return 0;
1177 }
1178
1179 static int get_last_trigger(
1180 sd_bus *bus,
1181 const char *path,
1182 usec_t *last) {
1183
1184 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1185 int r;
1186
1187 assert(bus);
1188 assert(path);
1189 assert(last);
1190
1191 r = sd_bus_get_property_trivial(
1192 bus,
1193 "org.freedesktop.systemd1",
1194 path,
1195 "org.freedesktop.systemd1.Timer",
1196 "LastTriggerUSec",
1197 &error,
1198 't',
1199 last);
1200 if (r < 0)
1201 return log_error_errno(r, "Failed to get last trigger time: %s", bus_error_message(&error, r));
1202
1203 return 0;
1204 }
1205
1206 struct timer_info {
1207 const char* machine;
1208 const char* id;
1209 usec_t next_elapse;
1210 usec_t last_trigger;
1211 char** triggered;
1212 };
1213
1214 static int timer_info_compare(const struct timer_info *a, const struct timer_info *b) {
1215 int r;
1216
1217 assert(a);
1218 assert(b);
1219
1220 r = strcasecmp_ptr(a->machine, b->machine);
1221 if (r != 0)
1222 return r;
1223
1224 r = CMP(a->next_elapse, b->next_elapse);
1225 if (r != 0)
1226 return r;
1227
1228 return strcmp(a->id, b->id);
1229 }
1230
1231 static int output_timers_list(struct timer_info *timer_infos, unsigned n) {
1232 _cleanup_(table_unrefp) Table *table = NULL;
1233 struct timer_info *t;
1234 const char *on, *off;
1235 int r;
1236
1237 assert(timer_infos || n == 0);
1238
1239 table = table_new("next", "left", "last", "passed", "unit", "activates");
1240 if (!table)
1241 return log_oom();
1242
1243 table_set_header(table, !arg_no_legend);
1244 if (arg_full)
1245 table_set_width(table, 0);
1246
1247 (void) table_set_empty_string(table, "-");
1248
1249 if (n > 0) {
1250 for (t = timer_infos; t < timer_infos + n; t++) {
1251 _cleanup_free_ char *j = NULL, *activates = NULL;
1252 const char *unit;
1253
1254 if (t->machine) {
1255 j = strjoin(t->machine, ":", t->id);
1256 if (!j)
1257 return log_oom();
1258 unit = j;
1259 } else
1260 unit = t->id;
1261
1262 activates = strv_join(t->triggered, ", ");
1263 if (!activates)
1264 return log_oom();
1265
1266 r = table_add_many(table,
1267 TABLE_TIMESTAMP, t->next_elapse,
1268 TABLE_TIMESTAMP_RELATIVE, t->next_elapse,
1269 TABLE_TIMESTAMP, t->last_trigger,
1270 TABLE_TIMESTAMP_RELATIVE, t->last_trigger,
1271 TABLE_STRING, unit,
1272 TABLE_STRING, activates);
1273 if (r < 0)
1274 return table_log_add_error(r);
1275 }
1276
1277 on = ansi_highlight();
1278 off = ansi_normal();
1279 } else {
1280 on = ansi_highlight_red();
1281 off = ansi_normal();
1282 }
1283
1284 r = output_table(table);
1285 if (r < 0)
1286 return r;
1287
1288 if (!arg_no_legend) {
1289 printf("\n%s%u timers listed.%s\n", on, n, off);
1290 if (!arg_all)
1291 printf("Pass --all to see loaded but inactive timers, too.\n");
1292 }
1293
1294 return 0;
1295 }
1296
1297 static usec_t calc_next_elapse(dual_timestamp *nw, dual_timestamp *next) {
1298 usec_t next_elapse;
1299
1300 assert(nw);
1301 assert(next);
1302
1303 if (timestamp_is_set(next->monotonic)) {
1304 usec_t converted;
1305
1306 if (next->monotonic > nw->monotonic)
1307 converted = nw->realtime + (next->monotonic - nw->monotonic);
1308 else
1309 converted = nw->realtime - (nw->monotonic - next->monotonic);
1310
1311 if (timestamp_is_set(next->realtime))
1312 next_elapse = MIN(converted, next->realtime);
1313 else
1314 next_elapse = converted;
1315
1316 } else
1317 next_elapse = next->realtime;
1318
1319 return next_elapse;
1320 }
1321
1322 static int list_timers(int argc, char *argv[], void *userdata) {
1323 _cleanup_(message_set_freep) Set *replies = NULL;
1324 _cleanup_strv_free_ char **machines = NULL;
1325 _cleanup_strv_free_ char **timers_with_suffix = NULL;
1326 _cleanup_free_ struct timer_info *timer_infos = NULL;
1327 _cleanup_free_ UnitInfo *unit_infos = NULL;
1328 struct timer_info *t;
1329 const UnitInfo *u;
1330 size_t size = 0;
1331 int n, c = 0;
1332 dual_timestamp nw;
1333 sd_bus *bus;
1334 int r = 0;
1335
1336 r = acquire_bus(BUS_MANAGER, &bus);
1337 if (r < 0)
1338 return r;
1339
1340 (void) pager_open(arg_pager_flags);
1341
1342 r = expand_names(bus, strv_skip(argv, 1), ".timer", &timers_with_suffix, NULL);
1343 if (r < 0)
1344 return r;
1345
1346 if (argc == 1 || timers_with_suffix) {
1347 n = get_unit_list_recursive(bus, timers_with_suffix, &unit_infos, &replies, &machines);
1348 if (n < 0)
1349 return n;
1350
1351 dual_timestamp_get(&nw);
1352
1353 for (u = unit_infos; u < unit_infos + n; u++) {
1354 _cleanup_strv_free_ char **triggered = NULL;
1355 dual_timestamp next = DUAL_TIMESTAMP_NULL;
1356 usec_t m, last = 0;
1357
1358 if (!endswith(u->id, ".timer"))
1359 continue;
1360
1361 r = get_triggered_units(bus, u->unit_path, &triggered);
1362 if (r < 0)
1363 goto cleanup;
1364
1365 r = get_next_elapse(bus, u->unit_path, &next);
1366 if (r < 0)
1367 goto cleanup;
1368
1369 get_last_trigger(bus, u->unit_path, &last);
1370
1371 if (!GREEDY_REALLOC(timer_infos, size, c+1)) {
1372 r = log_oom();
1373 goto cleanup;
1374 }
1375
1376 m = calc_next_elapse(&nw, &next);
1377
1378 timer_infos[c++] = (struct timer_info) {
1379 .machine = u->machine,
1380 .id = u->id,
1381 .next_elapse = m,
1382 .last_trigger = last,
1383 .triggered = TAKE_PTR(triggered),
1384 };
1385 }
1386
1387 typesafe_qsort(timer_infos, c, timer_info_compare);
1388 }
1389
1390 output_timers_list(timer_infos, c);
1391
1392 cleanup:
1393 for (t = timer_infos; t < timer_infos + c; t++)
1394 strv_free(t->triggered);
1395
1396 return r;
1397 }
1398
1399 static int compare_unit_file_list(const UnitFileList *a, const UnitFileList *b) {
1400 const char *d1, *d2;
1401
1402 d1 = strrchr(a->path, '.');
1403 d2 = strrchr(b->path, '.');
1404
1405 if (d1 && d2) {
1406 int r;
1407
1408 r = strcasecmp(d1, d2);
1409 if (r != 0)
1410 return r;
1411 }
1412
1413 return strcasecmp(basename(a->path), basename(b->path));
1414 }
1415
1416 static bool output_show_unit_file(const UnitFileList *u, char **states, char **patterns) {
1417 assert(u);
1418
1419 if (!strv_fnmatch_or_empty(patterns, basename(u->path), FNM_NOESCAPE))
1420 return false;
1421
1422 if (!strv_isempty(arg_types)) {
1423 const char *dot;
1424
1425 dot = strrchr(u->path, '.');
1426 if (!dot)
1427 return false;
1428
1429 if (!strv_find(arg_types, dot+1))
1430 return false;
1431 }
1432
1433 if (!strv_isempty(states) &&
1434 !strv_find(states, unit_file_state_to_string(u->state)))
1435 return false;
1436
1437 return true;
1438 }
1439
1440 static bool show_preset_for_state(UnitFileState state) {
1441 /* Don't show preset state in those unit file states, it'll only confuse users. */
1442 return !IN_SET(state,
1443 UNIT_FILE_ALIAS,
1444 UNIT_FILE_STATIC,
1445 UNIT_FILE_GENERATED,
1446 UNIT_FILE_TRANSIENT);
1447 }
1448
1449 static int output_unit_file_list(const UnitFileList *units, unsigned c) {
1450 _cleanup_(table_unrefp) Table *table = NULL;
1451 _cleanup_(unit_file_presets_freep) UnitFilePresets presets = {};
1452 int r;
1453
1454 table = table_new("unit file", "state", "vendor preset");
1455 if (!table)
1456 return log_oom();
1457
1458 table_set_header(table, !arg_no_legend);
1459 if (arg_full)
1460 table_set_width(table, 0);
1461
1462 (void) table_set_empty_string(table, "-");
1463
1464 for (const UnitFileList *u = units; u < units + c; u++) {
1465 const char *on_underline = NULL, *on_unit_color = NULL, *id;
1466 bool underline;
1467
1468 underline = u + 1 < units + c &&
1469 !streq(unit_type_suffix(u->path), unit_type_suffix((u + 1)->path));
1470
1471 if (underline)
1472 on_underline = ansi_underline();
1473
1474 if (IN_SET(u->state,
1475 UNIT_FILE_MASKED,
1476 UNIT_FILE_MASKED_RUNTIME,
1477 UNIT_FILE_DISABLED,
1478 UNIT_FILE_BAD))
1479 on_unit_color = underline ? ansi_highlight_red_underline() : ansi_highlight_red();
1480 else if (IN_SET(u->state,
1481 UNIT_FILE_ENABLED,
1482 UNIT_FILE_ALIAS))
1483 on_unit_color = underline ? ansi_highlight_green_underline() : ansi_highlight_green();
1484 else
1485 on_unit_color = on_underline;
1486
1487 id = basename(u->path);
1488
1489 r = table_add_many(table,
1490 TABLE_STRING, id,
1491 TABLE_SET_BOTH_COLORS, strempty(on_underline),
1492 TABLE_STRING, unit_file_state_to_string(u->state),
1493 TABLE_SET_BOTH_COLORS, strempty(on_unit_color));
1494 if (r < 0)
1495 return table_log_add_error(r);
1496
1497 if (show_preset_for_state(u->state)) {
1498 const char *unit_preset_str, *on_preset_color;
1499
1500 r = unit_file_query_preset(arg_scope, arg_root, id, &presets);
1501 if (r < 0) {
1502 unit_preset_str = "n/a";
1503 on_preset_color = underline ? on_underline : ansi_normal();
1504 } else if (r == 0) {
1505 unit_preset_str = "disabled";
1506 on_preset_color = underline ? ansi_highlight_red_underline() : ansi_highlight_red();
1507 } else {
1508 unit_preset_str = "enabled";
1509 on_preset_color = underline ? ansi_highlight_green_underline() : ansi_highlight_green();
1510 }
1511
1512 r = table_add_many(table,
1513 TABLE_STRING, unit_preset_str,
1514 TABLE_SET_BOTH_COLORS, strempty(on_preset_color));
1515 } else
1516 r = table_add_many(table,
1517 TABLE_EMPTY,
1518 TABLE_SET_BOTH_COLORS, underline ? ansi_grey_underline() : ansi_grey());
1519 if (r < 0)
1520 return table_log_add_error(r);
1521 }
1522
1523 r = output_table(table);
1524 if (r < 0)
1525 return r;
1526
1527 if (!arg_no_legend)
1528 printf("\n%u unit files listed.\n", c);
1529
1530 return 0;
1531 }
1532
1533 static int list_unit_files(int argc, char *argv[], void *userdata) {
1534 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1535 _cleanup_free_ UnitFileList *units = NULL;
1536 UnitFileList *unit;
1537 size_t size = 0;
1538 unsigned c = 0;
1539 const char *state;
1540 char *path;
1541 int r;
1542 bool fallback = false;
1543
1544 if (install_client_side()) {
1545 Hashmap *h;
1546 UnitFileList *u;
1547 Iterator i;
1548 unsigned n_units;
1549
1550 h = hashmap_new(&string_hash_ops);
1551 if (!h)
1552 return log_oom();
1553
1554 r = unit_file_get_list(arg_scope, arg_root, h, arg_states, strv_skip(argv, 1));
1555 if (r < 0) {
1556 unit_file_list_free(h);
1557 return log_error_errno(r, "Failed to get unit file list: %m");
1558 }
1559
1560 n_units = hashmap_size(h);
1561
1562 units = new(UnitFileList, n_units ?: 1); /* avoid malloc(0) */
1563 if (!units) {
1564 unit_file_list_free(h);
1565 return log_oom();
1566 }
1567
1568 HASHMAP_FOREACH(u, h, i) {
1569 if (!output_show_unit_file(u, NULL, NULL))
1570 continue;
1571
1572 units[c++] = *u;
1573 free(u);
1574 }
1575
1576 assert(c <= n_units);
1577 hashmap_free(h);
1578
1579 r = 0;
1580 } else {
1581 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1582 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1583 sd_bus *bus;
1584
1585 r = acquire_bus(BUS_MANAGER, &bus);
1586 if (r < 0)
1587 return r;
1588
1589 r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "ListUnitFilesByPatterns");
1590 if (r < 0)
1591 return bus_log_create_error(r);
1592
1593 r = sd_bus_message_append_strv(m, arg_states);
1594 if (r < 0)
1595 return bus_log_create_error(r);
1596
1597 if (arg_with_dependencies) {
1598 _cleanup_strv_free_ char **names_with_deps = NULL;
1599
1600 r = append_unit_dependencies(bus, strv_skip(argv, 1), &names_with_deps);
1601 if (r < 0)
1602 return log_error_errno(r, "Failed to append unit dependencies: %m");
1603
1604 r = sd_bus_message_append_strv(m, names_with_deps);
1605 if (r < 0)
1606 return bus_log_create_error(r);
1607 } else {
1608 r = sd_bus_message_append_strv(m, strv_skip(argv, 1));
1609 if (r < 0)
1610 return bus_log_create_error(r);
1611 }
1612
1613 r = sd_bus_call(bus, m, 0, &error, &reply);
1614 if (r < 0 && sd_bus_error_has_name(&error, SD_BUS_ERROR_UNKNOWN_METHOD)) {
1615 /* Fallback to legacy ListUnitFiles method */
1616 fallback = true;
1617 log_debug_errno(r, "Failed to list unit files: %s Falling back to ListUnitsFiles method.", bus_error_message(&error, r));
1618 m = sd_bus_message_unref(m);
1619 sd_bus_error_free(&error);
1620
1621 r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "ListUnitFiles");
1622 if (r < 0)
1623 return bus_log_create_error(r);
1624
1625 r = sd_bus_call(bus, m, 0, &error, &reply);
1626 }
1627 if (r < 0)
1628 return log_error_errno(r, "Failed to list unit files: %s", bus_error_message(&error, r));
1629
1630 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ss)");
1631 if (r < 0)
1632 return bus_log_parse_error(r);
1633
1634 while ((r = sd_bus_message_read(reply, "(ss)", &path, &state)) > 0) {
1635
1636 if (!GREEDY_REALLOC(units, size, c + 1))
1637 return log_oom();
1638
1639 units[c] = (struct UnitFileList) {
1640 path,
1641 unit_file_state_from_string(state)
1642 };
1643
1644 if (output_show_unit_file(&units[c],
1645 fallback ? arg_states : NULL,
1646 fallback ? strv_skip(argv, 1) : NULL))
1647 c++;
1648
1649 }
1650 if (r < 0)
1651 return bus_log_parse_error(r);
1652
1653 r = sd_bus_message_exit_container(reply);
1654 if (r < 0)
1655 return bus_log_parse_error(r);
1656 }
1657
1658 (void) pager_open(arg_pager_flags);
1659
1660 typesafe_qsort(units, c, compare_unit_file_list);
1661 r = output_unit_file_list(units, c);
1662 if (r < 0)
1663 return r;
1664
1665 if (install_client_side())
1666 for (unit = units; unit < units + c; unit++)
1667 free(unit->path);
1668
1669 if (c == 0)
1670 return -ENOENT;
1671
1672 return 0;
1673 }
1674
1675 static int list_dependencies_print(const char *name, int level, unsigned branches, bool last) {
1676 _cleanup_free_ char *n = NULL;
1677 size_t max_len = MAX(columns(),20u);
1678 size_t len = 0;
1679 int i;
1680
1681 if (!arg_plain) {
1682
1683 for (i = level - 1; i >= 0; i--) {
1684 len += 2;
1685 if (len > max_len - 3 && !arg_full) {
1686 printf("%s...\n",max_len % 2 ? "" : " ");
1687 return 0;
1688 }
1689 printf("%s", special_glyph(branches & (1 << i) ? SPECIAL_GLYPH_TREE_VERTICAL : SPECIAL_GLYPH_TREE_SPACE));
1690 }
1691 len += 2;
1692
1693 if (len > max_len - 3 && !arg_full) {
1694 printf("%s...\n",max_len % 2 ? "" : " ");
1695 return 0;
1696 }
1697
1698 printf("%s", special_glyph(last ? SPECIAL_GLYPH_TREE_RIGHT : SPECIAL_GLYPH_TREE_BRANCH));
1699 }
1700
1701 if (arg_full) {
1702 printf("%s\n", name);
1703 return 0;
1704 }
1705
1706 n = ellipsize(name, max_len-len, 100);
1707 if (!n)
1708 return log_oom();
1709
1710 printf("%s\n", n);
1711 return 0;
1712 }
1713
1714 static int list_dependencies_compare(char * const *a, char * const *b) {
1715 if (unit_name_to_type(*a) == UNIT_TARGET && unit_name_to_type(*b) != UNIT_TARGET)
1716 return 1;
1717 if (unit_name_to_type(*a) != UNIT_TARGET && unit_name_to_type(*b) == UNIT_TARGET)
1718 return -1;
1719
1720 return strcasecmp(*a, *b);
1721 }
1722
1723 static int list_dependencies_one(
1724 sd_bus *bus,
1725 const char *name,
1726 int level,
1727 char ***units,
1728 unsigned branches) {
1729
1730 _cleanup_strv_free_ char **deps = NULL;
1731 char **c;
1732 int r = 0;
1733
1734 assert(bus);
1735 assert(name);
1736 assert(units);
1737
1738 r = strv_extend(units, name);
1739 if (r < 0)
1740 return log_oom();
1741
1742 r = list_dependencies_get_dependencies(bus, name, &deps);
1743 if (r < 0)
1744 return r;
1745
1746 typesafe_qsort(deps, strv_length(deps), list_dependencies_compare);
1747
1748 STRV_FOREACH(c, deps) {
1749 if (strv_contains(*units, *c)) {
1750 if (!arg_plain) {
1751 printf(" ");
1752 r = list_dependencies_print("...", level + 1, (branches << 1) | (c[1] == NULL ? 0 : 1), 1);
1753 if (r < 0)
1754 return r;
1755 }
1756 continue;
1757 }
1758
1759 if (arg_plain)
1760 printf(" ");
1761 else {
1762 UnitActiveState active_state = _UNIT_ACTIVE_STATE_INVALID;
1763 const char *on;
1764
1765 (void) get_state_one_unit(bus, *c, &active_state);
1766
1767 switch (active_state) {
1768 case UNIT_ACTIVE:
1769 case UNIT_RELOADING:
1770 case UNIT_ACTIVATING:
1771 on = ansi_highlight_green();
1772 break;
1773
1774 case UNIT_INACTIVE:
1775 case UNIT_DEACTIVATING:
1776 on = ansi_normal();
1777 break;
1778
1779 default:
1780 on = ansi_highlight_red();
1781 break;
1782 }
1783
1784 printf("%s%s%s ", on, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE), ansi_normal());
1785 }
1786
1787 r = list_dependencies_print(*c, level, branches, c[1] == NULL);
1788 if (r < 0)
1789 return r;
1790
1791 if (arg_all || unit_name_to_type(*c) == UNIT_TARGET) {
1792 r = list_dependencies_one(bus, *c, level + 1, units, (branches << 1) | (c[1] == NULL ? 0 : 1));
1793 if (r < 0)
1794 return r;
1795 }
1796 }
1797
1798 if (!arg_plain)
1799 strv_remove(*units, name);
1800
1801 return 0;
1802 }
1803
1804 static int list_dependencies(int argc, char *argv[], void *userdata) {
1805 _cleanup_strv_free_ char **units = NULL, **done = NULL;
1806 char **u, **patterns;
1807 sd_bus *bus;
1808 int r;
1809
1810 r = acquire_bus(BUS_MANAGER, &bus);
1811 if (r < 0)
1812 return r;
1813
1814 patterns = strv_skip(argv, 1);
1815 if (strv_isempty(patterns)) {
1816 units = strv_new(SPECIAL_DEFAULT_TARGET);
1817 if (!units)
1818 return log_oom();
1819 } else {
1820 r = expand_names(bus, patterns, NULL, &units, NULL);
1821 if (r < 0)
1822 return log_error_errno(r, "Failed to expand names: %m");
1823 }
1824
1825 (void) pager_open(arg_pager_flags);
1826
1827 STRV_FOREACH(u, units) {
1828 if (u != units)
1829 puts("");
1830
1831 puts(*u);
1832 r = list_dependencies_one(bus, *u, 0, &done, 0);
1833 if (r < 0)
1834 return r;
1835 }
1836
1837 return 0;
1838 }
1839
1840 struct machine_info {
1841 bool is_host;
1842 char *name;
1843 char *state;
1844 char *control_group;
1845 uint32_t n_failed_units;
1846 uint32_t n_jobs;
1847 usec_t timestamp;
1848 };
1849
1850 static const struct bus_properties_map machine_info_property_map[] = {
1851 { "SystemState", "s", NULL, offsetof(struct machine_info, state) },
1852 { "NJobs", "u", NULL, offsetof(struct machine_info, n_jobs) },
1853 { "NFailedUnits", "u", NULL, offsetof(struct machine_info, n_failed_units) },
1854 { "ControlGroup", "s", NULL, offsetof(struct machine_info, control_group) },
1855 { "UserspaceTimestamp", "t", NULL, offsetof(struct machine_info, timestamp) },
1856 {}
1857 };
1858
1859 static void machine_info_clear(struct machine_info *info) {
1860 assert(info);
1861
1862 free(info->name);
1863 free(info->state);
1864 free(info->control_group);
1865 zero(*info);
1866 }
1867
1868 static void free_machines_list(struct machine_info *machine_infos, int n) {
1869 int i;
1870
1871 if (!machine_infos)
1872 return;
1873
1874 for (i = 0; i < n; i++)
1875 machine_info_clear(&machine_infos[i]);
1876
1877 free(machine_infos);
1878 }
1879
1880 static int compare_machine_info(const struct machine_info *a, const struct machine_info *b) {
1881 int r;
1882
1883 r = CMP(b->is_host, a->is_host);
1884 if (r != 0)
1885 return r;
1886
1887 return strcasecmp(a->name, b->name);
1888 }
1889
1890 static int get_machine_properties(sd_bus *bus, struct machine_info *mi) {
1891 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *container = NULL;
1892 int r;
1893
1894 assert(mi);
1895
1896 if (!bus) {
1897 r = sd_bus_open_system_machine(&container, mi->name);
1898 if (r < 0)
1899 return r;
1900
1901 bus = container;
1902 }
1903
1904 r = bus_map_all_properties(
1905 bus,
1906 "org.freedesktop.systemd1",
1907 "/org/freedesktop/systemd1",
1908 machine_info_property_map,
1909 BUS_MAP_STRDUP,
1910 NULL,
1911 NULL,
1912 mi);
1913 if (r < 0)
1914 return r;
1915
1916 return 0;
1917 }
1918
1919 static bool output_show_machine(const char *name, char **patterns) {
1920 return strv_fnmatch_or_empty(patterns, name, FNM_NOESCAPE);
1921 }
1922
1923 static int get_machine_list(
1924 sd_bus *bus,
1925 struct machine_info **_machine_infos,
1926 char **patterns) {
1927
1928 struct machine_info *machine_infos = NULL;
1929 _cleanup_strv_free_ char **m = NULL;
1930 _cleanup_free_ char *hn = NULL;
1931 size_t sz = 0;
1932 char **i;
1933 int c = 0, r;
1934
1935 hn = gethostname_malloc();
1936 if (!hn)
1937 return log_oom();
1938
1939 if (output_show_machine(hn, patterns)) {
1940 if (!GREEDY_REALLOC0(machine_infos, sz, c+1))
1941 return log_oom();
1942
1943 machine_infos[c].is_host = true;
1944 machine_infos[c].name = TAKE_PTR(hn);
1945
1946 (void) get_machine_properties(bus, &machine_infos[c]);
1947 c++;
1948 }
1949
1950 r = sd_get_machine_names(&m);
1951 if (r < 0)
1952 return log_error_errno(r, "Failed to get machine list: %m");
1953
1954 STRV_FOREACH(i, m) {
1955 _cleanup_free_ char *class = NULL;
1956
1957 if (!output_show_machine(*i, patterns))
1958 continue;
1959
1960 sd_machine_get_class(*i, &class);
1961 if (!streq_ptr(class, "container"))
1962 continue;
1963
1964 if (!GREEDY_REALLOC0(machine_infos, sz, c+1)) {
1965 free_machines_list(machine_infos, c);
1966 return log_oom();
1967 }
1968
1969 machine_infos[c].is_host = false;
1970 machine_infos[c].name = strdup(*i);
1971 if (!machine_infos[c].name) {
1972 free_machines_list(machine_infos, c);
1973 return log_oom();
1974 }
1975
1976 (void) get_machine_properties(NULL, &machine_infos[c]);
1977 c++;
1978 }
1979
1980 *_machine_infos = machine_infos;
1981 return c;
1982 }
1983
1984 static int output_machines_list(struct machine_info *machine_infos, unsigned n) {
1985 _cleanup_(table_unrefp) Table *table = NULL;
1986 struct machine_info *m;
1987 bool state_missing = false;
1988 int r;
1989
1990 assert(machine_infos || n == 0);
1991
1992 table = table_new("", "name", "state", "failed", "jobs");
1993 if (!table)
1994 return log_oom();
1995
1996 table_set_header(table, !arg_no_legend);
1997 if (arg_plain) {
1998 /* Hide the 'glyph' column when --plain is requested */
1999 r = table_hide_column_from_display(table, 0);
2000 if (r < 0)
2001 return log_error_errno(r, "Failed to hide column: %m");
2002 }
2003 if (arg_full)
2004 table_set_width(table, 0);
2005
2006 (void) table_set_empty_string(table, "-");
2007
2008 for (m = machine_infos; m < machine_infos + n; m++) {
2009 _cleanup_free_ char *mname = NULL;
2010 const char *on_state = "", *on_failed = "";
2011 bool circle = false;
2012
2013 if (streq_ptr(m->state, "degraded")) {
2014 on_state = ansi_highlight_red();
2015 circle = true;
2016 } else if (!streq_ptr(m->state, "running")) {
2017 on_state = ansi_highlight_yellow();
2018 circle = true;
2019 }
2020
2021 if (m->n_failed_units > 0)
2022 on_failed = ansi_highlight_red();
2023 else
2024 on_failed = "";
2025
2026 if (!m->state)
2027 state_missing = true;
2028
2029 if (m->is_host)
2030 mname = strjoin(strna(m->name), " (host)");
2031
2032 r = table_add_many(table,
2033 TABLE_STRING, circle ? special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE) : " ",
2034 TABLE_SET_COLOR, on_state,
2035 TABLE_STRING, m->is_host ? mname : strna(m->name),
2036 TABLE_STRING, strna(m->state),
2037 TABLE_SET_COLOR, on_state,
2038 TABLE_UINT32, m->n_failed_units,
2039 TABLE_SET_COLOR, on_failed,
2040 TABLE_UINT32, m->n_jobs);
2041 if (r < 0)
2042 return table_log_add_error(r);
2043 }
2044
2045 r = output_table(table);
2046 if (r < 0)
2047 return r;
2048
2049 if (!arg_no_legend) {
2050 printf("\n");
2051 if (state_missing && geteuid() != 0)
2052 printf("Notice: some information only available to privileged users was not shown.\n");
2053 printf("%u machines listed.\n", n);
2054 }
2055
2056 return 0;
2057 }
2058
2059 static int list_machines(int argc, char *argv[], void *userdata) {
2060 struct machine_info *machine_infos = NULL;
2061 sd_bus *bus;
2062 int r, rc;
2063
2064 r = acquire_bus(BUS_MANAGER, &bus);
2065 if (r < 0)
2066 return r;
2067
2068 r = get_machine_list(bus, &machine_infos, strv_skip(argv, 1));
2069 if (r < 0)
2070 return r;
2071
2072 (void) pager_open(arg_pager_flags);
2073
2074 typesafe_qsort(machine_infos, r, compare_machine_info);
2075 rc = output_machines_list(machine_infos, r);
2076 free_machines_list(machine_infos, r);
2077
2078 return rc;
2079 }
2080
2081 static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
2082 char **ret = data;
2083
2084 if (streq(key, "systemd.unit")) {
2085 if (proc_cmdline_value_missing(key, value))
2086 return 0;
2087 if (!unit_name_is_valid(value, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
2088 return log_warning("Unit name specified on %s= is not valid, ignoring: %s", key, value);
2089
2090 return free_and_strdup_warn(ret, key);
2091
2092 } else if (!value) {
2093 if (runlevel_to_target(key))
2094 return free_and_strdup_warn(ret, key);
2095 }
2096
2097 return 0;
2098 }
2099
2100 static void emit_cmdline_warning(void) {
2101 if (arg_quiet || arg_root)
2102 /* don't bother checking the commandline if we're operating on a container */
2103 return;
2104
2105 _cleanup_free_ char *override = NULL;
2106 int r;
2107
2108 r = proc_cmdline_parse(parse_proc_cmdline_item, &override, 0);
2109 if (r < 0)
2110 log_debug_errno(r, "Failed to parse kernel command line, ignoring: %m");
2111 if (override)
2112 log_notice("Note: found \"%s\" on the kernel commandline, which overrides the default unit.",
2113 override);
2114 }
2115
2116 static int determine_default(char **ret_name) {
2117 int r;
2118
2119 if (install_client_side()) {
2120 r = unit_file_get_default(arg_scope, arg_root, ret_name);
2121 if (r < 0)
2122 return log_error_errno(r, "Failed to get default target: %m");
2123 return 0;
2124
2125 } else {
2126 sd_bus *bus;
2127 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
2128 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2129 const char *name;
2130
2131 r = acquire_bus(BUS_MANAGER, &bus);
2132 if (r < 0)
2133 return r;
2134
2135 r = bus_call_method(bus, bus_systemd_mgr, "GetDefaultTarget", &error, &reply, NULL);
2136 if (r < 0)
2137 return log_error_errno(r, "Failed to get default target: %s", bus_error_message(&error, r));
2138
2139 r = sd_bus_message_read(reply, "s", &name);
2140 if (r < 0)
2141 return bus_log_parse_error(r);
2142
2143 return free_and_strdup_warn(ret_name, name);
2144 }
2145 }
2146
2147 static int get_default(int argc, char *argv[], void *userdata) {
2148 _cleanup_free_ char *name = NULL;
2149 int r;
2150
2151 r = determine_default(&name);
2152 if (r < 0)
2153 return r;
2154
2155 printf("%s\n", name);
2156
2157 emit_cmdline_warning();
2158
2159 return 0;
2160 }
2161
2162 static int set_default(int argc, char *argv[], void *userdata) {
2163 _cleanup_free_ char *unit = NULL;
2164 UnitFileChange *changes = NULL;
2165 size_t n_changes = 0;
2166 int r;
2167
2168 assert(argc >= 2);
2169 assert(argv);
2170
2171 r = unit_name_mangle_with_suffix(argv[1], "set-default",
2172 arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN,
2173 ".target", &unit);
2174 if (r < 0)
2175 return log_error_errno(r, "Failed to mangle unit name: %m");
2176
2177 if (install_client_side()) {
2178 r = unit_file_set_default(arg_scope, UNIT_FILE_FORCE, arg_root, unit, &changes, &n_changes);
2179 unit_file_dump_changes(r, "set default", changes, n_changes, arg_quiet);
2180
2181 if (r > 0)
2182 r = 0;
2183 } else {
2184 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2185 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
2186 sd_bus *bus;
2187
2188 polkit_agent_open_maybe();
2189
2190 r = acquire_bus(BUS_MANAGER, &bus);
2191 if (r < 0)
2192 return r;
2193
2194 r = bus_call_method(bus, bus_systemd_mgr, "SetDefaultTarget", &error, &reply, "sb", unit, 1);
2195 if (r < 0)
2196 return log_error_errno(r, "Failed to set default target: %s", bus_error_message(&error, r));
2197
2198 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
2199 if (r < 0)
2200 goto finish;
2201
2202 /* Try to reload if enabled */
2203 if (!arg_no_reload)
2204 r = daemon_reload(argc, argv, userdata);
2205 else
2206 r = 0;
2207 }
2208
2209 emit_cmdline_warning();
2210
2211 if (!arg_quiet) {
2212 _cleanup_free_ char *final = NULL;
2213
2214 r = determine_default(&final);
2215 if (r < 0)
2216 return r;
2217
2218 if (!streq(final, unit))
2219 log_notice("Note: \"%s\" is the default unit (possibly a runtime override).", final);
2220 }
2221
2222 finish:
2223 unit_file_changes_free(changes, n_changes);
2224
2225 return r;
2226 }
2227
2228 static int output_waiting_jobs(sd_bus *bus, Table *table, uint32_t id, const char *method, const char *prefix) {
2229 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2230 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
2231 const char *name, *type;
2232 uint32_t other_id;
2233 int r;
2234
2235 assert(bus);
2236
2237 r = bus_call_method(bus, bus_systemd_mgr, method, &error, &reply, "u", id);
2238 if (r < 0)
2239 return log_debug_errno(r, "Failed to get waiting jobs for job %" PRIu32, id);
2240
2241 r = sd_bus_message_enter_container(reply, 'a', "(usssoo)");
2242 if (r < 0)
2243 return bus_log_parse_error(r);
2244
2245 while ((r = sd_bus_message_read(reply, "(usssoo)", &other_id, &name, &type, NULL, NULL, NULL)) > 0) {
2246 _cleanup_free_ char *row = NULL;
2247 int rc;
2248
2249 if (asprintf(&row, "%s %u (%s/%s)", prefix, other_id, name, type) < 0)
2250 return log_oom();
2251
2252 rc = table_add_many(table,
2253 TABLE_STRING, special_glyph(SPECIAL_GLYPH_TREE_RIGHT),
2254 TABLE_STRING, row,
2255 TABLE_EMPTY,
2256 TABLE_EMPTY);
2257 if (rc < 0)
2258 return table_log_add_error(r);
2259 }
2260
2261 if (r < 0)
2262 return bus_log_parse_error(r);
2263
2264 r = sd_bus_message_exit_container(reply);
2265 if (r < 0)
2266 return bus_log_parse_error(r);
2267
2268 return 0;
2269 }
2270
2271 struct job_info {
2272 uint32_t id;
2273 const char *name, *type, *state;
2274 };
2275
2276 static int output_jobs_list(sd_bus *bus, const struct job_info* jobs, unsigned n, bool skipped) {
2277 _cleanup_(table_unrefp) Table *table = NULL;
2278 const struct job_info *j;
2279 const char *on, *off;
2280 int r;
2281
2282 assert(n == 0 || jobs);
2283
2284 if (n == 0) {
2285 if (!arg_no_legend) {
2286 on = ansi_highlight_green();
2287 off = ansi_normal();
2288
2289 printf("%sNo jobs %s.%s\n", on, skipped ? "listed" : "running", off);
2290 }
2291 return 0;
2292 }
2293
2294 (void) pager_open(arg_pager_flags);
2295
2296 table = table_new("job", "unit", "type", "state");
2297 if (!table)
2298 return log_oom();
2299
2300 table_set_header(table, !arg_no_legend);
2301 if (arg_full)
2302 table_set_width(table, 0);
2303
2304 (void) table_set_empty_string(table, "-");
2305
2306 for (j = jobs; j < jobs + n; j++) {
2307 if (streq(j->state, "running"))
2308 on = ansi_highlight();
2309 else
2310 on = "";
2311
2312 r = table_add_many(table,
2313 TABLE_UINT, j->id,
2314 TABLE_STRING, j->name,
2315 TABLE_SET_COLOR, on,
2316 TABLE_STRING, j->type,
2317 TABLE_STRING, j->state,
2318 TABLE_SET_COLOR, on);
2319 if (r < 0)
2320 return table_log_add_error(r);
2321
2322 if (arg_jobs_after)
2323 output_waiting_jobs(bus, table, j->id, "GetJobAfter", "\twaiting for job");
2324 if (arg_jobs_before)
2325 output_waiting_jobs(bus, table, j->id, "GetJobBefore", "\tblocking job");
2326 }
2327
2328 r = table_print(table, NULL);
2329 if (r < 0)
2330 return log_error_errno(r, "Failed to print the table: %m");
2331
2332 if (!arg_no_legend) {
2333 on = ansi_highlight();
2334 off = ansi_normal();
2335
2336 printf("\n%s%u jobs listed%s.\n", on, n, off);
2337 }
2338
2339 return 0;
2340 }
2341
2342 static bool output_show_job(struct job_info *job, char **patterns) {
2343 return strv_fnmatch_or_empty(patterns, job->name, FNM_NOESCAPE);
2344 }
2345
2346 static int list_jobs(int argc, char *argv[], void *userdata) {
2347 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2348 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
2349 _cleanup_free_ struct job_info *jobs = NULL;
2350 const char *name, *type, *state;
2351 bool skipped = false;
2352 size_t size = 0;
2353 unsigned c = 0;
2354 sd_bus *bus;
2355 uint32_t id;
2356 int r;
2357
2358 r = acquire_bus(BUS_MANAGER, &bus);
2359 if (r < 0)
2360 return r;
2361
2362 r = bus_call_method(bus, bus_systemd_mgr, "ListJobs", &error, &reply, NULL);
2363 if (r < 0)
2364 return log_error_errno(r, "Failed to list jobs: %s", bus_error_message(&error, r));
2365
2366 r = sd_bus_message_enter_container(reply, 'a', "(usssoo)");
2367 if (r < 0)
2368 return bus_log_parse_error(r);
2369
2370 while ((r = sd_bus_message_read(reply, "(usssoo)", &id, &name, &type, &state, NULL, NULL)) > 0) {
2371 struct job_info job = { id, name, type, state };
2372
2373 if (!output_show_job(&job, strv_skip(argv, 1))) {
2374 skipped = true;
2375 continue;
2376 }
2377
2378 if (!GREEDY_REALLOC(jobs, size, c + 1))
2379 return log_oom();
2380
2381 jobs[c++] = job;
2382 }
2383 if (r < 0)
2384 return bus_log_parse_error(r);
2385
2386 r = sd_bus_message_exit_container(reply);
2387 if (r < 0)
2388 return bus_log_parse_error(r);
2389
2390 (void) pager_open(arg_pager_flags);
2391
2392 return output_jobs_list(bus, jobs, c, skipped);
2393 }
2394
2395 static int cancel_job(int argc, char *argv[], void *userdata) {
2396 sd_bus *bus;
2397 char **name;
2398 int r = 0;
2399
2400 if (argc <= 1)
2401 return trivial_method(argc, argv, userdata);
2402
2403 r = acquire_bus(BUS_MANAGER, &bus);
2404 if (r < 0)
2405 return r;
2406
2407 polkit_agent_open_maybe();
2408
2409 STRV_FOREACH(name, strv_skip(argv, 1)) {
2410 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2411 uint32_t id;
2412 int q;
2413
2414 q = safe_atou32(*name, &id);
2415 if (q < 0)
2416 return log_error_errno(q, "Failed to parse job id \"%s\": %m", *name);
2417
2418 q = bus_call_method(bus, bus_systemd_mgr, "CancelJob", &error, NULL, "u", id);
2419 if (q < 0) {
2420 log_error_errno(q, "Failed to cancel job %"PRIu32": %s", id, bus_error_message(&error, q));
2421 if (r == 0)
2422 r = q;
2423 }
2424 }
2425
2426 return r;
2427 }
2428
2429 static int need_daemon_reload(sd_bus *bus, const char *unit) {
2430 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
2431 const char *path;
2432 int b, r;
2433
2434 /* We ignore all errors here, since this is used to show a
2435 * warning only */
2436
2437 /* We don't use unit_dbus_path_from_name() directly since we
2438 * don't want to load the unit if it isn't loaded. */
2439
2440 r = bus_call_method(bus, bus_systemd_mgr, "GetUnit", NULL, &reply, "s", unit);
2441 if (r < 0)
2442 return r;
2443
2444 r = sd_bus_message_read(reply, "o", &path);
2445 if (r < 0)
2446 return r;
2447
2448 r = sd_bus_get_property_trivial(
2449 bus,
2450 "org.freedesktop.systemd1",
2451 path,
2452 "org.freedesktop.systemd1.Unit",
2453 "NeedDaemonReload",
2454 NULL,
2455 'b', &b);
2456 if (r < 0)
2457 return r;
2458
2459 return b;
2460 }
2461
2462 static void warn_unit_file_changed(const char *name) {
2463 assert(name);
2464
2465 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.",
2466 ansi_highlight_red(),
2467 ansi_normal(),
2468 name,
2469 arg_scope == UNIT_FILE_SYSTEM ? "" : " --user");
2470 }
2471
2472 static int unit_file_find_path(LookupPaths *lp, const char *unit_name, char **ret_unit_path) {
2473 char **p;
2474
2475 assert(lp);
2476 assert(unit_name);
2477
2478 STRV_FOREACH(p, lp->search_path) {
2479 _cleanup_free_ char *path = NULL, *lpath = NULL;
2480 int r;
2481
2482 path = path_join(*p, unit_name);
2483 if (!path)
2484 return log_oom();
2485
2486 r = chase_symlinks(path, arg_root, 0, &lpath, NULL);
2487 if (r == -ENOENT)
2488 continue;
2489 if (r == -ENOMEM)
2490 return log_oom();
2491 if (r < 0)
2492 return log_error_errno(r, "Failed to access path \"%s\": %m", path);
2493
2494 if (ret_unit_path)
2495 *ret_unit_path = TAKE_PTR(lpath);
2496
2497 return 1;
2498 }
2499
2500 if (ret_unit_path)
2501 *ret_unit_path = NULL;
2502
2503 return 0;
2504 }
2505
2506 static int unit_find_template_path(
2507 const char *unit_name,
2508 LookupPaths *lp,
2509 char **ret_fragment_path,
2510 char **ret_template) {
2511
2512 _cleanup_free_ char *t = NULL, *f = NULL;
2513 int r;
2514
2515 /* Returns 1 if a fragment was found, 0 if not found, negative on error. */
2516
2517 r = unit_file_find_path(lp, unit_name, &f);
2518 if (r < 0)
2519 return r;
2520 if (r > 0) {
2521 if (ret_fragment_path)
2522 *ret_fragment_path = TAKE_PTR(f);
2523 if (ret_template)
2524 *ret_template = NULL;
2525 return r; /* found a real unit */
2526 }
2527
2528 r = unit_name_template(unit_name, &t);
2529 if (r == -EINVAL) {
2530 if (ret_fragment_path)
2531 *ret_fragment_path = NULL;
2532 if (ret_template)
2533 *ret_template = NULL;
2534
2535 return 0; /* not a template, does not exist */
2536 }
2537 if (r < 0)
2538 return log_error_errno(r, "Failed to determine template name: %m");
2539
2540 r = unit_file_find_path(lp, t, ret_fragment_path);
2541 if (r < 0)
2542 return r;
2543
2544 if (ret_template)
2545 *ret_template = r > 0 ? TAKE_PTR(t) : NULL;
2546
2547 return r;
2548 }
2549
2550 static int unit_find_paths(
2551 sd_bus *bus,
2552 const char *unit_name,
2553 LookupPaths *lp,
2554 bool force_client_side,
2555 char **ret_fragment_path,
2556 char ***ret_dropin_paths) {
2557
2558 _cleanup_strv_free_ char **dropins = NULL;
2559 _cleanup_free_ char *path = NULL;
2560 int r;
2561
2562 /**
2563 * Finds where the unit is defined on disk. Returns 0 if the unit is not found. Returns 1 if it is
2564 * found, and sets:
2565 * - the path to the unit in *ret_frament_path, if it exists on disk,
2566 * - and a strv of existing drop-ins in *ret_dropin_paths, if the arg is not NULL and any dropins
2567 * were found.
2568 *
2569 * Returns -ERFKILL if the unit is masked, and -EKEYREJECTED if the unit file could not be loaded for
2570 * some reason (the latter only applies if we are going through the service manager).
2571 */
2572
2573 assert(unit_name);
2574 assert(ret_fragment_path);
2575 assert(lp);
2576
2577 /* Go via the bus to acquire the path, unless we are explicitly told not to, or when the unit name is a template */
2578 if (!force_client_side &&
2579 !install_client_side() &&
2580 !unit_name_is_valid(unit_name, UNIT_NAME_TEMPLATE)) {
2581 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2582 _cleanup_free_ char *load_state = NULL, *dbus_path = NULL;
2583
2584 dbus_path = unit_dbus_path_from_name(unit_name);
2585 if (!dbus_path)
2586 return log_oom();
2587
2588 r = sd_bus_get_property_string(
2589 bus,
2590 "org.freedesktop.systemd1",
2591 dbus_path,
2592 "org.freedesktop.systemd1.Unit",
2593 "LoadState",
2594 &error,
2595 &load_state);
2596 if (r < 0)
2597 return log_error_errno(r, "Failed to get LoadState: %s", bus_error_message(&error, r));
2598
2599 if (streq(load_state, "masked"))
2600 return -ERFKILL;
2601 if (streq(load_state, "not-found")) {
2602 r = 0;
2603 goto not_found;
2604 }
2605 if (!STR_IN_SET(load_state, "loaded", "bad-setting"))
2606 return -EKEYREJECTED;
2607
2608 r = sd_bus_get_property_string(
2609 bus,
2610 "org.freedesktop.systemd1",
2611 dbus_path,
2612 "org.freedesktop.systemd1.Unit",
2613 "FragmentPath",
2614 &error,
2615 &path);
2616 if (r < 0)
2617 return log_error_errno(r, "Failed to get FragmentPath: %s", bus_error_message(&error, r));
2618
2619 if (ret_dropin_paths) {
2620 r = sd_bus_get_property_strv(
2621 bus,
2622 "org.freedesktop.systemd1",
2623 dbus_path,
2624 "org.freedesktop.systemd1.Unit",
2625 "DropInPaths",
2626 &error,
2627 &dropins);
2628 if (r < 0)
2629 return log_error_errno(r, "Failed to get DropInPaths: %s", bus_error_message(&error, r));
2630 }
2631 } else {
2632 const char *_path;
2633 _cleanup_set_free_free_ Set *names = NULL;
2634
2635 if (!cached_name_map) {
2636 r = unit_file_build_name_map(lp, NULL, &cached_id_map, &cached_name_map, NULL);
2637 if (r < 0)
2638 return r;
2639 }
2640
2641 r = unit_file_find_fragment(cached_id_map, cached_name_map, unit_name, &_path, &names);
2642 if (r < 0)
2643 return r;
2644
2645 if (_path) {
2646 path = strdup(_path);
2647 if (!path)
2648 return log_oom();
2649 }
2650
2651 if (ret_dropin_paths) {
2652 r = unit_file_find_dropin_paths(arg_root, lp->search_path, NULL,
2653 ".d", ".conf",
2654 names, &dropins);
2655 if (r < 0)
2656 return r;
2657 }
2658 }
2659
2660 if (isempty(path)) {
2661 *ret_fragment_path = NULL;
2662 r = 0;
2663 } else {
2664 *ret_fragment_path = TAKE_PTR(path);
2665 r = 1;
2666 }
2667
2668 if (ret_dropin_paths) {
2669 if (!strv_isempty(dropins)) {
2670 *ret_dropin_paths = TAKE_PTR(dropins);
2671 r = 1;
2672 } else
2673 *ret_dropin_paths = NULL;
2674 }
2675
2676 not_found:
2677 if (r == 0 && !arg_force)
2678 log_error("No files found for %s.", unit_name);
2679
2680 return r;
2681 }
2682
2683 static int get_state_one_unit(sd_bus *bus, const char *name, UnitActiveState *active_state) {
2684 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2685 _cleanup_free_ char *buf = NULL, *dbus_path = NULL;
2686 UnitActiveState state;
2687 int r;
2688
2689 assert(name);
2690 assert(active_state);
2691
2692 dbus_path = unit_dbus_path_from_name(name);
2693 if (!dbus_path)
2694 return log_oom();
2695
2696 r = sd_bus_get_property_string(
2697 bus,
2698 "org.freedesktop.systemd1",
2699 dbus_path,
2700 "org.freedesktop.systemd1.Unit",
2701 "ActiveState",
2702 &error,
2703 &buf);
2704 if (r < 0)
2705 return log_error_errno(r, "Failed to retrieve unit state: %s", bus_error_message(&error, r));
2706
2707 state = unit_active_state_from_string(buf);
2708 if (state < 0)
2709 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid unit state '%s' for: %s", buf, name);
2710
2711 *active_state = state;
2712 return 0;
2713 }
2714
2715 static int unit_is_masked(sd_bus *bus, LookupPaths *lp, const char *name) {
2716 _cleanup_free_ char *load_state = NULL;
2717 int r;
2718
2719 if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
2720 _cleanup_free_ char *path = NULL;
2721
2722 /* A template cannot be loaded, but it can be still masked, so
2723 * we need to use a different method. */
2724
2725 r = unit_file_find_path(lp, name, &path);
2726 if (r < 0)
2727 return r;
2728 if (r == 0)
2729 return false;
2730 return null_or_empty_path(path);
2731 }
2732
2733 r = unit_load_state(bus, name, &load_state);
2734 if (r < 0)
2735 return r;
2736
2737 return streq(load_state, "masked");
2738 }
2739
2740 static int check_triggering_units(sd_bus *bus, const char *name) {
2741 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2742 _cleanup_free_ char *n = NULL, *dbus_path = NULL, *load_state = NULL;
2743 _cleanup_strv_free_ char **triggered_by = NULL;
2744 bool print_warning_label = true;
2745 UnitActiveState active_state;
2746 char **i;
2747 int r;
2748
2749 r = unit_name_mangle(name, 0, &n);
2750 if (r < 0)
2751 return log_error_errno(r, "Failed to mangle unit name: %m");
2752
2753 r = unit_load_state(bus, name, &load_state);
2754 if (r < 0)
2755 return r;
2756
2757 if (streq(load_state, "masked"))
2758 return 0;
2759
2760 dbus_path = unit_dbus_path_from_name(n);
2761 if (!dbus_path)
2762 return log_oom();
2763
2764 r = sd_bus_get_property_strv(
2765 bus,
2766 "org.freedesktop.systemd1",
2767 dbus_path,
2768 "org.freedesktop.systemd1.Unit",
2769 "TriggeredBy",
2770 &error,
2771 &triggered_by);
2772 if (r < 0)
2773 return log_error_errno(r, "Failed to get triggered by array of %s: %s", n, bus_error_message(&error, r));
2774
2775 STRV_FOREACH(i, triggered_by) {
2776 r = get_state_one_unit(bus, *i, &active_state);
2777 if (r < 0)
2778 return r;
2779
2780 if (!IN_SET(active_state, UNIT_ACTIVE, UNIT_RELOADING))
2781 continue;
2782
2783 if (print_warning_label) {
2784 log_warning("Warning: Stopping %s, but it can still be activated by:", n);
2785 print_warning_label = false;
2786 }
2787
2788 log_warning(" %s", *i);
2789 }
2790
2791 return 0;
2792 }
2793
2794 static const struct {
2795 const char *verb; /* systemctl verb */
2796 const char *method; /* Name of the specific D-Bus method */
2797 const char *job_type; /* Job type when passing to the generic EnqueueUnitJob() method */
2798 } unit_actions[] = {
2799 { "start", "StartUnit", "start" },
2800 { "stop", "StopUnit", "stop" },
2801 { "condstop", "StopUnit", "stop" }, /* legacy alias */
2802 { "reload", "ReloadUnit", "reload" },
2803 { "restart", "RestartUnit", "restart" },
2804 { "try-restart", "TryRestartUnit", "try-restart" },
2805 { "condrestart", "TryRestartUnit", "try-restart" }, /* legacy alias */
2806 { "reload-or-restart", "ReloadOrRestartUnit", "reload-or-restart" },
2807 { "try-reload-or-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" },
2808 { "reload-or-try-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2809 { "condreload", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2810 { "force-reload", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2811 };
2812
2813 static const char *verb_to_method(const char *verb) {
2814 size_t i;
2815
2816 for (i = 0; i < ELEMENTSOF(unit_actions); i++)
2817 if (streq_ptr(unit_actions[i].verb, verb))
2818 return unit_actions[i].method;
2819
2820 return "StartUnit";
2821 }
2822
2823 static const char *verb_to_job_type(const char *verb) {
2824 size_t i;
2825
2826 for (i = 0; i < ELEMENTSOF(unit_actions); i++)
2827 if (streq_ptr(unit_actions[i].verb, verb))
2828 return unit_actions[i].job_type;
2829
2830 return "start";
2831 }
2832
2833 static int start_unit_one(
2834 sd_bus *bus,
2835 const char *method, /* When using classic per-job bus methods */
2836 const char *job_type, /* When using new-style EnqueueUnitJob() */
2837 const char *name,
2838 const char *mode,
2839 sd_bus_error *error,
2840 BusWaitForJobs *w,
2841 BusWaitForUnits *wu) {
2842
2843 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
2844 const char *path;
2845 bool done = false;
2846 int r;
2847
2848 assert(method);
2849 assert(name);
2850 assert(mode);
2851 assert(error);
2852
2853 log_debug("%s dbus call org.freedesktop.systemd1.Manager %s(%s, %s)",
2854 arg_dry_run ? "Would execute" : "Executing",
2855 method, name, mode);
2856
2857 if (arg_dry_run)
2858 return 0;
2859
2860 if (arg_show_transaction) {
2861 _cleanup_(sd_bus_error_free) sd_bus_error enqueue_error = SD_BUS_ERROR_NULL;
2862
2863 /* Use the new, fancy EnqueueUnitJob() API if the user wants us to print the transaction */
2864 r = bus_call_method(
2865 bus,
2866 bus_systemd_mgr,
2867 "EnqueueUnitJob",
2868 &enqueue_error,
2869 &reply,
2870 "sss",
2871 name, job_type, mode);
2872 if (r < 0) {
2873 if (!sd_bus_error_has_name(&enqueue_error, SD_BUS_ERROR_UNKNOWN_METHOD)) {
2874 (void) sd_bus_error_move(error, &enqueue_error);
2875 goto fail;
2876 }
2877
2878 /* Hmm, the API is not yet available. Let's use the classic API instead (see below). */
2879 log_notice("--show-transaction not supported by this service manager, proceeding without.");
2880 } else {
2881 const char *u, *jt;
2882 uint32_t id;
2883
2884 r = sd_bus_message_read(reply, "uosos", &id, &path, &u, NULL, &jt);
2885 if (r < 0)
2886 return bus_log_parse_error(r);
2887
2888 log_info("Enqueued anchor job %" PRIu32 " %s/%s.", id, u, jt);
2889
2890 r = sd_bus_message_enter_container(reply, 'a', "(uosos)");
2891 if (r < 0)
2892 return bus_log_parse_error(r);
2893 for (;;) {
2894 r = sd_bus_message_read(reply, "(uosos)", &id, NULL, &u, NULL, &jt);
2895 if (r < 0)
2896 return bus_log_parse_error(r);
2897 if (r == 0)
2898 break;
2899
2900 log_info("Enqueued auxiliary job %" PRIu32 " %s/%s.", id, u, jt);
2901 }
2902
2903 r = sd_bus_message_exit_container(reply);
2904 if (r < 0)
2905 return bus_log_parse_error(r);
2906
2907 done = true;
2908 }
2909 }
2910
2911 if (!done) {
2912 r = bus_call_method(bus, bus_systemd_mgr, method, error, &reply, "ss", name, mode);
2913 if (r < 0)
2914 goto fail;
2915
2916 r = sd_bus_message_read(reply, "o", &path);
2917 if (r < 0)
2918 return bus_log_parse_error(r);
2919 }
2920
2921 if (need_daemon_reload(bus, name) > 0)
2922 warn_unit_file_changed(name);
2923
2924 if (w) {
2925 log_debug("Adding %s to the set", path);
2926 r = bus_wait_for_jobs_add(w, path);
2927 if (r < 0)
2928 return log_error_errno(r, "Failed to watch job for %s: %m", name);
2929 }
2930
2931 if (wu) {
2932 r = bus_wait_for_units_add_unit(wu, name, BUS_WAIT_FOR_INACTIVE|BUS_WAIT_NO_JOB, NULL, NULL);
2933 if (r < 0)
2934 return log_error_errno(r, "Failed to watch unit %s: %m", name);
2935 }
2936
2937 return 0;
2938
2939 fail:
2940 /* There's always a fallback possible for legacy actions. */
2941 if (arg_action != ACTION_SYSTEMCTL)
2942 return r;
2943
2944 log_error_errno(r, "Failed to %s %s: %s", job_type, name, bus_error_message(error, r));
2945
2946 if (!sd_bus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT) &&
2947 !sd_bus_error_has_name(error, BUS_ERROR_UNIT_MASKED) &&
2948 !sd_bus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE))
2949 log_error("See %s logs and 'systemctl%s status%s %s' for details.",
2950 arg_scope == UNIT_FILE_SYSTEM ? "system" : "user",
2951 arg_scope == UNIT_FILE_SYSTEM ? "" : " --user",
2952 name[0] == '-' ? " --" : "",
2953 name);
2954
2955 return r;
2956 }
2957
2958 static const struct {
2959 const char *target;
2960 const char *verb;
2961 const char *mode;
2962 } action_table[_ACTION_MAX] = {
2963 [ACTION_HALT] = { SPECIAL_HALT_TARGET, "halt", "replace-irreversibly" },
2964 [ACTION_POWEROFF] = { SPECIAL_POWEROFF_TARGET, "poweroff", "replace-irreversibly" },
2965 [ACTION_REBOOT] = { SPECIAL_REBOOT_TARGET, "reboot", "replace-irreversibly" },
2966 [ACTION_KEXEC] = { SPECIAL_KEXEC_TARGET, "kexec", "replace-irreversibly" },
2967 [ACTION_RUNLEVEL2] = { SPECIAL_MULTI_USER_TARGET, NULL, "isolate" },
2968 [ACTION_RUNLEVEL3] = { SPECIAL_MULTI_USER_TARGET, NULL, "isolate" },
2969 [ACTION_RUNLEVEL4] = { SPECIAL_MULTI_USER_TARGET, NULL, "isolate" },
2970 [ACTION_RUNLEVEL5] = { SPECIAL_GRAPHICAL_TARGET, NULL, "isolate" },
2971 [ACTION_RESCUE] = { SPECIAL_RESCUE_TARGET, "rescue", "isolate" },
2972 [ACTION_EMERGENCY] = { SPECIAL_EMERGENCY_TARGET, "emergency", "isolate" },
2973 [ACTION_DEFAULT] = { SPECIAL_DEFAULT_TARGET, "default", "isolate" },
2974 [ACTION_EXIT] = { SPECIAL_EXIT_TARGET, "exit", "replace-irreversibly" },
2975 [ACTION_SUSPEND] = { SPECIAL_SUSPEND_TARGET, "suspend", "replace-irreversibly" },
2976 [ACTION_HIBERNATE] = { SPECIAL_HIBERNATE_TARGET, "hibernate", "replace-irreversibly" },
2977 [ACTION_HYBRID_SLEEP] = { SPECIAL_HYBRID_SLEEP_TARGET, "hybrid-sleep", "replace-irreversibly" },
2978 [ACTION_SUSPEND_THEN_HIBERNATE] = { SPECIAL_SUSPEND_THEN_HIBERNATE_TARGET, "suspend-then-hibernate", "replace-irreversibly" },
2979 };
2980
2981 static enum action verb_to_action(const char *verb) {
2982 enum action i;
2983
2984 for (i = 0; i < _ACTION_MAX; i++)
2985 if (streq_ptr(action_table[i].verb, verb))
2986 return i;
2987
2988 return _ACTION_INVALID;
2989 }
2990
2991 static const char** make_extra_args(const char *extra_args[static 4]) {
2992 size_t n = 0;
2993
2994 assert(extra_args);
2995
2996 if (arg_scope != UNIT_FILE_SYSTEM)
2997 extra_args[n++] = "--user";
2998
2999 if (arg_transport == BUS_TRANSPORT_REMOTE) {
3000 extra_args[n++] = "-H";
3001 extra_args[n++] = arg_host;
3002 } else if (arg_transport == BUS_TRANSPORT_MACHINE) {
3003 extra_args[n++] = "-M";
3004 extra_args[n++] = arg_host;
3005 } else
3006 assert(arg_transport == BUS_TRANSPORT_LOCAL);
3007
3008 extra_args[n] = NULL;
3009 return extra_args;
3010 }
3011
3012 static int start_unit(int argc, char *argv[], void *userdata) {
3013 _cleanup_(bus_wait_for_units_freep) BusWaitForUnits *wu = NULL;
3014 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
3015 const char *method, *job_type, *mode, *one_name, *suffix = NULL;
3016 _cleanup_free_ char **stopped_units = NULL; /* Do not use _cleanup_strv_free_ */
3017 _cleanup_strv_free_ char **names = NULL;
3018 int r, ret = EXIT_SUCCESS;
3019 sd_bus *bus;
3020 char **name;
3021
3022 if (arg_wait && !STR_IN_SET(argv[0], "start", "restart"))
3023 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3024 "--wait may only be used with the 'start' or 'restart' commands.");
3025
3026 /* we cannot do sender tracking on the private bus, so we need the full
3027 * one for RefUnit to implement --wait */
3028 r = acquire_bus(arg_wait ? BUS_FULL : BUS_MANAGER, &bus);
3029 if (r < 0)
3030 return r;
3031
3032 ask_password_agent_open_maybe();
3033 polkit_agent_open_maybe();
3034
3035 if (arg_action == ACTION_SYSTEMCTL) {
3036 enum action action;
3037
3038 action = verb_to_action(argv[0]);
3039
3040 if (action != _ACTION_INVALID) {
3041 /* A command in style "systemctl reboot", "systemctl poweroff", … */
3042 method = "StartUnit";
3043 job_type = "start";
3044 mode = action_table[action].mode;
3045 one_name = action_table[action].target;
3046 } else {
3047 if (streq(argv[0], "isolate")) {
3048 /* A "systemctl isolate <unit1> <unit2> …" command */
3049 method = "StartUnit";
3050 job_type = "start";
3051 mode = "isolate";
3052 suffix = ".target";
3053 } else {
3054 /* A command in style of "systemctl start <unit1> <unit2> …", "sysemctl stop <unit1> <unit2> …" and so on */
3055 method = verb_to_method(argv[0]);
3056 job_type = verb_to_job_type(argv[0]);
3057 mode = arg_job_mode;
3058 }
3059 one_name = NULL;
3060 }
3061 } else {
3062 /* A SysV legacy command such as "halt", "reboot", "poweroff", … */
3063 assert(arg_action >= 0 && arg_action < _ACTION_MAX);
3064 assert(action_table[arg_action].target);
3065 assert(action_table[arg_action].mode);
3066
3067 method = "StartUnit";
3068 job_type = "start";
3069 mode = action_table[arg_action].mode;
3070 one_name = action_table[arg_action].target;
3071 }
3072
3073 if (one_name) {
3074 names = strv_new(one_name);
3075 if (!names)
3076 return log_oom();
3077 } else {
3078 bool expanded;
3079
3080 r = expand_names(bus, strv_skip(argv, 1), suffix, &names, &expanded);
3081 if (r < 0)
3082 return log_error_errno(r, "Failed to expand names: %m");
3083
3084 if (!arg_all && expanded && streq(job_type, "start") && !arg_quiet) {
3085 log_warning("Warning: %ssystemctl start called with a glob pattern.%s",
3086 ansi_highlight_red(),
3087 ansi_normal());
3088 log_notice("Hint: unit globs expand to loaded units, so start will usually have no effect.\n"
3089 " Passing --all will also load units which are pulled in by other units.\n"
3090 " See systemctl(1) for more details.");
3091 }
3092 }
3093
3094 if (!arg_no_block) {
3095 r = bus_wait_for_jobs_new(bus, &w);
3096 if (r < 0)
3097 return log_error_errno(r, "Could not watch jobs: %m");
3098 }
3099
3100 if (arg_wait) {
3101 r = bus_call_method_async(bus, NULL, bus_systemd_mgr, "Subscribe", NULL, NULL, NULL);
3102 if (r < 0)
3103 return log_error_errno(r, "Failed to enable subscription: %m");
3104
3105 r = bus_wait_for_units_new(bus, &wu);
3106 if (r < 0)
3107 return log_error_errno(r, "Failed to allocate unit watch context: %m");
3108 }
3109
3110 STRV_FOREACH(name, names) {
3111 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3112
3113 r = start_unit_one(bus, method, job_type, *name, mode, &error, w, wu);
3114 if (ret == EXIT_SUCCESS && r < 0)
3115 ret = translate_bus_error_to_exit_status(r, &error);
3116
3117 if (r >= 0 && streq(method, "StopUnit")) {
3118 r = strv_push(&stopped_units, *name);
3119 if (r < 0)
3120 return log_oom();
3121 }
3122 }
3123
3124 if (!arg_no_block) {
3125 const char* extra_args[4];
3126
3127 r = bus_wait_for_jobs(w, arg_quiet, make_extra_args(extra_args));
3128 if (r < 0)
3129 return r;
3130
3131 /* When stopping units, warn if they can still be triggered by
3132 * another active unit (socket, path, timer) */
3133 if (!arg_quiet)
3134 STRV_FOREACH(name, stopped_units)
3135 (void) check_triggering_units(bus, *name);
3136 }
3137
3138 if (arg_wait) {
3139 r = bus_wait_for_units_run(wu);
3140 if (r < 0)
3141 return log_error_errno(r, "Failed to wait for units: %m");
3142 if (r == BUS_WAIT_FAILURE && ret == EXIT_SUCCESS)
3143 ret = EXIT_FAILURE;
3144 }
3145
3146 return ret;
3147 }
3148
3149 #if ENABLE_LOGIND
3150 static int logind_set_wall_message(void) {
3151 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3152 sd_bus *bus;
3153 _cleanup_free_ char *m = NULL;
3154 int r;
3155
3156 r = acquire_bus(BUS_FULL, &bus);
3157 if (r < 0)
3158 return r;
3159
3160 m = strv_join(arg_wall, " ");
3161 if (!m)
3162 return log_oom();
3163
3164 log_debug("%s wall message \"%s\".", arg_dry_run ? "Would set" : "Setting", m);
3165 if (arg_dry_run)
3166 return 0;
3167
3168 r = bus_call_method(bus, bus_login_mgr, "SetWallMessage", &error, NULL, "sb", m, !arg_no_wall);
3169 if (r < 0)
3170 return log_warning_errno(r, "Failed to set wall message, ignoring: %s", bus_error_message(&error, r));
3171 return 0;
3172 }
3173 #endif
3174
3175 /* Ask systemd-logind, which might grant access to unprivileged users through polkit */
3176 static int logind_reboot(enum action a) {
3177 #if ENABLE_LOGIND
3178 static const struct {
3179 const char *method;
3180 const char *description;
3181 } actions[_ACTION_MAX] = {
3182 [ACTION_POWEROFF] = { "PowerOff", "power off system" },
3183 [ACTION_REBOOT] = { "Reboot", "reboot system" },
3184 [ACTION_HALT] = { "Halt", "halt system" },
3185 [ACTION_SUSPEND] = { "Suspend", "suspend system" },
3186 [ACTION_HIBERNATE] = { "Hibernate", "hibernate system" },
3187 [ACTION_HYBRID_SLEEP] = { "HybridSleep", "put system into hybrid sleep" },
3188 [ACTION_SUSPEND_THEN_HIBERNATE] = { "SuspendThenHibernate", "suspend system, hibernate later" },
3189 };
3190
3191 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3192 sd_bus *bus;
3193 int r;
3194
3195 if (a < 0 || a >= _ACTION_MAX || !actions[a].method)
3196 return -EINVAL;
3197
3198 r = acquire_bus(BUS_FULL, &bus);
3199 if (r < 0)
3200 return r;
3201
3202 polkit_agent_open_maybe();
3203 (void) logind_set_wall_message();
3204
3205 log_debug("%s org.freedesktop.login1.Manager %s dbus call.", arg_dry_run ? "Would execute" : "Executing", actions[a].method);
3206
3207 if (arg_dry_run)
3208 return 0;
3209
3210 r = bus_call_method(bus, bus_login_mgr, actions[a].method, &error, NULL, "b", arg_ask_password);
3211 if (r < 0)
3212 return log_error_errno(r, "Failed to %s via logind: %s", actions[a].description, bus_error_message(&error, r));
3213
3214 return 0;
3215 #else
3216 return -ENOSYS;
3217 #endif
3218 }
3219
3220 static int logind_check_inhibitors(enum action a) {
3221 #if ENABLE_LOGIND
3222 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
3223 _cleanup_strv_free_ char **sessions = NULL;
3224 const char *what, *who, *why, *mode;
3225 uint32_t uid, pid;
3226 sd_bus *bus;
3227 unsigned c = 0;
3228 char **s;
3229 int r;
3230
3231 if (arg_ignore_inhibitors || arg_force > 0)
3232 return 0;
3233
3234 if (arg_when > 0)
3235 return 0;
3236
3237 if (geteuid() == 0)
3238 return 0;
3239
3240 if (!on_tty())
3241 return 0;
3242
3243 if (arg_transport != BUS_TRANSPORT_LOCAL)
3244 return 0;
3245
3246 r = acquire_bus(BUS_FULL, &bus);
3247 if (r < 0)
3248 return r;
3249
3250 r = bus_call_method(bus, bus_login_mgr, "ListInhibitors", NULL, &reply, NULL);
3251 if (r < 0)
3252 /* If logind is not around, then there are no inhibitors... */
3253 return 0;
3254
3255 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssuu)");
3256 if (r < 0)
3257 return bus_log_parse_error(r);
3258
3259 while ((r = sd_bus_message_read(reply, "(ssssuu)", &what, &who, &why, &mode, &uid, &pid)) > 0) {
3260 _cleanup_free_ char *comm = NULL, *user = NULL;
3261 _cleanup_strv_free_ char **sv = NULL;
3262
3263 if (!streq(mode, "block"))
3264 continue;
3265
3266 sv = strv_split(what, ":");
3267 if (!sv)
3268 return log_oom();
3269
3270 if (!pid_is_valid((pid_t) pid))
3271 return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Invalid PID "PID_FMT".", (pid_t) pid);
3272
3273 if (!strv_contains(sv,
3274 IN_SET(a,
3275 ACTION_HALT,
3276 ACTION_POWEROFF,
3277 ACTION_REBOOT,
3278 ACTION_KEXEC) ? "shutdown" : "sleep"))
3279 continue;
3280
3281 get_process_comm(pid, &comm);
3282 user = uid_to_name(uid);
3283
3284 log_warning("Operation inhibited by \"%s\" (PID "PID_FMT" \"%s\", user %s), reason is \"%s\".",
3285 who, (pid_t) pid, strna(comm), strna(user), why);
3286
3287 c++;
3288 }
3289 if (r < 0)
3290 return bus_log_parse_error(r);
3291
3292 r = sd_bus_message_exit_container(reply);
3293 if (r < 0)
3294 return bus_log_parse_error(r);
3295
3296 /* Check for current sessions */
3297 sd_get_sessions(&sessions);
3298 STRV_FOREACH(s, sessions) {
3299 _cleanup_free_ char *type = NULL, *tty = NULL, *seat = NULL, *user = NULL, *service = NULL, *class = NULL;
3300
3301 if (sd_session_get_uid(*s, &uid) < 0 || uid == getuid())
3302 continue;
3303
3304 if (sd_session_get_class(*s, &class) < 0 || !streq(class, "user"))
3305 continue;
3306
3307 if (sd_session_get_type(*s, &type) < 0 || !STR_IN_SET(type, "x11", "wayland", "tty", "mir"))
3308 continue;
3309
3310 sd_session_get_tty(*s, &tty);
3311 sd_session_get_seat(*s, &seat);
3312 sd_session_get_service(*s, &service);
3313 user = uid_to_name(uid);
3314
3315 log_warning("User %s is logged in on %s.", strna(user), isempty(tty) ? (isempty(seat) ? strna(service) : seat) : tty);
3316 c++;
3317 }
3318
3319 if (c <= 0)
3320 return 0;
3321
3322 log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'systemctl %s -i'.",
3323 action_table[a].verb);
3324
3325 return -EPERM;
3326 #else
3327 return 0;
3328 #endif
3329 }
3330
3331 static int prepare_firmware_setup(void) {
3332
3333 if (!arg_firmware_setup)
3334 return 0;
3335
3336 #if ENABLE_LOGIND
3337 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3338 sd_bus *bus;
3339 int r;
3340
3341 r = acquire_bus(BUS_FULL, &bus);
3342 if (r < 0)
3343 return r;
3344
3345 r = bus_call_method(bus, bus_login_mgr, "SetRebootToFirmwareSetup", &error, NULL, "b", true);
3346 if (r < 0)
3347 return log_error_errno(r, "Cannot indicate to EFI to boot into setup mode: %s", bus_error_message(&error, r));
3348
3349 return 0;
3350 #else
3351 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS),
3352 "Booting into firmware setup not supported.");
3353 #endif
3354 }
3355
3356 static int prepare_boot_loader_menu(void) {
3357
3358 if (arg_boot_loader_menu == USEC_INFINITY)
3359 return 0;
3360
3361 #if ENABLE_LOGIND
3362 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3363 sd_bus *bus;
3364 int r;
3365
3366 r = acquire_bus(BUS_FULL, &bus);
3367 if (r < 0)
3368 return r;
3369
3370 r = bus_call_method(bus, bus_login_mgr, "SetRebootToBootLoaderMenu", &error, NULL, "t", arg_boot_loader_menu);
3371 if (r < 0)
3372 return log_error_errno(r, "Cannot indicate to boot loader to enter boot loader entry menu: %s", bus_error_message(&error, r));
3373
3374 return 0;
3375 #else
3376 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS),
3377 "Booting into boot loader menu not supported.");
3378 #endif
3379 }
3380
3381 static int prepare_boot_loader_entry(void) {
3382
3383 if (!arg_boot_loader_entry)
3384 return 0;
3385
3386 #if ENABLE_LOGIND
3387 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3388 sd_bus *bus;
3389 int r;
3390
3391 r = acquire_bus(BUS_FULL, &bus);
3392 if (r < 0)
3393 return r;
3394
3395 r = bus_call_method(bus, bus_login_mgr, "SetRebootToBootLoaderEntry", &error, NULL, "s", arg_boot_loader_entry);
3396 if (r < 0)
3397 return log_error_errno(r, "Cannot set boot into loader entry '%s': %s", arg_boot_loader_entry, bus_error_message(&error, r));
3398
3399 return 0;
3400 #else
3401 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS),
3402 "Booting into boot loader entry not supported.");
3403 #endif
3404 }
3405
3406 static int load_kexec_kernel(void) {
3407 _cleanup_(boot_config_free) BootConfig config = {};
3408 _cleanup_free_ char *kernel = NULL, *initrd = NULL, *options = NULL;
3409 const BootEntry *e;
3410 pid_t pid;
3411 int r;
3412
3413 if (kexec_loaded()) {
3414 log_debug("Kexec kernel already loaded.");
3415 return 0;
3416 }
3417
3418 if (access(KEXEC, X_OK) < 0)
3419 return log_error_errno(errno, KEXEC" is not available: %m");
3420
3421 r = boot_entries_load_config_auto(NULL, NULL, &config);
3422 if (r == -ENOKEY)
3423 /* The call doesn't log about ENOKEY, let's do so here. */
3424 return log_error_errno(r,
3425 "No kexec kernel loaded and autodetection failed.\n%s",
3426 is_efi_boot()
3427 ? "Cannot automatically load kernel: ESP partition mount point not found."
3428 : "Automatic loading works only on systems booted with EFI.");
3429 if (r < 0)
3430 return r;
3431
3432 e = boot_config_default_entry(&config);
3433 if (!e)
3434 return log_error_errno(SYNTHETIC_ERRNO(ENOENT),
3435 "No boot loader entry suitable as default, refusing to guess.");
3436
3437 log_debug("Found default boot loader entry in file \"%s\"", e->path);
3438
3439 if (!e->kernel)
3440 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
3441 "Boot entry does not refer to Linux kernel, which is not supported currently.");
3442 if (strv_length(e->initrd) > 1)
3443 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
3444 "Boot entry specifies multiple initrds, which is not supported currently.");
3445
3446 kernel = path_join(e->root, e->kernel);
3447 if (!kernel)
3448 return log_oom();
3449
3450 if (!strv_isempty(e->initrd)) {
3451 initrd = path_join(e->root, e->initrd[0]);
3452 if (!initrd)
3453 return log_oom();
3454 }
3455
3456 options = strv_join(e->options, " ");
3457 if (!options)
3458 return log_oom();
3459
3460 log_full(arg_quiet ? LOG_DEBUG : LOG_INFO,
3461 "%s "KEXEC" --load \"%s\" --append \"%s\"%s%s%s",
3462 arg_dry_run ? "Would run" : "Running",
3463 kernel,
3464 options,
3465 initrd ? " --initrd \"" : NULL, strempty(initrd), initrd ? "\"" : "");
3466 if (arg_dry_run)
3467 return 0;
3468
3469 r = safe_fork("(kexec)", FORK_WAIT|FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG, &pid);
3470 if (r < 0)
3471 return r;
3472 if (r == 0) {
3473 const char* const args[] = {
3474 KEXEC,
3475 "--load", kernel,
3476 "--append", options,
3477 initrd ? "--initrd" : NULL, initrd,
3478 NULL
3479 };
3480
3481 /* Child */
3482 execv(args[0], (char * const *) args);
3483 _exit(EXIT_FAILURE);
3484 }
3485
3486 return 0;
3487 }
3488
3489 static int set_exit_code(uint8_t code) {
3490 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3491 sd_bus *bus;
3492 int r;
3493
3494 r = acquire_bus(BUS_MANAGER, &bus);
3495 if (r < 0)
3496 return r;
3497
3498 r = bus_call_method(bus, bus_systemd_mgr, "SetExitCode", &error, NULL, "y", code);
3499 if (r < 0)
3500 return log_error_errno(r, "Failed to set exit code: %s", bus_error_message(&error, r));
3501
3502 return 0;
3503 }
3504
3505 static int start_special(int argc, char *argv[], void *userdata) {
3506 enum action a;
3507 int r;
3508 bool termination_action; /* an action that terminates the manager,
3509 * can be performed also by signal. */
3510
3511 assert(argv);
3512
3513 a = verb_to_action(argv[0]);
3514
3515 r = logind_check_inhibitors(a);
3516 if (r < 0)
3517 return r;
3518
3519 if (arg_force >= 2) {
3520 r = must_be_root();
3521 if (r < 0)
3522 return r;
3523 }
3524
3525 r = prepare_firmware_setup();
3526 if (r < 0)
3527 return r;
3528
3529 r = prepare_boot_loader_menu();
3530 if (r < 0)
3531 return r;
3532
3533 r = prepare_boot_loader_entry();
3534 if (r < 0)
3535 return r;
3536
3537 if (a == ACTION_REBOOT) {
3538 const char *arg = NULL;
3539
3540 if (argc > 1) {
3541 if (arg_reboot_argument)
3542 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Both --reboot-argument= and positional argument passed to reboot command, refusing.");
3543
3544 log_notice("Positional argument to reboot command is deprecated, please use --reboot-argument= instead. Accepting anyway.");
3545 arg = argv[1];
3546 } else
3547 arg = arg_reboot_argument;
3548
3549 if (arg) {
3550 r = update_reboot_parameter_and_warn(arg, false);
3551 if (r < 0)
3552 return r;
3553 }
3554
3555 } else if (a == ACTION_KEXEC) {
3556 r = load_kexec_kernel();
3557 if (r < 0 && arg_force >= 1)
3558 log_notice("Failed to load kexec kernel, continuing without.");
3559 else if (r < 0)
3560 return r;
3561
3562 } else if (a == ACTION_EXIT && argc > 1) {
3563 uint8_t code;
3564
3565 /* If the exit code is not given on the command line,
3566 * don't reset it to zero: just keep it as it might
3567 * have been set previously. */
3568
3569 r = safe_atou8(argv[1], &code);
3570 if (r < 0)
3571 return log_error_errno(r, "Invalid exit code.");
3572
3573 r = set_exit_code(code);
3574 if (r < 0)
3575 return r;
3576 }
3577
3578 termination_action = IN_SET(a,
3579 ACTION_HALT,
3580 ACTION_POWEROFF,
3581 ACTION_REBOOT);
3582 if (termination_action && arg_force >= 2)
3583 return halt_now(a);
3584
3585 if (arg_force >= 1 &&
3586 (termination_action || IN_SET(a, ACTION_KEXEC, ACTION_EXIT)))
3587 r = trivial_method(argc, argv, userdata);
3588 else {
3589 /* First try logind, to allow authentication with polkit */
3590 if (IN_SET(a,
3591 ACTION_POWEROFF,
3592 ACTION_REBOOT,
3593 ACTION_HALT,
3594 ACTION_SUSPEND,
3595 ACTION_HIBERNATE,
3596 ACTION_HYBRID_SLEEP,
3597 ACTION_SUSPEND_THEN_HIBERNATE)) {
3598
3599 r = logind_reboot(a);
3600 if (r >= 0)
3601 return r;
3602 if (IN_SET(r, -EOPNOTSUPP, -EINPROGRESS))
3603 /* requested operation is not supported or already in progress */
3604 return r;
3605
3606 /* On all other errors, try low-level operation. In order to minimize the difference between
3607 * operation with and without logind, we explicitly enable non-blocking mode for this, as
3608 * logind's shutdown operations are always non-blocking. */
3609
3610 arg_no_block = true;
3611
3612 } else if (IN_SET(a, ACTION_EXIT, ACTION_KEXEC))
3613 /* Since exit/kexec are so close in behaviour to power-off/reboot, let's also make them
3614 * asynchronous, in order to not confuse the user needlessly with unexpected behaviour. */
3615 arg_no_block = true;
3616
3617 r = start_unit(argc, argv, userdata);
3618 }
3619
3620 if (termination_action && arg_force < 2 &&
3621 IN_SET(r, -ENOENT, -ETIMEDOUT))
3622 log_notice("It is possible to perform action directly, see discussion of --force --force in man:systemctl(1).");
3623
3624 return r;
3625 }
3626
3627 static int start_system_special(int argc, char *argv[], void *userdata) {
3628 /* Like start_special above, but raises an error when running in user mode */
3629
3630 if (arg_scope != UNIT_FILE_SYSTEM)
3631 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3632 "Bad action for %s mode.",
3633 arg_scope == UNIT_FILE_GLOBAL ? "--global" : "--user");
3634
3635 return start_special(argc, argv, userdata);
3636 }
3637
3638 static int check_unit_generic(int code, const UnitActiveState good_states[], int nb_states, char **args) {
3639 _cleanup_strv_free_ char **names = NULL;
3640 UnitActiveState active_state;
3641 sd_bus *bus;
3642 char **name;
3643 int r, i;
3644 bool found = false;
3645
3646 r = acquire_bus(BUS_MANAGER, &bus);
3647 if (r < 0)
3648 return r;
3649
3650 r = expand_names(bus, args, NULL, &names, NULL);
3651 if (r < 0)
3652 return log_error_errno(r, "Failed to expand names: %m");
3653
3654 STRV_FOREACH(name, names) {
3655 r = get_state_one_unit(bus, *name, &active_state);
3656 if (r < 0)
3657 return r;
3658
3659 if (!arg_quiet)
3660 puts(unit_active_state_to_string(active_state));
3661
3662 for (i = 0; i < nb_states; ++i)
3663 if (good_states[i] == active_state)
3664 found = true;
3665 }
3666
3667 /* use the given return code for the case that we won't find
3668 * any unit which matches the list */
3669 return found ? 0 : code;
3670 }
3671
3672 static int check_unit_active(int argc, char *argv[], void *userdata) {
3673 static const UnitActiveState states[] = {
3674 UNIT_ACTIVE,
3675 UNIT_RELOADING,
3676 };
3677
3678 /* According to LSB: 3, "program is not running" */
3679 return check_unit_generic(EXIT_PROGRAM_NOT_RUNNING, states, ELEMENTSOF(states), strv_skip(argv, 1));
3680 }
3681
3682 static int check_unit_failed(int argc, char *argv[], void *userdata) {
3683 static const UnitActiveState states[] = {
3684 UNIT_FAILED,
3685 };
3686
3687 return check_unit_generic(EXIT_PROGRAM_DEAD_AND_PID_EXISTS, states, ELEMENTSOF(states), strv_skip(argv, 1));
3688 }
3689
3690 static int kill_unit(int argc, char *argv[], void *userdata) {
3691 _cleanup_strv_free_ char **names = NULL;
3692 char *kill_who = NULL, **name;
3693 sd_bus *bus;
3694 int r, q;
3695
3696 r = acquire_bus(BUS_MANAGER, &bus);
3697 if (r < 0)
3698 return r;
3699
3700 polkit_agent_open_maybe();
3701
3702 if (!arg_kill_who)
3703 arg_kill_who = "all";
3704
3705 /* --fail was specified */
3706 if (streq(arg_job_mode, "fail"))
3707 kill_who = strjoina(arg_kill_who, "-fail");
3708
3709 r = expand_names(bus, strv_skip(argv, 1), NULL, &names, NULL);
3710 if (r < 0)
3711 return log_error_errno(r, "Failed to expand names: %m");
3712
3713 STRV_FOREACH(name, names) {
3714 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3715
3716 q = bus_call_method(
3717 bus,
3718 bus_systemd_mgr,
3719 "KillUnit",
3720 &error,
3721 NULL,
3722 "ssi", *name, kill_who ? kill_who : arg_kill_who, arg_signal);
3723 if (q < 0) {
3724 log_error_errno(q, "Failed to kill unit %s: %s", *name, bus_error_message(&error, q));
3725 if (r == 0)
3726 r = q;
3727 }
3728 }
3729
3730 return r;
3731 }
3732
3733 static int clean_or_freeze_unit(int argc, char *argv[], void *userdata) {
3734 _cleanup_(bus_wait_for_units_freep) BusWaitForUnits *w = NULL;
3735 _cleanup_strv_free_ char **names = NULL;
3736 int r, ret = EXIT_SUCCESS;
3737 char **name;
3738 const char *method;
3739 sd_bus *bus;
3740
3741 r = acquire_bus(BUS_FULL, &bus);
3742 if (r < 0)
3743 return r;
3744
3745 polkit_agent_open_maybe();
3746
3747 if (!arg_clean_what) {
3748 arg_clean_what = strv_new("cache", "runtime");
3749 if (!arg_clean_what)
3750 return log_oom();
3751 }
3752
3753 r = expand_names(bus, strv_skip(argv, 1), NULL, &names, NULL);
3754 if (r < 0)
3755 return log_error_errno(r, "Failed to expand names: %m");
3756
3757 if (!arg_no_block) {
3758 r = bus_wait_for_units_new(bus, &w);
3759 if (r < 0)
3760 return log_error_errno(r, "Failed to allocate unit waiter: %m");
3761 }
3762
3763 if (streq(argv[0], "clean"))
3764 method = "CleanUnit";
3765 else if (streq(argv[0], "freeze"))
3766 method = "FreezeUnit";
3767 else if (streq(argv[0], "thaw"))
3768 method = "ThawUnit";
3769 else
3770 assert_not_reached("Unhandled method");
3771
3772 STRV_FOREACH(name, names) {
3773 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3774 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
3775
3776 if (w) {
3777 /* If we shall wait for the cleaning to complete, let's add a ref on the unit first */
3778 r = bus_call_method(bus, bus_systemd_mgr, "RefUnit", &error, NULL, "s", *name);
3779 if (r < 0) {
3780 log_error_errno(r, "Failed to add reference to unit %s: %s", *name, bus_error_message(&error, r));
3781 if (ret == EXIT_SUCCESS)
3782 ret = r;
3783 continue;
3784 }
3785 }
3786
3787 r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, method);
3788 if (r < 0)
3789 return bus_log_create_error(r);
3790
3791 r = sd_bus_message_append(m, "s", *name);
3792 if (r < 0)
3793 return bus_log_create_error(r);
3794
3795 if (streq(method, "CleanUnit")) {
3796 r = sd_bus_message_append_strv(m, arg_clean_what);
3797 if (r < 0)
3798 return bus_log_create_error(r);
3799 }
3800
3801 r = sd_bus_call(bus, m, 0, &error, NULL);
3802 if (r < 0) {
3803 log_error_errno(r, "Failed to %s unit %s: %s", argv[0], *name, bus_error_message(&error, r));
3804 if (ret == EXIT_SUCCESS) {
3805 ret = r;
3806 continue;
3807 }
3808 }
3809
3810 if (w) {
3811 r = bus_wait_for_units_add_unit(w, *name, BUS_WAIT_REFFED|BUS_WAIT_FOR_MAINTENANCE_END, NULL, NULL);
3812 if (r < 0)
3813 return log_error_errno(r, "Failed to watch unit %s: %m", *name);
3814 }
3815 }
3816
3817 r = bus_wait_for_units_run(w);
3818 if (r < 0)
3819 return log_error_errno(r, "Failed to wait for units: %m");
3820 if (r == BUS_WAIT_FAILURE)
3821 ret = EXIT_FAILURE;
3822
3823 return ret;
3824 }
3825
3826 typedef struct ExecStatusInfo {
3827 char *name;
3828
3829 char *path;
3830 char **argv;
3831
3832 bool ignore;
3833
3834 usec_t start_timestamp;
3835 usec_t exit_timestamp;
3836 pid_t pid;
3837 int code;
3838 int status;
3839
3840 ExecCommandFlags flags;
3841
3842 LIST_FIELDS(struct ExecStatusInfo, exec);
3843 } ExecStatusInfo;
3844
3845 static void exec_status_info_free(ExecStatusInfo *i) {
3846 assert(i);
3847
3848 free(i->name);
3849 free(i->path);
3850 strv_free(i->argv);
3851 free(i);
3852 }
3853
3854 static int exec_status_info_deserialize(sd_bus_message *m, ExecStatusInfo *i, bool is_ex_prop) {
3855 _cleanup_strv_free_ char **ex_opts = NULL;
3856 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
3857 const char *path;
3858 uint32_t pid;
3859 int32_t code, status;
3860 int ignore, r;
3861
3862 assert(m);
3863 assert(i);
3864
3865 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_STRUCT, is_ex_prop ? "sasasttttuii" : "sasbttttuii");
3866 if (r < 0)
3867 return bus_log_parse_error(r);
3868 else if (r == 0)
3869 return 0;
3870
3871 r = sd_bus_message_read(m, "s", &path);
3872 if (r < 0)
3873 return bus_log_parse_error(r);
3874
3875 i->path = strdup(path);
3876 if (!i->path)
3877 return log_oom();
3878
3879 r = sd_bus_message_read_strv(m, &i->argv);
3880 if (r < 0)
3881 return bus_log_parse_error(r);
3882
3883 r = is_ex_prop ? sd_bus_message_read_strv(m, &ex_opts) : sd_bus_message_read(m, "b", &ignore);
3884 if (r < 0)
3885 return bus_log_parse_error(r);
3886
3887 r = sd_bus_message_read(m,
3888 "ttttuii",
3889 &start_timestamp, &start_timestamp_monotonic,
3890 &exit_timestamp, &exit_timestamp_monotonic,
3891 &pid,
3892 &code, &status);
3893 if (r < 0)
3894 return bus_log_parse_error(r);
3895
3896 if (is_ex_prop) {
3897 r = exec_command_flags_from_strv(ex_opts, &i->flags);
3898 if (r < 0)
3899 return log_error_errno(r, "Failed to convert strv to ExecCommandFlags: %m");
3900
3901 i->ignore = FLAGS_SET(i->flags, EXEC_COMMAND_IGNORE_FAILURE);
3902 } else
3903 i->ignore = ignore;
3904
3905 i->start_timestamp = (usec_t) start_timestamp;
3906 i->exit_timestamp = (usec_t) exit_timestamp;
3907 i->pid = (pid_t) pid;
3908 i->code = code;
3909 i->status = status;
3910
3911 r = sd_bus_message_exit_container(m);
3912 if (r < 0)
3913 return bus_log_parse_error(r);
3914
3915 return 1;
3916 }
3917
3918 typedef struct UnitCondition {
3919 char *name;
3920 char *param;
3921 bool trigger;
3922 bool negate;
3923 int tristate;
3924
3925 LIST_FIELDS(struct UnitCondition, conditions);
3926 } UnitCondition;
3927
3928 static void unit_condition_free(UnitCondition *c) {
3929 if (!c)
3930 return;
3931
3932 free(c->name);
3933 free(c->param);
3934 free(c);
3935 }
3936
3937 DEFINE_TRIVIAL_CLEANUP_FUNC(UnitCondition*, unit_condition_free);
3938
3939 typedef struct UnitStatusInfo {
3940 const char *id;
3941 const char *load_state;
3942 const char *active_state;
3943 const char *freezer_state;
3944 const char *sub_state;
3945 const char *unit_file_state;
3946 const char *unit_file_preset;
3947
3948 const char *description;
3949 const char *following;
3950
3951 char **documentation;
3952
3953 const char *fragment_path;
3954 const char *source_path;
3955 const char *control_group;
3956
3957 char **dropin_paths;
3958
3959 char **triggered_by;
3960 char **triggers;
3961
3962 const char *load_error;
3963 const char *result;
3964
3965 usec_t inactive_exit_timestamp;
3966 usec_t inactive_exit_timestamp_monotonic;
3967 usec_t active_enter_timestamp;
3968 usec_t active_exit_timestamp;
3969 usec_t inactive_enter_timestamp;
3970
3971 bool need_daemon_reload;
3972 bool transient;
3973
3974 /* Service */
3975 pid_t main_pid;
3976 pid_t control_pid;
3977 const char *status_text;
3978 const char *pid_file;
3979 bool running:1;
3980 int status_errno;
3981
3982 usec_t start_timestamp;
3983 usec_t exit_timestamp;
3984
3985 int exit_code, exit_status;
3986
3987 const char *log_namespace;
3988
3989 usec_t condition_timestamp;
3990 bool condition_result;
3991 LIST_HEAD(UnitCondition, conditions);
3992
3993 usec_t assert_timestamp;
3994 bool assert_result;
3995 bool failed_assert_trigger;
3996 bool failed_assert_negate;
3997 const char *failed_assert;
3998 const char *failed_assert_parameter;
3999 usec_t next_elapse_real;
4000 usec_t next_elapse_monotonic;
4001
4002 /* Socket */
4003 unsigned n_accepted;
4004 unsigned n_connections;
4005 unsigned n_refused;
4006 bool accept;
4007
4008 /* Pairs of type, path */
4009 char **listen;
4010
4011 /* Device */
4012 const char *sysfs_path;
4013
4014 /* Mount, Automount */
4015 const char *where;
4016
4017 /* Swap */
4018 const char *what;
4019
4020 /* CGroup */
4021 uint64_t memory_current;
4022 uint64_t memory_min;
4023 uint64_t memory_low;
4024 uint64_t memory_high;
4025 uint64_t memory_max;
4026 uint64_t memory_swap_max;
4027 uint64_t memory_limit;
4028 uint64_t cpu_usage_nsec;
4029 uint64_t tasks_current;
4030 uint64_t tasks_max;
4031 uint64_t ip_ingress_bytes;
4032 uint64_t ip_egress_bytes;
4033 uint64_t io_read_bytes;
4034 uint64_t io_write_bytes;
4035
4036 uint64_t default_memory_min;
4037 uint64_t default_memory_low;
4038
4039 LIST_HEAD(ExecStatusInfo, exec);
4040 } UnitStatusInfo;
4041
4042 static void unit_status_info_free(UnitStatusInfo *info) {
4043 ExecStatusInfo *p;
4044 UnitCondition *c;
4045
4046 strv_free(info->documentation);
4047 strv_free(info->dropin_paths);
4048 strv_free(info->triggered_by);
4049 strv_free(info->triggers);
4050 strv_free(info->listen);
4051
4052 while ((c = info->conditions)) {
4053 LIST_REMOVE(conditions, info->conditions, c);
4054 unit_condition_free(c);
4055 }
4056
4057 while ((p = info->exec)) {
4058 LIST_REMOVE(exec, info->exec, p);
4059 exec_status_info_free(p);
4060 }
4061 }
4062
4063 static void format_active_state(const char *active_state, const char **active_on, const char **active_off) {
4064 if (streq_ptr(active_state, "failed")) {
4065 *active_on = ansi_highlight_red();
4066 *active_off = ansi_normal();
4067 } else if (STRPTR_IN_SET(active_state, "active", "reloading")) {
4068 *active_on = ansi_highlight_green();
4069 *active_off = ansi_normal();
4070 } else
4071 *active_on = *active_off = "";
4072 }
4073
4074 static void print_status_info(
4075 sd_bus *bus,
4076 UnitStatusInfo *i,
4077 bool *ellipsized) {
4078
4079 char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], since2[FORMAT_TIMESTAMP_MAX];
4080 const char *s1, *s2, *active_on, *active_off, *on, *off, *ss, *fs;
4081 _cleanup_free_ char *formatted_path = NULL;
4082 ExecStatusInfo *p;
4083 usec_t timestamp;
4084 const char *path;
4085 char **t, **t2;
4086 int r;
4087
4088 assert(i);
4089
4090 /* This shows pretty information about a unit. See
4091 * print_property() for a low-level property printer */
4092
4093 format_active_state(i->active_state, &active_on, &active_off);
4094
4095 printf("%s%s%s %s", active_on, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE), active_off, strna(i->id));
4096
4097 if (i->description && !streq_ptr(i->id, i->description))
4098 printf(" - %s", i->description);
4099
4100 printf("\n");
4101
4102 if (i->following)
4103 printf(" Follow: unit currently follows state of %s\n", i->following);
4104
4105 if (STRPTR_IN_SET(i->load_state, "error", "not-found", "bad-setting")) {
4106 on = ansi_highlight_red();
4107 off = ansi_normal();
4108 } else
4109 on = off = "";
4110
4111 path = i->source_path ?: i->fragment_path;
4112 if (path && terminal_urlify_path(path, NULL, &formatted_path) >= 0)
4113 path = formatted_path;
4114
4115 if (!isempty(i->load_error))
4116 printf(" Loaded: %s%s%s (Reason: %s)\n",
4117 on, strna(i->load_state), off, i->load_error);
4118 else if (path && !isempty(i->unit_file_state)) {
4119 bool show_preset = !isempty(i->unit_file_preset) &&
4120 show_preset_for_state(unit_file_state_from_string(i->unit_file_state));
4121
4122 printf(" Loaded: %s%s%s (%s; %s%s%s)\n",
4123 on, strna(i->load_state), off,
4124 path,
4125 i->unit_file_state,
4126 show_preset ? "; vendor preset: " : "",
4127 show_preset ? i->unit_file_preset : "");
4128
4129 } else if (path)
4130 printf(" Loaded: %s%s%s (%s)\n",
4131 on, strna(i->load_state), off, path);
4132 else
4133 printf(" Loaded: %s%s%s\n",
4134 on, strna(i->load_state), off);
4135
4136 if (i->transient)
4137 printf(" Transient: yes\n");
4138
4139 if (!strv_isempty(i->dropin_paths)) {
4140 _cleanup_free_ char *dir = NULL;
4141 bool last = false;
4142 char ** dropin;
4143
4144 STRV_FOREACH(dropin, i->dropin_paths) {
4145 _cleanup_free_ char *dropin_formatted = NULL;
4146 const char *df;
4147
4148 if (!dir || last) {
4149 printf(dir ? " " :
4150 " Drop-In: ");
4151
4152 dir = mfree(dir);
4153
4154 dir = dirname_malloc(*dropin);
4155 if (!dir) {
4156 log_oom();
4157 return;
4158 }
4159
4160 printf("%s\n"
4161 " %s", dir,
4162 special_glyph(SPECIAL_GLYPH_TREE_RIGHT));
4163 }
4164
4165 last = ! (*(dropin + 1) && startswith(*(dropin + 1), dir));
4166
4167 if (terminal_urlify_path(*dropin, basename(*dropin), &dropin_formatted) >= 0)
4168 df = dropin_formatted;
4169 else
4170 df = *dropin;
4171
4172 printf("%s%s", df, last ? "\n" : ", ");
4173 }
4174 }
4175
4176 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
4177 if (ss)
4178 printf(" Active: %s%s (%s)%s",
4179 active_on, strna(i->active_state), ss, active_off);
4180 else
4181 printf(" Active: %s%s%s",
4182 active_on, strna(i->active_state), active_off);
4183
4184 fs = !isempty(i->freezer_state) && !streq(i->freezer_state, "running") ? i->freezer_state : NULL;
4185 if (fs)
4186 printf(" %s(%s)%s", ansi_highlight_yellow(), fs, ansi_normal());
4187
4188 if (!isempty(i->result) && !streq(i->result, "success"))
4189 printf(" (Result: %s)", i->result);
4190
4191 timestamp = STRPTR_IN_SET(i->active_state, "active", "reloading") ? i->active_enter_timestamp :
4192 STRPTR_IN_SET(i->active_state, "inactive", "failed") ? i->inactive_enter_timestamp :
4193 STRPTR_IN_SET(i->active_state, "activating") ? i->inactive_exit_timestamp :
4194 i->active_exit_timestamp;
4195
4196 s1 = format_timestamp_relative(since1, sizeof(since1), timestamp);
4197 s2 = format_timestamp(since2, sizeof(since2), timestamp);
4198
4199 if (s1)
4200 printf(" since %s; %s\n", s2, s1);
4201 else if (s2)
4202 printf(" since %s\n", s2);
4203 else
4204 printf("\n");
4205
4206 STRV_FOREACH(t, i->triggered_by) {
4207 UnitActiveState state = _UNIT_ACTIVE_STATE_INVALID;
4208
4209 (void) get_state_one_unit(bus, *t, &state);
4210 format_active_state(unit_active_state_to_string(state), &on, &off);
4211
4212 printf("%s %s%s%s %s\n",
4213 t == i->triggered_by ? "TriggeredBy:" : " ",
4214 on, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE), off,
4215 *t);
4216 }
4217
4218 if (endswith(i->id, ".timer")) {
4219 char tstamp1[FORMAT_TIMESTAMP_RELATIVE_MAX],
4220 tstamp2[FORMAT_TIMESTAMP_MAX];
4221 const char *next_rel_time, *next_time;
4222 dual_timestamp nw, next = {i->next_elapse_real,
4223 i->next_elapse_monotonic};
4224 usec_t next_elapse;
4225
4226 printf(" Trigger: ");
4227
4228 dual_timestamp_get(&nw);
4229 next_elapse = calc_next_elapse(&nw, &next);
4230 next_rel_time = format_timestamp_relative(tstamp1, sizeof tstamp1, next_elapse);
4231 next_time = format_timestamp(tstamp2, sizeof tstamp2, next_elapse);
4232
4233 if (next_time && next_rel_time)
4234 printf("%s; %s\n", next_time, next_rel_time);
4235 else
4236 printf("n/a\n");
4237 }
4238
4239 STRV_FOREACH(t, i->triggers) {
4240 UnitActiveState state = _UNIT_ACTIVE_STATE_INVALID;
4241
4242 (void) get_state_one_unit(bus, *t, &state);
4243 format_active_state(unit_active_state_to_string(state), &on, &off);
4244
4245 printf("%s %s%s%s %s\n",
4246 t == i->triggers ? " Triggers:" : " ",
4247 on, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE), off,
4248 *t);
4249 }
4250
4251 if (!i->condition_result && i->condition_timestamp > 0) {
4252 UnitCondition *c;
4253 int n = 0;
4254
4255 s1 = format_timestamp_relative(since1, sizeof(since1), i->condition_timestamp);
4256 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
4257
4258 printf(" Condition: start %scondition failed%s at %s%s%s\n",
4259 ansi_highlight_yellow(), ansi_normal(),
4260 s2, s1 ? "; " : "", strempty(s1));
4261
4262 LIST_FOREACH(conditions, c, i->conditions)
4263 if (c->tristate < 0)
4264 n++;
4265
4266 LIST_FOREACH(conditions, c, i->conditions)
4267 if (c->tristate < 0)
4268 printf(" %s %s=%s%s%s was not met\n",
4269 --n ? special_glyph(SPECIAL_GLYPH_TREE_BRANCH) : special_glyph(SPECIAL_GLYPH_TREE_RIGHT),
4270 c->name,
4271 c->trigger ? "|" : "",
4272 c->negate ? "!" : "",
4273 c->param);
4274 }
4275
4276 if (!i->assert_result && i->assert_timestamp > 0) {
4277 s1 = format_timestamp_relative(since1, sizeof(since1), i->assert_timestamp);
4278 s2 = format_timestamp(since2, sizeof(since2), i->assert_timestamp);
4279
4280 printf(" Assert: start %sassertion failed%s at %s%s%s\n",
4281 ansi_highlight_red(), ansi_normal(),
4282 s2, s1 ? "; " : "", strempty(s1));
4283 if (i->failed_assert_trigger)
4284 printf(" none of the trigger assertions were met\n");
4285 else if (i->failed_assert)
4286 printf(" %s=%s%s was not met\n",
4287 i->failed_assert,
4288 i->failed_assert_negate ? "!" : "",
4289 i->failed_assert_parameter);
4290 }
4291
4292 if (i->sysfs_path)
4293 printf(" Device: %s\n", i->sysfs_path);
4294 if (i->where)
4295 printf(" Where: %s\n", i->where);
4296 if (i->what)
4297 printf(" What: %s\n", i->what);
4298
4299 STRV_FOREACH(t, i->documentation) {
4300 _cleanup_free_ char *formatted = NULL;
4301 const char *q;
4302
4303 if (terminal_urlify(*t, NULL, &formatted) >= 0)
4304 q = formatted;
4305 else
4306 q = *t;
4307
4308 printf(" %*s %s\n", 9, t == i->documentation ? "Docs:" : "", q);
4309 }
4310
4311 STRV_FOREACH_PAIR(t, t2, i->listen)
4312 printf(" %*s %s (%s)\n", 9, t == i->listen ? "Listen:" : "", *t2, *t);
4313
4314 if (i->accept) {
4315 printf(" Accepted: %u; Connected: %u;", i->n_accepted, i->n_connections);
4316 if (i->n_refused)
4317 printf(" Refused: %u", i->n_refused);
4318 printf("\n");
4319 }
4320
4321 LIST_FOREACH(exec, p, i->exec) {
4322 _cleanup_free_ char *argv = NULL;
4323 bool good;
4324
4325 /* Only show exited processes here */
4326 if (p->code == 0)
4327 continue;
4328
4329 /* Don't print ExecXYZEx= properties here since it will appear as a
4330 * duplicate of the non-Ex= variant. */
4331 if (endswith(p->name, "Ex"))
4332 continue;
4333
4334 argv = strv_join(p->argv, " ");
4335 printf(" Process: "PID_FMT" %s=%s ", p->pid, p->name, strna(argv));
4336
4337 good = is_clean_exit(p->code, p->status, EXIT_CLEAN_DAEMON, NULL);
4338 if (!good) {
4339 on = ansi_highlight_red();
4340 off = ansi_normal();
4341 } else
4342 on = off = "";
4343
4344 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
4345
4346 if (p->code == CLD_EXITED) {
4347 const char *c;
4348
4349 printf("status=%i", p->status);
4350
4351 c = exit_status_to_string(p->status, EXIT_STATUS_LIBC | EXIT_STATUS_SYSTEMD);
4352 if (c)
4353 printf("/%s", c);
4354
4355 } else
4356 printf("signal=%s", signal_to_string(p->status));
4357
4358 printf(")%s\n", off);
4359
4360 if (i->main_pid == p->pid &&
4361 i->start_timestamp == p->start_timestamp &&
4362 i->exit_timestamp == p->start_timestamp)
4363 /* Let's not show this twice */
4364 i->main_pid = 0;
4365
4366 if (p->pid == i->control_pid)
4367 i->control_pid = 0;
4368 }
4369
4370 if (i->main_pid > 0 || i->control_pid > 0) {
4371 if (i->main_pid > 0) {
4372 printf(" Main PID: "PID_FMT, i->main_pid);
4373
4374 if (i->running) {
4375
4376 if (arg_transport == BUS_TRANSPORT_LOCAL) {
4377 _cleanup_free_ char *comm = NULL;
4378
4379 (void) get_process_comm(i->main_pid, &comm);
4380 if (comm)
4381 printf(" (%s)", comm);
4382 }
4383
4384 } else if (i->exit_code > 0) {
4385 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
4386
4387 if (i->exit_code == CLD_EXITED) {
4388 const char *c;
4389
4390 printf("status=%i", i->exit_status);
4391
4392 c = exit_status_to_string(i->exit_status,
4393 EXIT_STATUS_LIBC | EXIT_STATUS_SYSTEMD);
4394 if (c)
4395 printf("/%s", c);
4396
4397 } else
4398 printf("signal=%s", signal_to_string(i->exit_status));
4399 printf(")");
4400 }
4401 }
4402
4403 if (i->control_pid > 0) {
4404 _cleanup_free_ char *c = NULL;
4405
4406 if (i->main_pid > 0)
4407 fputs("; Control PID: ", stdout);
4408 else
4409 fputs("Cntrl PID: ", stdout); /* if first in column, abbreviated so it fits alignment */
4410
4411 printf(PID_FMT, i->control_pid);
4412
4413 if (arg_transport == BUS_TRANSPORT_LOCAL) {
4414 (void) get_process_comm(i->control_pid, &c);
4415 if (c)
4416 printf(" (%s)", c);
4417 }
4418 }
4419
4420 printf("\n");
4421 }
4422
4423 if (i->status_text)
4424 printf(" Status: \"%s\"\n", i->status_text);
4425 if (i->status_errno > 0)
4426 printf(" Error: %i (%s)\n", i->status_errno, strerror_safe(i->status_errno));
4427
4428 if (i->ip_ingress_bytes != (uint64_t) -1 && i->ip_egress_bytes != (uint64_t) -1) {
4429 char buf_in[FORMAT_BYTES_MAX], buf_out[FORMAT_BYTES_MAX];
4430
4431 printf(" IP: %s in, %s out\n",
4432 format_bytes(buf_in, sizeof(buf_in), i->ip_ingress_bytes),
4433 format_bytes(buf_out, sizeof(buf_out), i->ip_egress_bytes));
4434 }
4435
4436 if (i->io_read_bytes != UINT64_MAX && i->io_write_bytes != UINT64_MAX) {
4437 char buf_in[FORMAT_BYTES_MAX], buf_out[FORMAT_BYTES_MAX];
4438
4439 printf(" IO: %s read, %s written\n",
4440 format_bytes(buf_in, sizeof(buf_in), i->io_read_bytes),
4441 format_bytes(buf_out, sizeof(buf_out), i->io_write_bytes));
4442 }
4443
4444 if (i->tasks_current != (uint64_t) -1) {
4445 printf(" Tasks: %" PRIu64, i->tasks_current);
4446
4447 if (i->tasks_max != (uint64_t) -1)
4448 printf(" (limit: %" PRIu64 ")\n", i->tasks_max);
4449 else
4450 printf("\n");
4451 }
4452
4453 if (i->memory_current != (uint64_t) -1) {
4454 char buf[FORMAT_BYTES_MAX];
4455
4456 printf(" Memory: %s", format_bytes(buf, sizeof(buf), i->memory_current));
4457
4458 if (i->memory_min > 0 || i->memory_low > 0 ||
4459 i->memory_high != CGROUP_LIMIT_MAX || i->memory_max != CGROUP_LIMIT_MAX ||
4460 i->memory_swap_max != CGROUP_LIMIT_MAX ||
4461 i->memory_limit != CGROUP_LIMIT_MAX) {
4462 const char *prefix = "";
4463
4464 printf(" (");
4465 if (i->memory_min > 0) {
4466 printf("%smin: %s", prefix, format_bytes_cgroup_protection(buf, sizeof(buf), i->memory_min));
4467 prefix = " ";
4468 }
4469 if (i->memory_low > 0) {
4470 printf("%slow: %s", prefix, format_bytes_cgroup_protection(buf, sizeof(buf), i->memory_low));
4471 prefix = " ";
4472 }
4473 if (i->memory_high != CGROUP_LIMIT_MAX) {
4474 printf("%shigh: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_high));
4475 prefix = " ";
4476 }
4477 if (i->memory_max != CGROUP_LIMIT_MAX) {
4478 printf("%smax: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_max));
4479 prefix = " ";
4480 }
4481 if (i->memory_swap_max != CGROUP_LIMIT_MAX) {
4482 printf("%sswap max: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_swap_max));
4483 prefix = " ";
4484 }
4485 if (i->memory_limit != CGROUP_LIMIT_MAX) {
4486 printf("%slimit: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_limit));
4487 prefix = " ";
4488 }
4489 printf(")");
4490 }
4491 printf("\n");
4492 }
4493
4494 if (i->cpu_usage_nsec != (uint64_t) -1) {
4495 char buf[FORMAT_TIMESPAN_MAX];
4496 printf(" CPU: %s\n", format_timespan(buf, sizeof(buf), i->cpu_usage_nsec / NSEC_PER_USEC, USEC_PER_MSEC));
4497 }
4498
4499 if (i->control_group) {
4500 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4501 static const char prefix[] = " ";
4502 unsigned c;
4503
4504 printf(" CGroup: %s\n", i->control_group);
4505
4506 c = columns();
4507 if (c > sizeof(prefix) - 1)
4508 c -= sizeof(prefix) - 1;
4509 else
4510 c = 0;
4511
4512 r = unit_show_processes(bus, i->id, i->control_group, prefix, c, get_output_flags(), &error);
4513 if (r == -EBADR) {
4514 unsigned k = 0;
4515 pid_t extra[2];
4516
4517 /* Fallback for older systemd versions where the GetUnitProcesses() call is not yet available */
4518
4519 if (i->main_pid > 0)
4520 extra[k++] = i->main_pid;
4521
4522 if (i->control_pid > 0)
4523 extra[k++] = i->control_pid;
4524
4525 show_cgroup_and_extra(SYSTEMD_CGROUP_CONTROLLER, i->control_group, prefix, c, extra, k, get_output_flags());
4526 } else if (r < 0)
4527 log_warning_errno(r, "Failed to dump process list for '%s', ignoring: %s",
4528 i->id, bus_error_message(&error, r));
4529 }
4530
4531 if (i->id && arg_transport == BUS_TRANSPORT_LOCAL)
4532 show_journal_by_unit(
4533 stdout,
4534 i->id,
4535 i->log_namespace,
4536 arg_output,
4537 0,
4538 i->inactive_exit_timestamp_monotonic,
4539 arg_lines,
4540 getuid(),
4541 get_output_flags() | OUTPUT_BEGIN_NEWLINE,
4542 SD_JOURNAL_LOCAL_ONLY,
4543 arg_scope == UNIT_FILE_SYSTEM,
4544 ellipsized);
4545
4546 if (i->need_daemon_reload)
4547 warn_unit_file_changed(i->id);
4548 }
4549
4550 static void show_unit_help(UnitStatusInfo *i) {
4551 char **p;
4552
4553 assert(i);
4554
4555 if (!i->documentation) {
4556 log_info("Documentation for %s not known.", i->id);
4557 return;
4558 }
4559
4560 STRV_FOREACH(p, i->documentation)
4561 if (startswith(*p, "man:"))
4562 show_man_page(*p + 4, false);
4563 else
4564 log_info("Can't show: %s", *p);
4565 }
4566
4567 static int map_main_pid(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4568 UnitStatusInfo *i = userdata;
4569 uint32_t u;
4570 int r;
4571
4572 r = sd_bus_message_read(m, "u", &u);
4573 if (r < 0)
4574 return r;
4575
4576 i->main_pid = (pid_t) u;
4577 i->running = u > 0;
4578
4579 return 0;
4580 }
4581
4582 static int map_load_error(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4583 const char *message, **p = userdata;
4584 int r;
4585
4586 r = sd_bus_message_read(m, "(ss)", NULL, &message);
4587 if (r < 0)
4588 return r;
4589
4590 if (!isempty(message))
4591 *p = message;
4592
4593 return 0;
4594 }
4595
4596 static int map_listen(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4597 const char *type, *path;
4598 char ***p = userdata;
4599 int r;
4600
4601 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
4602 if (r < 0)
4603 return r;
4604
4605 while ((r = sd_bus_message_read(m, "(ss)", &type, &path)) > 0) {
4606
4607 r = strv_extend(p, type);
4608 if (r < 0)
4609 return r;
4610
4611 r = strv_extend(p, path);
4612 if (r < 0)
4613 return r;
4614 }
4615 if (r < 0)
4616 return r;
4617
4618 r = sd_bus_message_exit_container(m);
4619 if (r < 0)
4620 return r;
4621
4622 return 0;
4623 }
4624
4625 static int map_conditions(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4626 UnitStatusInfo *i = userdata;
4627 const char *cond, *param;
4628 int trigger, negate;
4629 int32_t state;
4630 int r;
4631
4632 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sbbsi)");
4633 if (r < 0)
4634 return r;
4635
4636 while ((r = sd_bus_message_read(m, "(sbbsi)", &cond, &trigger, &negate, &param, &state)) > 0) {
4637 _cleanup_(unit_condition_freep) UnitCondition *c = NULL;
4638
4639 c = new(UnitCondition, 1);
4640 if (!c)
4641 return -ENOMEM;
4642
4643 *c = (UnitCondition) {
4644 .name = strdup(cond),
4645 .param = strdup(param),
4646 .trigger = trigger,
4647 .negate = negate,
4648 .tristate = state,
4649 };
4650
4651 if (!c->name || !c->param)
4652 return -ENOMEM;
4653
4654 LIST_PREPEND(conditions, i->conditions, TAKE_PTR(c));
4655 }
4656 if (r < 0)
4657 return r;
4658
4659 r = sd_bus_message_exit_container(m);
4660 if (r < 0)
4661 return r;
4662
4663 return 0;
4664 }
4665
4666 static int map_asserts(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4667 UnitStatusInfo *i = userdata;
4668 const char *cond, *param;
4669 int trigger, negate;
4670 int32_t state;
4671 int r;
4672
4673 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sbbsi)");
4674 if (r < 0)
4675 return r;
4676
4677 while ((r = sd_bus_message_read(m, "(sbbsi)", &cond, &trigger, &negate, &param, &state)) > 0) {
4678 if (state < 0 && (!trigger || !i->failed_assert)) {
4679 i->failed_assert = cond;
4680 i->failed_assert_trigger = trigger;
4681 i->failed_assert_negate = negate;
4682 i->failed_assert_parameter = param;
4683 }
4684 }
4685 if (r < 0)
4686 return r;
4687
4688 r = sd_bus_message_exit_container(m);
4689 if (r < 0)
4690 return r;
4691
4692 return 0;
4693 }
4694
4695 static int map_exec(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4696 _cleanup_free_ ExecStatusInfo *info = NULL;
4697 ExecStatusInfo *last;
4698 UnitStatusInfo *i = userdata;
4699 bool is_ex_prop = endswith(member, "Ex");
4700 int r;
4701
4702 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, is_ex_prop ? "(sasasttttuii)" : "(sasbttttuii)");
4703 if (r < 0)
4704 return r;
4705
4706 info = new0(ExecStatusInfo, 1);
4707 if (!info)
4708 return -ENOMEM;
4709
4710 LIST_FIND_TAIL(exec, i->exec, last);
4711
4712 while ((r = exec_status_info_deserialize(m, info, is_ex_prop)) > 0) {
4713
4714 info->name = strdup(member);
4715 if (!info->name)
4716 return -ENOMEM;
4717
4718 LIST_INSERT_AFTER(exec, i->exec, last, info);
4719 last = info;
4720
4721 info = new0(ExecStatusInfo, 1);
4722 if (!info)
4723 return -ENOMEM;
4724 }
4725 if (r < 0)
4726 return r;
4727
4728 r = sd_bus_message_exit_container(m);
4729 if (r < 0)
4730 return r;
4731
4732 return 0;
4733 }
4734
4735 static int print_property(const char *name, const char *expected_value, sd_bus_message *m, bool value, bool all) {
4736 char bus_type;
4737 const char *contents;
4738 int r;
4739
4740 assert(name);
4741 assert(m);
4742
4743 /* This is a low-level property printer, see
4744 * print_status_info() for the nicer output */
4745
4746 r = sd_bus_message_peek_type(m, &bus_type, &contents);
4747 if (r < 0)
4748 return r;
4749
4750 switch (bus_type) {
4751
4752 case SD_BUS_TYPE_INT32:
4753 if (endswith(name, "ActionExitStatus")) {
4754 int32_t i;
4755
4756 r = sd_bus_message_read_basic(m, bus_type, &i);
4757 if (r < 0)
4758 return r;
4759
4760 if (i >= 0 && i <= 255)
4761 bus_print_property_valuef(name, expected_value, value, "%"PRIi32, i);
4762 else if (all)
4763 bus_print_property_value(name, expected_value, value, "[not set]");
4764
4765 return 1;
4766 } else if (streq(name, "NUMAPolicy")) {
4767 int32_t i;
4768
4769 r = sd_bus_message_read_basic(m, bus_type, &i);
4770 if (r < 0)
4771 return r;
4772
4773 bus_print_property_valuef(name, expected_value, value, "%s", strna(mpol_to_string(i)));
4774
4775 return 1;
4776 }
4777 break;
4778
4779 case SD_BUS_TYPE_STRUCT:
4780
4781 if (contents[0] == SD_BUS_TYPE_UINT32 && streq(name, "Job")) {
4782 uint32_t u;
4783
4784 r = sd_bus_message_read(m, "(uo)", &u, NULL);
4785 if (r < 0)
4786 return bus_log_parse_error(r);
4787
4788 if (u > 0)
4789 bus_print_property_valuef(name, expected_value, value, "%"PRIu32, u);
4790 else if (all)
4791 bus_print_property_value(name, expected_value, value, "");
4792
4793 return 1;
4794
4795 } else if (contents[0] == SD_BUS_TYPE_STRING && streq(name, "Unit")) {
4796 const char *s;
4797
4798 r = sd_bus_message_read(m, "(so)", &s, NULL);
4799 if (r < 0)
4800 return bus_log_parse_error(r);
4801
4802 if (all || !isempty(s))
4803 bus_print_property_value(name, expected_value, value, s);
4804
4805 return 1;
4806
4807 } else if (contents[0] == SD_BUS_TYPE_STRING && streq(name, "LoadError")) {
4808 const char *a = NULL, *b = NULL;
4809
4810 r = sd_bus_message_read(m, "(ss)", &a, &b);
4811 if (r < 0)
4812 return bus_log_parse_error(r);
4813
4814 if (!isempty(a) || !isempty(b))
4815 bus_print_property_valuef(name, expected_value, value, "%s \"%s\"", strempty(a), strempty(b));
4816 else if (all)
4817 bus_print_property_value(name, expected_value, value, "");
4818
4819 return 1;
4820
4821 } else if (STR_IN_SET(name, "SystemCallFilter", "RestrictAddressFamilies")) {
4822 _cleanup_strv_free_ char **l = NULL;
4823 int whitelist;
4824
4825 r = sd_bus_message_enter_container(m, 'r', "bas");
4826 if (r < 0)
4827 return bus_log_parse_error(r);
4828
4829 r = sd_bus_message_read(m, "b", &whitelist);
4830 if (r < 0)
4831 return bus_log_parse_error(r);
4832
4833 r = sd_bus_message_read_strv(m, &l);
4834 if (r < 0)
4835 return bus_log_parse_error(r);
4836
4837 r = sd_bus_message_exit_container(m);
4838 if (r < 0)
4839 return bus_log_parse_error(r);
4840
4841 if (all || whitelist || !strv_isempty(l)) {
4842 bool first = true;
4843 char **i;
4844
4845 if (!value) {
4846 fputs(name, stdout);
4847 fputc('=', stdout);
4848 }
4849
4850 if (!whitelist)
4851 fputc('~', stdout);
4852
4853 STRV_FOREACH(i, l) {
4854 if (first)
4855 first = false;
4856 else
4857 fputc(' ', stdout);
4858
4859 fputs(*i, stdout);
4860 }
4861 fputc('\n', stdout);
4862 }
4863
4864 return 1;
4865
4866 } else if (STR_IN_SET(name, "SELinuxContext", "AppArmorProfile", "SmackProcessLabel")) {
4867 int ignore;
4868 const char *s;
4869
4870 r = sd_bus_message_read(m, "(bs)", &ignore, &s);
4871 if (r < 0)
4872 return bus_log_parse_error(r);
4873
4874 if (!isempty(s))
4875 bus_print_property_valuef(name, expected_value, value, "%s%s", ignore ? "-" : "", s);
4876 else if (all)
4877 bus_print_property_value(name, expected_value, value, "");
4878
4879 return 1;
4880
4881 } else if (endswith(name, "ExitStatus") && streq(contents, "aiai")) {
4882 const int32_t *status, *signal;
4883 size_t n_status, n_signal, i;
4884
4885 r = sd_bus_message_enter_container(m, 'r', "aiai");
4886 if (r < 0)
4887 return bus_log_parse_error(r);
4888
4889 r = sd_bus_message_read_array(m, 'i', (const void **) &status, &n_status);
4890 if (r < 0)
4891 return bus_log_parse_error(r);
4892
4893 r = sd_bus_message_read_array(m, 'i', (const void **) &signal, &n_signal);
4894 if (r < 0)
4895 return bus_log_parse_error(r);
4896
4897 r = sd_bus_message_exit_container(m);
4898 if (r < 0)
4899 return bus_log_parse_error(r);
4900
4901 n_status /= sizeof(int32_t);
4902 n_signal /= sizeof(int32_t);
4903
4904 if (all || n_status > 0 || n_signal > 0) {
4905 bool first = true;
4906
4907 if (!value) {
4908 fputs(name, stdout);
4909 fputc('=', stdout);
4910 }
4911
4912 for (i = 0; i < n_status; i++) {
4913 if (first)
4914 first = false;
4915 else
4916 fputc(' ', stdout);
4917
4918 printf("%"PRIi32, status[i]);
4919 }
4920
4921 for (i = 0; i < n_signal; i++) {
4922 const char *str;
4923
4924 str = signal_to_string((int) signal[i]);
4925
4926 if (first)
4927 first = false;
4928 else
4929 fputc(' ', stdout);
4930
4931 if (str)
4932 fputs(str, stdout);
4933 else
4934 printf("%"PRIi32, status[i]);
4935 }
4936
4937 fputc('\n', stdout);
4938 }
4939 return 1;
4940 }
4941
4942 break;
4943
4944 case SD_BUS_TYPE_ARRAY:
4945
4946 if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "EnvironmentFiles")) {
4947 const char *path;
4948 int ignore;
4949
4950 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sb)");
4951 if (r < 0)
4952 return bus_log_parse_error(r);
4953
4954 while ((r = sd_bus_message_read(m, "(sb)", &path, &ignore)) > 0)
4955 bus_print_property_valuef(name, expected_value, value, "%s (ignore_errors=%s)", path, yes_no(ignore));
4956
4957 if (r < 0)
4958 return bus_log_parse_error(r);
4959
4960 r = sd_bus_message_exit_container(m);
4961 if (r < 0)
4962 return bus_log_parse_error(r);
4963
4964 return 1;
4965
4966 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "Paths")) {
4967 const char *type, *path;
4968
4969 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
4970 if (r < 0)
4971 return bus_log_parse_error(r);
4972
4973 while ((r = sd_bus_message_read(m, "(ss)", &type, &path)) > 0)
4974 bus_print_property_valuef(name, expected_value, value, "%s (%s)", path, type);
4975 if (r < 0)
4976 return bus_log_parse_error(r);
4977
4978 r = sd_bus_message_exit_container(m);
4979 if (r < 0)
4980 return bus_log_parse_error(r);
4981
4982 return 1;
4983
4984 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "Listen")) {
4985 const char *type, *path;
4986
4987 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
4988 if (r < 0)
4989 return bus_log_parse_error(r);
4990
4991 while ((r = sd_bus_message_read(m, "(ss)", &type, &path)) > 0)
4992 bus_print_property_valuef(name, expected_value, value, "%s (%s)", path, type);
4993 if (r < 0)
4994 return bus_log_parse_error(r);
4995
4996 r = sd_bus_message_exit_container(m);
4997 if (r < 0)
4998 return bus_log_parse_error(r);
4999
5000 return 1;
5001
5002 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "TimersMonotonic")) {
5003 const char *base;
5004 uint64_t v, next_elapse;
5005
5006 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(stt)");
5007 if (r < 0)
5008 return bus_log_parse_error(r);
5009
5010 while ((r = sd_bus_message_read(m, "(stt)", &base, &v, &next_elapse)) > 0) {
5011 char timespan1[FORMAT_TIMESPAN_MAX] = "n/a", timespan2[FORMAT_TIMESPAN_MAX] = "n/a";
5012
5013 (void) format_timespan(timespan1, sizeof timespan1, v, 0);
5014 (void) format_timespan(timespan2, sizeof timespan2, next_elapse, 0);
5015
5016 bus_print_property_valuef(name, expected_value, value,
5017 "{ %s=%s ; next_elapse=%s }", base, timespan1, timespan2);
5018 }
5019 if (r < 0)
5020 return bus_log_parse_error(r);
5021
5022 r = sd_bus_message_exit_container(m);
5023 if (r < 0)
5024 return bus_log_parse_error(r);
5025
5026 return 1;
5027
5028 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "TimersCalendar")) {
5029 const char *base, *spec;
5030 uint64_t next_elapse;
5031
5032 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sst)");
5033 if (r < 0)
5034 return bus_log_parse_error(r);
5035
5036 while ((r = sd_bus_message_read(m, "(sst)", &base, &spec, &next_elapse)) > 0) {
5037 char timestamp[FORMAT_TIMESTAMP_MAX] = "n/a";
5038
5039 (void) format_timestamp(timestamp, sizeof(timestamp), next_elapse);
5040 bus_print_property_valuef(name, expected_value, value,
5041 "{ %s=%s ; next_elapse=%s }", base, spec, timestamp);
5042 }
5043 if (r < 0)
5044 return bus_log_parse_error(r);
5045
5046 r = sd_bus_message_exit_container(m);
5047 if (r < 0)
5048 return bus_log_parse_error(r);
5049
5050 return 1;
5051
5052 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && startswith(name, "Exec")) {
5053 ExecStatusInfo info = {};
5054 bool is_ex_prop = endswith(name, "Ex");
5055
5056 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, is_ex_prop ? "(sasasttttuii)" : "(sasbttttuii)");
5057 if (r < 0)
5058 return bus_log_parse_error(r);
5059
5060 while ((r = exec_status_info_deserialize(m, &info, is_ex_prop)) > 0) {
5061 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
5062 _cleanup_strv_free_ char **optv = NULL;
5063 _cleanup_free_ char *tt, *o = NULL;
5064
5065 tt = strv_join(info.argv, " ");
5066
5067 if (is_ex_prop) {
5068 r = exec_command_flags_to_strv(info.flags, &optv);
5069 if (r < 0)
5070 return log_error_errno(r, "Failed to convert ExecCommandFlags to strv: %m");
5071
5072 o = strv_join(optv, " ");
5073
5074 bus_print_property_valuef(name, expected_value, value,
5075 "{ path=%s ; argv[]=%s ; flags=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT" ; code=%s ; status=%i%s%s }",
5076 strna(info.path),
5077 strna(tt),
5078 strna(o),
5079 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
5080 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
5081 info.pid,
5082 sigchld_code_to_string(info.code),
5083 info.status,
5084 info.code == CLD_EXITED ? "" : "/",
5085 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
5086 } else
5087 bus_print_property_valuef(name, expected_value, value,
5088 "{ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT" ; code=%s ; status=%i%s%s }",
5089 strna(info.path),
5090 strna(tt),
5091 yes_no(info.ignore),
5092 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
5093 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
5094 info.pid,
5095 sigchld_code_to_string(info.code),
5096 info.status,
5097 info.code == CLD_EXITED ? "" : "/",
5098 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
5099
5100 free(info.path);
5101 strv_free(info.argv);
5102 zero(info);
5103 }
5104
5105 r = sd_bus_message_exit_container(m);
5106 if (r < 0)
5107 return bus_log_parse_error(r);
5108
5109 return 1;
5110
5111 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "DeviceAllow")) {
5112 const char *path, *rwm;
5113
5114 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
5115 if (r < 0)
5116 return bus_log_parse_error(r);
5117
5118 while ((r = sd_bus_message_read(m, "(ss)", &path, &rwm)) > 0)
5119 bus_print_property_valuef(name, expected_value, value, "%s %s", strna(path), strna(rwm));
5120 if (r < 0)
5121 return bus_log_parse_error(r);
5122
5123 r = sd_bus_message_exit_container(m);
5124 if (r < 0)
5125 return bus_log_parse_error(r);
5126
5127 return 1;
5128
5129 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN &&
5130 STR_IN_SET(name, "IODeviceWeight", "BlockIODeviceWeight")) {
5131 const char *path;
5132 uint64_t weight;
5133
5134 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(st)");
5135 if (r < 0)
5136 return bus_log_parse_error(r);
5137
5138 while ((r = sd_bus_message_read(m, "(st)", &path, &weight)) > 0)
5139 bus_print_property_valuef(name, expected_value, value, "%s %"PRIu64, strna(path), weight);
5140 if (r < 0)
5141 return bus_log_parse_error(r);
5142
5143 r = sd_bus_message_exit_container(m);
5144 if (r < 0)
5145 return bus_log_parse_error(r);
5146
5147 return 1;
5148
5149 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN &&
5150 (cgroup_io_limit_type_from_string(name) >= 0 ||
5151 STR_IN_SET(name, "BlockIOReadBandwidth", "BlockIOWriteBandwidth"))) {
5152 const char *path;
5153 uint64_t bandwidth;
5154
5155 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(st)");
5156 if (r < 0)
5157 return bus_log_parse_error(r);
5158
5159 while ((r = sd_bus_message_read(m, "(st)", &path, &bandwidth)) > 0)
5160 bus_print_property_valuef(name, expected_value, value, "%s %"PRIu64, strna(path), bandwidth);
5161 if (r < 0)
5162 return bus_log_parse_error(r);
5163
5164 r = sd_bus_message_exit_container(m);
5165 if (r < 0)
5166 return bus_log_parse_error(r);
5167
5168 return 1;
5169
5170 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN &&
5171 streq(name, "IODeviceLatencyTargetUSec")) {
5172 char ts[FORMAT_TIMESPAN_MAX];
5173 const char *path;
5174 uint64_t target;
5175
5176 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(st)");
5177 if (r < 0)
5178 return bus_log_parse_error(r);
5179
5180 while ((r = sd_bus_message_read(m, "(st)", &path, &target)) > 0)
5181 bus_print_property_valuef(name, expected_value, value, "%s %s", strna(path),
5182 format_timespan(ts, sizeof(ts), target, 1));
5183 if (r < 0)
5184 return bus_log_parse_error(r);
5185
5186 r = sd_bus_message_exit_container(m);
5187 if (r < 0)
5188 return bus_log_parse_error(r);
5189
5190 return 1;
5191
5192 } else if (contents[0] == SD_BUS_TYPE_BYTE && streq(name, "StandardInputData")) {
5193 _cleanup_free_ char *h = NULL;
5194 const void *p;
5195 size_t sz;
5196 ssize_t n;
5197
5198 r = sd_bus_message_read_array(m, 'y', &p, &sz);
5199 if (r < 0)
5200 return bus_log_parse_error(r);
5201
5202 n = base64mem(p, sz, &h);
5203 if (n < 0)
5204 return log_oom();
5205
5206 bus_print_property_value(name, expected_value, value, h);
5207
5208 return 1;
5209
5210 } else if (STR_IN_SET(name, "IPAddressAllow", "IPAddressDeny")) {
5211 _cleanup_free_ char *addresses = NULL;
5212
5213 r = sd_bus_message_enter_container(m, 'a', "(iayu)");
5214 if (r < 0)
5215 return bus_log_parse_error(r);
5216
5217 for (;;) {
5218 _cleanup_free_ char *str = NULL;
5219 uint32_t prefixlen;
5220 int32_t family;
5221 const void *ap;
5222 size_t an;
5223
5224 r = sd_bus_message_enter_container(m, 'r', "iayu");
5225 if (r < 0)
5226 return bus_log_parse_error(r);
5227 if (r == 0)
5228 break;
5229
5230 r = sd_bus_message_read(m, "i", &family);
5231 if (r < 0)
5232 return bus_log_parse_error(r);
5233
5234 r = sd_bus_message_read_array(m, 'y', &ap, &an);
5235 if (r < 0)
5236 return bus_log_parse_error(r);
5237
5238 r = sd_bus_message_read(m, "u", &prefixlen);
5239 if (r < 0)
5240 return bus_log_parse_error(r);
5241
5242 r = sd_bus_message_exit_container(m);
5243 if (r < 0)
5244 return bus_log_parse_error(r);
5245
5246 if (!IN_SET(family, AF_INET, AF_INET6))
5247 continue;
5248
5249 if (an != FAMILY_ADDRESS_SIZE(family))
5250 continue;
5251
5252 if (prefixlen > FAMILY_ADDRESS_SIZE(family) * 8)
5253 continue;
5254
5255 if (in_addr_prefix_to_string(family, (union in_addr_union *) ap, prefixlen, &str) < 0)
5256 continue;
5257
5258 if (!strextend_with_separator(&addresses, " ", str, NULL))
5259 return log_oom();
5260 }
5261
5262 r = sd_bus_message_exit_container(m);
5263 if (r < 0)
5264 return bus_log_parse_error(r);
5265
5266 if (all || !isempty(addresses))
5267 bus_print_property_value(name, expected_value, value, strempty(addresses));
5268
5269 return 1;
5270
5271 } else if (STR_IN_SET(name, "BindPaths", "BindReadOnlyPaths")) {
5272 _cleanup_free_ char *paths = NULL;
5273 const char *source, *dest;
5274 int ignore_enoent;
5275 uint64_t rbind;
5276
5277 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ssbt)");
5278 if (r < 0)
5279 return bus_log_parse_error(r);
5280
5281 while ((r = sd_bus_message_read(m, "(ssbt)", &source, &dest, &ignore_enoent, &rbind)) > 0) {
5282 _cleanup_free_ char *str = NULL;
5283
5284 if (isempty(source))
5285 continue;
5286
5287 if (asprintf(&str, "%s%s%s%s%s",
5288 ignore_enoent ? "-" : "",
5289 source,
5290 isempty(dest) ? "" : ":",
5291 strempty(dest),
5292 rbind == MS_REC ? ":rbind" : "") < 0)
5293 return log_oom();
5294
5295 if (!strextend_with_separator(&paths, " ", str, NULL))
5296 return log_oom();
5297 }
5298 if (r < 0)
5299 return bus_log_parse_error(r);
5300
5301 r = sd_bus_message_exit_container(m);
5302 if (r < 0)
5303 return bus_log_parse_error(r);
5304
5305 if (all || !isempty(paths))
5306 bus_print_property_value(name, expected_value, value, strempty(paths));
5307
5308 return 1;
5309
5310 } else if (streq(name, "TemporaryFileSystem")) {
5311 _cleanup_free_ char *paths = NULL;
5312 const char *target, *option;
5313
5314 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
5315 if (r < 0)
5316 return bus_log_parse_error(r);
5317
5318 while ((r = sd_bus_message_read(m, "(ss)", &target, &option)) > 0) {
5319 _cleanup_free_ char *str = NULL;
5320
5321 if (isempty(target))
5322 continue;
5323
5324 if (asprintf(&str, "%s%s%s", target, isempty(option) ? "" : ":", strempty(option)) < 0)
5325 return log_oom();
5326
5327 if (!strextend_with_separator(&paths, " ", str, NULL))
5328 return log_oom();
5329 }
5330 if (r < 0)
5331 return bus_log_parse_error(r);
5332
5333 r = sd_bus_message_exit_container(m);
5334 if (r < 0)
5335 return bus_log_parse_error(r);
5336
5337 if (all || !isempty(paths))
5338 bus_print_property_value(name, expected_value, value, strempty(paths));
5339
5340 return 1;
5341
5342 } else if (streq(name, "LogExtraFields")) {
5343 _cleanup_free_ char *fields = NULL;
5344 const void *p;
5345 size_t sz;
5346
5347 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "ay");
5348 if (r < 0)
5349 return bus_log_parse_error(r);
5350
5351 while ((r = sd_bus_message_read_array(m, 'y', &p, &sz)) > 0) {
5352 _cleanup_free_ char *str = NULL;
5353 const char *eq;
5354
5355 if (memchr(p, 0, sz))
5356 continue;
5357
5358 eq = memchr(p, '=', sz);
5359 if (!eq)
5360 continue;
5361
5362 if (!journal_field_valid(p, eq - (const char*) p, false))
5363 continue;
5364
5365 str = malloc(sz + 1);
5366 if (!str)
5367 return log_oom();
5368
5369 memcpy(str, p, sz);
5370 str[sz] = '\0';
5371
5372 if (!utf8_is_valid(str))
5373 continue;
5374
5375 if (!strextend_with_separator(&fields, " ", str, NULL))
5376 return log_oom();
5377 }
5378 if (r < 0)
5379 return bus_log_parse_error(r);
5380
5381 r = sd_bus_message_exit_container(m);
5382 if (r < 0)
5383 return bus_log_parse_error(r);
5384
5385 if (all || !isempty(fields))
5386 bus_print_property_value(name, expected_value, value, strempty(fields));
5387
5388 return 1;
5389 } else if (contents[0] == SD_BUS_TYPE_BYTE && STR_IN_SET(name, "CPUAffinity", "NUMAMask", "AllowedCPUs", "AllowedMemoryNodes", "EffectiveCPUs", "EffectiveMemoryNodes")) {
5390 _cleanup_free_ char *affinity = NULL;
5391 _cleanup_(cpu_set_reset) CPUSet set = {};
5392 const void *a;
5393 size_t n;
5394
5395 r = sd_bus_message_read_array(m, 'y', &a, &n);
5396 if (r < 0)
5397 return bus_log_parse_error(r);
5398
5399 r = cpu_set_from_dbus(a, n, &set);
5400 if (r < 0)
5401 return log_error_errno(r, "Failed to deserialize %s: %m", name);
5402
5403 affinity = cpu_set_to_range_string(&set);
5404 if (!affinity)
5405 return log_oom();
5406
5407 bus_print_property_value(name, expected_value, value, affinity);
5408
5409 return 1;
5410 }
5411
5412 break;
5413 }
5414
5415 return 0;
5416 }
5417
5418 typedef enum SystemctlShowMode{
5419 SYSTEMCTL_SHOW_PROPERTIES,
5420 SYSTEMCTL_SHOW_STATUS,
5421 SYSTEMCTL_SHOW_HELP,
5422 _SYSTEMCTL_SHOW_MODE_MAX,
5423 _SYSTEMCTL_SHOW_MODE_INVALID = -1,
5424 } SystemctlShowMode;
5425
5426 static const char* const systemctl_show_mode_table[_SYSTEMCTL_SHOW_MODE_MAX] = {
5427 [SYSTEMCTL_SHOW_PROPERTIES] = "show",
5428 [SYSTEMCTL_SHOW_STATUS] = "status",
5429 [SYSTEMCTL_SHOW_HELP] = "help",
5430 };
5431
5432 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(systemctl_show_mode, SystemctlShowMode);
5433
5434 static int show_one(
5435 sd_bus *bus,
5436 const char *path,
5437 const char *unit,
5438 SystemctlShowMode show_mode,
5439 bool *new_line,
5440 bool *ellipsized) {
5441
5442 static const struct bus_properties_map property_map[] = {
5443 { "LoadState", "s", NULL, offsetof(UnitStatusInfo, load_state) },
5444 { "ActiveState", "s", NULL, offsetof(UnitStatusInfo, active_state) },
5445 { "FreezerState", "s", NULL, offsetof(UnitStatusInfo, freezer_state) },
5446 { "Documentation", "as", NULL, offsetof(UnitStatusInfo, documentation) },
5447 {}
5448 }, status_map[] = {
5449 { "Id", "s", NULL, offsetof(UnitStatusInfo, id) },
5450 { "LoadState", "s", NULL, offsetof(UnitStatusInfo, load_state) },
5451 { "ActiveState", "s", NULL, offsetof(UnitStatusInfo, active_state) },
5452 { "FreezerState", "s", NULL, offsetof(UnitStatusInfo, freezer_state) },
5453 { "SubState", "s", NULL, offsetof(UnitStatusInfo, sub_state) },
5454 { "UnitFileState", "s", NULL, offsetof(UnitStatusInfo, unit_file_state) },
5455 { "UnitFilePreset", "s", NULL, offsetof(UnitStatusInfo, unit_file_preset) },
5456 { "Description", "s", NULL, offsetof(UnitStatusInfo, description) },
5457 { "Following", "s", NULL, offsetof(UnitStatusInfo, following) },
5458 { "Documentation", "as", NULL, offsetof(UnitStatusInfo, documentation) },
5459 { "FragmentPath", "s", NULL, offsetof(UnitStatusInfo, fragment_path) },
5460 { "SourcePath", "s", NULL, offsetof(UnitStatusInfo, source_path) },
5461 { "ControlGroup", "s", NULL, offsetof(UnitStatusInfo, control_group) },
5462 { "DropInPaths", "as", NULL, offsetof(UnitStatusInfo, dropin_paths) },
5463 { "LoadError", "(ss)", map_load_error, offsetof(UnitStatusInfo, load_error) },
5464 { "Result", "s", NULL, offsetof(UnitStatusInfo, result) },
5465 { "TriggeredBy", "as", NULL, offsetof(UnitStatusInfo, triggered_by) },
5466 { "Triggers", "as", NULL, offsetof(UnitStatusInfo, triggers) },
5467 { "InactiveExitTimestamp", "t", NULL, offsetof(UnitStatusInfo, inactive_exit_timestamp) },
5468 { "InactiveExitTimestampMonotonic", "t", NULL, offsetof(UnitStatusInfo, inactive_exit_timestamp_monotonic) },
5469 { "ActiveEnterTimestamp", "t", NULL, offsetof(UnitStatusInfo, active_enter_timestamp) },
5470 { "ActiveExitTimestamp", "t", NULL, offsetof(UnitStatusInfo, active_exit_timestamp) },
5471 { "InactiveEnterTimestamp", "t", NULL, offsetof(UnitStatusInfo, inactive_enter_timestamp) },
5472 { "NeedDaemonReload", "b", NULL, offsetof(UnitStatusInfo, need_daemon_reload) },
5473 { "Transient", "b", NULL, offsetof(UnitStatusInfo, transient) },
5474 { "ExecMainPID", "u", NULL, offsetof(UnitStatusInfo, main_pid) },
5475 { "MainPID", "u", map_main_pid, 0 },
5476 { "ControlPID", "u", NULL, offsetof(UnitStatusInfo, control_pid) },
5477 { "StatusText", "s", NULL, offsetof(UnitStatusInfo, status_text) },
5478 { "PIDFile", "s", NULL, offsetof(UnitStatusInfo, pid_file) },
5479 { "StatusErrno", "i", NULL, offsetof(UnitStatusInfo, status_errno) },
5480 { "ExecMainStartTimestamp", "t", NULL, offsetof(UnitStatusInfo, start_timestamp) },
5481 { "ExecMainExitTimestamp", "t", NULL, offsetof(UnitStatusInfo, exit_timestamp) },
5482 { "ExecMainCode", "i", NULL, offsetof(UnitStatusInfo, exit_code) },
5483 { "ExecMainStatus", "i", NULL, offsetof(UnitStatusInfo, exit_status) },
5484 { "LogNamespace", "s", NULL, offsetof(UnitStatusInfo, log_namespace) },
5485 { "ConditionTimestamp", "t", NULL, offsetof(UnitStatusInfo, condition_timestamp) },
5486 { "ConditionResult", "b", NULL, offsetof(UnitStatusInfo, condition_result) },
5487 { "Conditions", "a(sbbsi)", map_conditions, 0 },
5488 { "AssertTimestamp", "t", NULL, offsetof(UnitStatusInfo, assert_timestamp) },
5489 { "AssertResult", "b", NULL, offsetof(UnitStatusInfo, assert_result) },
5490 { "Asserts", "a(sbbsi)", map_asserts, 0 },
5491 { "NextElapseUSecRealtime", "t", NULL, offsetof(UnitStatusInfo, next_elapse_real) },
5492 { "NextElapseUSecMonotonic", "t", NULL, offsetof(UnitStatusInfo, next_elapse_monotonic) },
5493 { "NAccepted", "u", NULL, offsetof(UnitStatusInfo, n_accepted) },
5494 { "NConnections", "u", NULL, offsetof(UnitStatusInfo, n_connections) },
5495 { "NRefused", "u", NULL, offsetof(UnitStatusInfo, n_refused) },
5496 { "Accept", "b", NULL, offsetof(UnitStatusInfo, accept) },
5497 { "Listen", "a(ss)", map_listen, offsetof(UnitStatusInfo, listen) },
5498 { "SysFSPath", "s", NULL, offsetof(UnitStatusInfo, sysfs_path) },
5499 { "Where", "s", NULL, offsetof(UnitStatusInfo, where) },
5500 { "What", "s", NULL, offsetof(UnitStatusInfo, what) },
5501 { "MemoryCurrent", "t", NULL, offsetof(UnitStatusInfo, memory_current) },
5502 { "DefaultMemoryMin", "t", NULL, offsetof(UnitStatusInfo, default_memory_min) },
5503 { "DefaultMemoryLow", "t", NULL, offsetof(UnitStatusInfo, default_memory_low) },
5504 { "MemoryMin", "t", NULL, offsetof(UnitStatusInfo, memory_min) },
5505 { "MemoryLow", "t", NULL, offsetof(UnitStatusInfo, memory_low) },
5506 { "MemoryHigh", "t", NULL, offsetof(UnitStatusInfo, memory_high) },
5507 { "MemoryMax", "t", NULL, offsetof(UnitStatusInfo, memory_max) },
5508 { "MemorySwapMax", "t", NULL, offsetof(UnitStatusInfo, memory_swap_max) },
5509 { "MemoryLimit", "t", NULL, offsetof(UnitStatusInfo, memory_limit) },
5510 { "CPUUsageNSec", "t", NULL, offsetof(UnitStatusInfo, cpu_usage_nsec) },
5511 { "TasksCurrent", "t", NULL, offsetof(UnitStatusInfo, tasks_current) },
5512 { "TasksMax", "t", NULL, offsetof(UnitStatusInfo, tasks_max) },
5513 { "IPIngressBytes", "t", NULL, offsetof(UnitStatusInfo, ip_ingress_bytes) },
5514 { "IPEgressBytes", "t", NULL, offsetof(UnitStatusInfo, ip_egress_bytes) },
5515 { "IOReadBytes", "t", NULL, offsetof(UnitStatusInfo, io_read_bytes) },
5516 { "IOWriteBytes", "t", NULL, offsetof(UnitStatusInfo, io_write_bytes) },
5517 { "ExecCondition", "a(sasbttttuii)", map_exec, 0 },
5518 { "ExecConditionEx", "a(sasasttttuii)", map_exec, 0 },
5519 { "ExecStartPre", "a(sasbttttuii)", map_exec, 0 },
5520 { "ExecStartPreEx", "a(sasasttttuii)", map_exec, 0 },
5521 { "ExecStart", "a(sasbttttuii)", map_exec, 0 },
5522 { "ExecStartEx", "a(sasasttttuii)", map_exec, 0 },
5523 { "ExecStartPost", "a(sasbttttuii)", map_exec, 0 },
5524 { "ExecStartPostEx", "a(sasasttttuii)", map_exec, 0 },
5525 { "ExecReload", "a(sasbttttuii)", map_exec, 0 },
5526 { "ExecReloadEx", "a(sasasttttuii)", map_exec, 0 },
5527 { "ExecStopPre", "a(sasbttttuii)", map_exec, 0 },
5528 { "ExecStop", "a(sasbttttuii)", map_exec, 0 },
5529 { "ExecStopEx", "a(sasasttttuii)", map_exec, 0 },
5530 { "ExecStopPost", "a(sasbttttuii)", map_exec, 0 },
5531 { "ExecStopPostEx", "a(sasasttttuii)", map_exec, 0 },
5532 {}
5533 };
5534
5535 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
5536 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5537 _cleanup_set_free_ Set *found_properties = NULL;
5538 _cleanup_(unit_status_info_free) UnitStatusInfo info = {
5539 .memory_current = (uint64_t) -1,
5540 .memory_high = CGROUP_LIMIT_MAX,
5541 .memory_max = CGROUP_LIMIT_MAX,
5542 .memory_swap_max = CGROUP_LIMIT_MAX,
5543 .memory_limit = (uint64_t) -1,
5544 .cpu_usage_nsec = (uint64_t) -1,
5545 .tasks_current = (uint64_t) -1,
5546 .tasks_max = (uint64_t) -1,
5547 .ip_ingress_bytes = (uint64_t) -1,
5548 .ip_egress_bytes = (uint64_t) -1,
5549 .io_read_bytes = UINT64_MAX,
5550 .io_write_bytes = UINT64_MAX,
5551 };
5552 char **pp;
5553 int r;
5554
5555 assert(path);
5556 assert(new_line);
5557
5558 log_debug("Showing one %s", path);
5559
5560 r = bus_map_all_properties(
5561 bus,
5562 "org.freedesktop.systemd1",
5563 path,
5564 show_mode == SYSTEMCTL_SHOW_STATUS ? status_map : property_map,
5565 BUS_MAP_BOOLEAN_AS_BOOL,
5566 &error,
5567 &reply,
5568 &info);
5569 if (r < 0)
5570 return log_error_errno(r, "Failed to get properties: %s", bus_error_message(&error, r));
5571
5572 if (unit && streq_ptr(info.load_state, "not-found") && streq_ptr(info.active_state, "inactive")) {
5573 log_full(show_mode == SYSTEMCTL_SHOW_STATUS ? LOG_ERR : LOG_DEBUG,
5574 "Unit %s could not be found.", unit);
5575
5576 if (show_mode == SYSTEMCTL_SHOW_STATUS)
5577 return EXIT_PROGRAM_OR_SERVICES_STATUS_UNKNOWN;
5578 else if (show_mode == SYSTEMCTL_SHOW_HELP)
5579 return -ENOENT;
5580 }
5581
5582 if (*new_line)
5583 printf("\n");
5584
5585 *new_line = true;
5586
5587 if (show_mode == SYSTEMCTL_SHOW_STATUS) {
5588 print_status_info(bus, &info, ellipsized);
5589
5590 if (info.active_state && !STR_IN_SET(info.active_state, "active", "reloading"))
5591 return EXIT_PROGRAM_NOT_RUNNING;
5592
5593 return EXIT_PROGRAM_RUNNING_OR_SERVICE_OK;
5594
5595 } else if (show_mode == SYSTEMCTL_SHOW_HELP) {
5596 show_unit_help(&info);
5597 return 0;
5598 }
5599
5600 r = sd_bus_message_rewind(reply, true);
5601 if (r < 0)
5602 return log_error_errno(r, "Failed to rewind: %s", bus_error_message(&error, r));
5603
5604 r = bus_message_print_all_properties(reply, print_property, arg_properties, arg_value, arg_all, &found_properties);
5605 if (r < 0)
5606 return bus_log_parse_error(r);
5607
5608 STRV_FOREACH(pp, arg_properties)
5609 if (!set_contains(found_properties, *pp))
5610 log_debug("Property %s does not exist.", *pp);
5611
5612 return 0;
5613 }
5614
5615 static int get_unit_dbus_path_by_pid(
5616 sd_bus *bus,
5617 uint32_t pid,
5618 char **unit) {
5619
5620 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5621 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
5622 char *u;
5623 int r;
5624
5625 r = bus_call_method(bus, bus_systemd_mgr, "GetUnitByPID", &error, &reply, "u", pid);
5626 if (r < 0)
5627 return log_error_errno(r, "Failed to get unit for PID %"PRIu32": %s", pid, bus_error_message(&error, r));
5628
5629 r = sd_bus_message_read(reply, "o", &u);
5630 if (r < 0)
5631 return bus_log_parse_error(r);
5632
5633 u = strdup(u);
5634 if (!u)
5635 return log_oom();
5636
5637 *unit = u;
5638 return 0;
5639 }
5640
5641 static int show_all(
5642 sd_bus *bus,
5643 bool *new_line,
5644 bool *ellipsized) {
5645
5646 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
5647 _cleanup_free_ UnitInfo *unit_infos = NULL;
5648 const UnitInfo *u;
5649 unsigned c;
5650 int r, ret = 0;
5651
5652 r = get_unit_list(bus, NULL, NULL, &unit_infos, 0, &reply);
5653 if (r < 0)
5654 return r;
5655
5656 (void) pager_open(arg_pager_flags);
5657
5658 c = (unsigned) r;
5659
5660 typesafe_qsort(unit_infos, c, compare_unit_info);
5661
5662 for (u = unit_infos; u < unit_infos + c; u++) {
5663 _cleanup_free_ char *p = NULL;
5664
5665 p = unit_dbus_path_from_name(u->id);
5666 if (!p)
5667 return log_oom();
5668
5669 r = show_one(bus, p, u->id, SYSTEMCTL_SHOW_STATUS, new_line, ellipsized);
5670 if (r < 0)
5671 return r;
5672 else if (r > 0 && ret == 0)
5673 ret = r;
5674 }
5675
5676 return ret;
5677 }
5678
5679 static int show_system_status(sd_bus *bus) {
5680 char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], since2[FORMAT_TIMESTAMP_MAX];
5681 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5682 _cleanup_(machine_info_clear) struct machine_info mi = {};
5683 _cleanup_free_ char *hn = NULL;
5684 const char *on, *off;
5685 int r;
5686
5687 hn = gethostname_malloc();
5688 if (!hn)
5689 return log_oom();
5690
5691 r = bus_map_all_properties(
5692 bus,
5693 "org.freedesktop.systemd1",
5694 "/org/freedesktop/systemd1",
5695 machine_info_property_map,
5696 BUS_MAP_STRDUP,
5697 &error,
5698 NULL,
5699 &mi);
5700 if (r < 0)
5701 return log_error_errno(r, "Failed to read server status: %s", bus_error_message(&error, r));
5702
5703 if (streq_ptr(mi.state, "degraded")) {
5704 on = ansi_highlight_red();
5705 off = ansi_normal();
5706 } else if (streq_ptr(mi.state, "running")) {
5707 on = ansi_highlight_green();
5708 off = ansi_normal();
5709 } else {
5710 on = ansi_highlight_yellow();
5711 off = ansi_normal();
5712 }
5713
5714 printf("%s%s%s %s\n", on, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE), off, arg_host ? arg_host : hn);
5715
5716 printf(" State: %s%s%s\n",
5717 on, strna(mi.state), off);
5718
5719 printf(" Jobs: %" PRIu32 " queued\n", mi.n_jobs);
5720 printf(" Failed: %" PRIu32 " units\n", mi.n_failed_units);
5721
5722 printf(" Since: %s; %s\n",
5723 format_timestamp(since2, sizeof(since2), mi.timestamp),
5724 format_timestamp_relative(since1, sizeof(since1), mi.timestamp));
5725
5726 printf(" CGroup: %s\n", mi.control_group ?: "/");
5727 if (IN_SET(arg_transport,
5728 BUS_TRANSPORT_LOCAL,
5729 BUS_TRANSPORT_MACHINE)) {
5730 static const char prefix[] = " ";
5731 unsigned c;
5732
5733 c = columns();
5734 if (c > sizeof(prefix) - 1)
5735 c -= sizeof(prefix) - 1;
5736 else
5737 c = 0;
5738
5739 show_cgroup(SYSTEMD_CGROUP_CONTROLLER, strempty(mi.control_group), prefix, c, get_output_flags());
5740 }
5741
5742 return 0;
5743 }
5744
5745 static int show(int argc, char *argv[], void *userdata) {
5746 bool new_line = false, ellipsized = false;
5747 SystemctlShowMode show_mode;
5748 int r, ret = 0;
5749 sd_bus *bus;
5750
5751 assert(argv);
5752
5753 show_mode = systemctl_show_mode_from_string(argv[0]);
5754 if (show_mode < 0)
5755 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
5756 "Invalid argument.");
5757
5758 if (show_mode == SYSTEMCTL_SHOW_HELP && argc <= 1)
5759 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
5760 "'help' command expects one or more unit names.\n"
5761 "(Alternatively, help for systemctl itself may be shown with --help)");
5762
5763 r = acquire_bus(BUS_MANAGER, &bus);
5764 if (r < 0)
5765 return r;
5766
5767 (void) pager_open(arg_pager_flags);
5768
5769 /* If no argument is specified inspect the manager itself */
5770 if (show_mode == SYSTEMCTL_SHOW_PROPERTIES && argc <= 1)
5771 return show_one(bus, "/org/freedesktop/systemd1", NULL, show_mode, &new_line, &ellipsized);
5772
5773 if (show_mode == SYSTEMCTL_SHOW_STATUS && argc <= 1) {
5774
5775 show_system_status(bus);
5776 new_line = true;
5777
5778 if (arg_all)
5779 ret = show_all(bus, &new_line, &ellipsized);
5780 } else {
5781 _cleanup_free_ char **patterns = NULL;
5782 char **name;
5783
5784 STRV_FOREACH(name, strv_skip(argv, 1)) {
5785 _cleanup_free_ char *path = NULL, *unit = NULL;
5786 uint32_t id;
5787
5788 if (safe_atou32(*name, &id) < 0) {
5789 if (strv_push(&patterns, *name) < 0)
5790 return log_oom();
5791
5792 continue;
5793 } else if (show_mode == SYSTEMCTL_SHOW_PROPERTIES) {
5794 /* Interpret as job id */
5795 if (asprintf(&path, "/org/freedesktop/systemd1/job/%u", id) < 0)
5796 return log_oom();
5797
5798 } else {
5799 /* Interpret as PID */
5800 r = get_unit_dbus_path_by_pid(bus, id, &path);
5801 if (r < 0) {
5802 ret = r;
5803 continue;
5804 }
5805
5806 r = unit_name_from_dbus_path(path, &unit);
5807 if (r < 0)
5808 return log_oom();
5809 }
5810
5811 r = show_one(bus, path, unit, show_mode, &new_line, &ellipsized);
5812 if (r < 0)
5813 return r;
5814 else if (r > 0 && ret == 0)
5815 ret = r;
5816 }
5817
5818 if (!strv_isempty(patterns)) {
5819 _cleanup_strv_free_ char **names = NULL;
5820
5821 r = expand_names(bus, patterns, NULL, &names, NULL);
5822 if (r < 0)
5823 return log_error_errno(r, "Failed to expand names: %m");
5824
5825 r = maybe_extend_with_unit_dependencies(bus, &names);
5826 if (r < 0)
5827 return r;
5828
5829 STRV_FOREACH(name, names) {
5830 _cleanup_free_ char *path;
5831
5832 path = unit_dbus_path_from_name(*name);
5833 if (!path)
5834 return log_oom();
5835
5836 r = show_one(bus, path, *name, show_mode, &new_line, &ellipsized);
5837 if (r < 0)
5838 return r;
5839 if (r > 0 && ret == 0)
5840 ret = r;
5841 }
5842 }
5843 }
5844
5845 if (ellipsized && !arg_quiet)
5846 printf("Hint: Some lines were ellipsized, use -l to show in full.\n");
5847
5848 return ret;
5849 }
5850
5851 static int cat(int argc, char *argv[], void *userdata) {
5852 _cleanup_(lookup_paths_free) LookupPaths lp = {};
5853 _cleanup_strv_free_ char **names = NULL;
5854 char **name;
5855 sd_bus *bus;
5856 bool first = true;
5857 int r, rc = 0;
5858
5859 /* Include all units by default — i.e. continue as if the --all
5860 * option was used */
5861 if (strv_isempty(arg_states))
5862 arg_all = true;
5863
5864 if (arg_transport != BUS_TRANSPORT_LOCAL)
5865 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot remotely cat units.");
5866
5867 r = lookup_paths_init(&lp, arg_scope, 0, arg_root);
5868 if (r < 0)
5869 return log_error_errno(r, "Failed to determine unit paths: %m");
5870
5871 r = acquire_bus(BUS_MANAGER, &bus);
5872 if (r < 0)
5873 return r;
5874
5875 r = expand_names(bus, strv_skip(argv, 1), NULL, &names, NULL);
5876 if (r < 0)
5877 return log_error_errno(r, "Failed to expand names: %m");
5878
5879 r = maybe_extend_with_unit_dependencies(bus, &names);
5880 if (r < 0)
5881 return r;
5882
5883 (void) pager_open(arg_pager_flags);
5884
5885 STRV_FOREACH(name, names) {
5886 _cleanup_free_ char *fragment_path = NULL;
5887 _cleanup_strv_free_ char **dropin_paths = NULL;
5888
5889 r = unit_find_paths(bus, *name, &lp, false, &fragment_path, &dropin_paths);
5890 if (r == -ERFKILL) {
5891 printf("%s# Unit %s is masked%s.\n",
5892 ansi_highlight_magenta(),
5893 *name,
5894 ansi_normal());
5895 continue;
5896 }
5897 if (r == -EKEYREJECTED) {
5898 printf("%s# Unit %s could not be loaded.%s\n",
5899 ansi_highlight_magenta(),
5900 *name,
5901 ansi_normal());
5902 continue;
5903 }
5904 if (r < 0)
5905 return r;
5906 if (r == 0) {
5907 /* Skip units which have no on-disk counterpart, but
5908 * propagate the error to the user */
5909 rc = -ENOENT;
5910 continue;
5911 }
5912
5913 if (first)
5914 first = false;
5915 else
5916 puts("");
5917
5918 if (need_daemon_reload(bus, *name) > 0) /* ignore errors (<0), this is informational output */
5919 fprintf(stderr,
5920 "%s# Warning: %s changed on disk, the version systemd has loaded is outdated.\n"
5921 "%s# This output shows the current version of the unit's original fragment and drop-in files.\n"
5922 "%s# If fragments or drop-ins were added or removed, they are not properly reflected in this output.\n"
5923 "%s# Run 'systemctl%s daemon-reload' to reload units.%s\n",
5924 ansi_highlight_red(),
5925 *name,
5926 ansi_highlight_red(),
5927 ansi_highlight_red(),
5928 ansi_highlight_red(),
5929 arg_scope == UNIT_FILE_SYSTEM ? "" : " --user",
5930 ansi_normal());
5931
5932 r = cat_files(fragment_path, dropin_paths, 0);
5933 if (r < 0)
5934 return r;
5935 }
5936
5937 return rc;
5938 }
5939
5940 static int set_property(int argc, char *argv[], void *userdata) {
5941 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
5942 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5943 _cleanup_free_ char *n = NULL;
5944 UnitType t;
5945 sd_bus *bus;
5946 int r;
5947
5948 r = acquire_bus(BUS_MANAGER, &bus);
5949 if (r < 0)
5950 return r;
5951
5952 polkit_agent_open_maybe();
5953
5954 r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "SetUnitProperties");
5955 if (r < 0)
5956 return bus_log_create_error(r);
5957
5958 r = unit_name_mangle(argv[1], arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, &n);
5959 if (r < 0)
5960 return log_error_errno(r, "Failed to mangle unit name: %m");
5961
5962 t = unit_name_to_type(n);
5963 if (t < 0)
5964 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid unit type: %s", n);
5965
5966 r = sd_bus_message_append(m, "sb", n, arg_runtime);
5967 if (r < 0)
5968 return bus_log_create_error(r);
5969
5970 r = sd_bus_message_open_container(m, SD_BUS_TYPE_ARRAY, "(sv)");
5971 if (r < 0)
5972 return bus_log_create_error(r);
5973
5974 r = bus_append_unit_property_assignment_many(m, t, strv_skip(argv, 2));
5975 if (r < 0)
5976 return r;
5977
5978 r = sd_bus_message_close_container(m);
5979 if (r < 0)
5980 return bus_log_create_error(r);
5981
5982 r = sd_bus_call(bus, m, 0, &error, NULL);
5983 if (r < 0)
5984 return log_error_errno(r, "Failed to set unit properties on %s: %s", n, bus_error_message(&error, r));
5985
5986 return 0;
5987 }
5988
5989 static int daemon_reload(int argc, char *argv[], void *userdata) {
5990 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5991 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
5992 const char *method;
5993 sd_bus *bus;
5994 int r;
5995
5996 r = acquire_bus(BUS_MANAGER, &bus);
5997 if (r < 0)
5998 return r;
5999
6000 polkit_agent_open_maybe();
6001
6002 switch (arg_action) {
6003
6004 case ACTION_RELOAD:
6005 method = "Reload";
6006 break;
6007
6008 case ACTION_REEXEC:
6009 method = "Reexecute";
6010 break;
6011
6012 case ACTION_SYSTEMCTL:
6013 method = streq(argv[0], "daemon-reexec") ? "Reexecute" :
6014 /* "daemon-reload" */ "Reload";
6015 break;
6016
6017 default:
6018 assert_not_reached("Unexpected action");
6019 }
6020
6021 r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, method);
6022 if (r < 0)
6023 return bus_log_create_error(r);
6024
6025 /* Note we use an extra-long timeout here. This is because a reload or reexec means generators are rerun which
6026 * are timed out after DEFAULT_TIMEOUT_USEC. Let's use twice that time here, so that the generators can have
6027 * their timeout, and for everything else there's the same time budget in place. */
6028
6029 r = sd_bus_call(bus, m, DEFAULT_TIMEOUT_USEC * 2, &error, NULL);
6030
6031 /* On reexecution, we expect a disconnect, not a reply */
6032 if (IN_SET(r, -ETIMEDOUT, -ECONNRESET) && streq(method, "Reexecute"))
6033 r = 0;
6034
6035 if (r < 0 && arg_action == ACTION_SYSTEMCTL)
6036 return log_error_errno(r, "Failed to reload daemon: %s", bus_error_message(&error, r));
6037
6038 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
6039 * old ways of doing things, hence don't log any error in that case here. */
6040
6041 return r < 0 ? r : 0;
6042 }
6043
6044 static int trivial_method(int argc, char *argv[], void *userdata) {
6045 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6046 const char *method;
6047 sd_bus *bus;
6048 int r;
6049
6050 if (arg_dry_run)
6051 return 0;
6052
6053 r = acquire_bus(BUS_MANAGER, &bus);
6054 if (r < 0)
6055 return r;
6056
6057 polkit_agent_open_maybe();
6058
6059 method =
6060 streq(argv[0], "clear-jobs") ||
6061 streq(argv[0], "cancel") ? "ClearJobs" :
6062 streq(argv[0], "reset-failed") ? "ResetFailed" :
6063 streq(argv[0], "halt") ? "Halt" :
6064 streq(argv[0], "reboot") ? "Reboot" :
6065 streq(argv[0], "kexec") ? "KExec" :
6066 streq(argv[0], "exit") ? "Exit" :
6067 /* poweroff */ "PowerOff";
6068
6069 r = bus_call_method(bus, bus_systemd_mgr, method, &error, NULL, NULL);
6070 if (r < 0 && arg_action == ACTION_SYSTEMCTL)
6071 return log_error_errno(r, "Failed to execute operation: %s", bus_error_message(&error, r));
6072
6073 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
6074 * old ways of doing things, hence don't log any error in that case here. */
6075
6076 return r < 0 ? r : 0;
6077 }
6078
6079 static int reset_failed(int argc, char *argv[], void *userdata) {
6080 _cleanup_strv_free_ char **names = NULL;
6081 sd_bus *bus;
6082 char **name;
6083 int r, q;
6084
6085 if (argc <= 1)
6086 return trivial_method(argc, argv, userdata);
6087
6088 r = acquire_bus(BUS_MANAGER, &bus);
6089 if (r < 0)
6090 return r;
6091
6092 polkit_agent_open_maybe();
6093
6094 r = expand_names(bus, strv_skip(argv, 1), NULL, &names, NULL);
6095 if (r < 0)
6096 return log_error_errno(r, "Failed to expand names: %m");
6097
6098 STRV_FOREACH(name, names) {
6099 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6100
6101 q = bus_call_method(bus, bus_systemd_mgr, "ResetFailedUnit", &error, NULL, "s", *name);
6102 if (q < 0) {
6103 log_error_errno(q, "Failed to reset failed state of unit %s: %s", *name, bus_error_message(&error, q));
6104 if (r == 0)
6105 r = q;
6106 }
6107 }
6108
6109 return r;
6110 }
6111
6112 static int print_variable(const char *s) {
6113 const char *sep;
6114 _cleanup_free_ char *esc = NULL;
6115
6116 sep = strchr(s, '=');
6117 if (!sep)
6118 return log_error_errno(SYNTHETIC_ERRNO(EUCLEAN),
6119 "Invalid environment block");
6120
6121 esc = shell_maybe_quote(sep + 1, ESCAPE_POSIX);
6122 if (!esc)
6123 return log_oom();
6124
6125 printf("%.*s=%s\n", (int)(sep-s), s, esc);
6126 return 0;
6127 }
6128
6129 static int show_environment(int argc, char *argv[], void *userdata) {
6130 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6131 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
6132 const char *text;
6133 sd_bus *bus;
6134 int r;
6135
6136 r = acquire_bus(BUS_MANAGER, &bus);
6137 if (r < 0)
6138 return r;
6139
6140 (void) pager_open(arg_pager_flags);
6141
6142 r = bus_get_property(bus, bus_systemd_mgr, "Environment", &error, &reply, "as");
6143 if (r < 0)
6144 return log_error_errno(r, "Failed to get environment: %s", bus_error_message(&error, r));
6145
6146 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "s");
6147 if (r < 0)
6148 return bus_log_parse_error(r);
6149
6150 while ((r = sd_bus_message_read_basic(reply, SD_BUS_TYPE_STRING, &text)) > 0) {
6151 r = print_variable(text);
6152 if (r < 0)
6153 return r;
6154 }
6155 if (r < 0)
6156 return bus_log_parse_error(r);
6157
6158 r = sd_bus_message_exit_container(reply);
6159 if (r < 0)
6160 return bus_log_parse_error(r);
6161
6162 return 0;
6163 }
6164
6165 static int switch_root(int argc, char *argv[], void *userdata) {
6166 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6167 _cleanup_free_ char *cmdline_init = NULL;
6168 const char *root, *init;
6169 sd_bus *bus;
6170 int r;
6171
6172 if (arg_transport != BUS_TRANSPORT_LOCAL)
6173 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot switch root remotely.");
6174
6175 if (argc < 2 || argc > 3)
6176 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Wrong number of arguments.");
6177
6178 root = argv[1];
6179
6180 if (argc >= 3)
6181 init = argv[2];
6182 else {
6183 r = proc_cmdline_get_key("init", 0, &cmdline_init);
6184 if (r < 0)
6185 log_debug_errno(r, "Failed to parse /proc/cmdline: %m");
6186
6187 init = cmdline_init;
6188 }
6189
6190 init = empty_to_null(init);
6191 if (init) {
6192 const char *root_systemd_path = NULL, *root_init_path = NULL;
6193
6194 root_systemd_path = prefix_roota(root, "/" SYSTEMD_BINARY_PATH);
6195 root_init_path = prefix_roota(root, init);
6196
6197 /* If the passed init is actually the same as the
6198 * systemd binary, then let's suppress it. */
6199 if (files_same(root_init_path, root_systemd_path, 0) > 0)
6200 init = NULL;
6201 }
6202
6203 /* Instruct PID1 to exclude us from its killing spree applied during the transition. Otherwise we
6204 * would exit with a failure status even though the switch to the new root has succeed. */
6205 assert(saved_argv);
6206 assert(saved_argv[0]);
6207 saved_argv[0][0] = '@';
6208
6209 r = acquire_bus(BUS_MANAGER, &bus);
6210 if (r < 0)
6211 return r;
6212
6213 /* If we are slow to exit after the root switch, the new systemd instance
6214 * will send us a signal to terminate. Just ignore it and exit normally.
6215 * This way the unit does not end up as failed.
6216 */
6217 r = ignore_signals(SIGTERM, -1);
6218 if (r < 0)
6219 log_warning_errno(r, "Failed to change disposition of SIGTERM to ignore: %m");
6220
6221 log_debug("Switching root - root: %s; init: %s", root, strna(init));
6222
6223 r = bus_call_method(bus, bus_systemd_mgr, "SwitchRoot", &error, NULL, "ss", root, init);
6224 if (r < 0) {
6225 (void) default_signals(SIGTERM, -1);
6226
6227 return log_error_errno(r, "Failed to switch root: %s", bus_error_message(&error, r));
6228 }
6229
6230 return 0;
6231 }
6232
6233 static int log_level(int argc, char *argv[], void *userdata) {
6234 sd_bus *bus;
6235 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6236 int r;
6237
6238 r = acquire_bus(BUS_MANAGER, &bus);
6239 if (r < 0)
6240 return r;
6241
6242 if (argc == 1) {
6243 _cleanup_free_ char *level = NULL;
6244
6245 r = bus_get_property_string(bus, bus_systemd_mgr, "LogLevel", &error, &level);
6246 if (r < 0)
6247 return log_error_errno(r, "Failed to get log level: %s", bus_error_message(&error, r));
6248
6249 puts(level);
6250
6251 } else {
6252 assert(argc == 2);
6253
6254 r = bus_set_property(bus, bus_systemd_mgr, "LogLevel", &error, "s", argv[1]);
6255 if (r < 0)
6256 return log_error_errno(r, "Failed to set log level: %s", bus_error_message(&error, r));
6257 }
6258
6259 return 0;
6260 }
6261
6262 static int log_target(int argc, char *argv[], void *userdata) {
6263 sd_bus *bus;
6264 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6265 int r;
6266
6267 r = acquire_bus(BUS_MANAGER, &bus);
6268 if (r < 0)
6269 return r;
6270
6271 if (argc == 1) {
6272 _cleanup_free_ char *target = NULL;
6273
6274 r = bus_get_property_string(bus, bus_systemd_mgr, "LogTarget", &error, &target);
6275 if (r < 0)
6276 return log_error_errno(r, "Failed to get log target: %s", bus_error_message(&error, r));
6277
6278 puts(target);
6279
6280 } else {
6281 assert(argc == 2);
6282
6283 r = bus_set_property(bus, bus_systemd_mgr, "LogTarget", &error, "s", argv[1]);
6284 if (r < 0)
6285 return log_error_errno(r, "Failed to set log target: %s", bus_error_message(&error, r));
6286 }
6287
6288 return 0;
6289 }
6290
6291 static int service_watchdogs(int argc, char *argv[], void *userdata) {
6292 sd_bus *bus;
6293 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6294 int b, r;
6295
6296 assert(argv);
6297
6298 r = acquire_bus(BUS_MANAGER, &bus);
6299 if (r < 0)
6300 return r;
6301
6302 if (argc == 1) {
6303 /* get ServiceWatchdogs */
6304 r = bus_get_property_trivial(bus, bus_systemd_mgr, "ServiceWatchdogs", &error, 'b', &b);
6305 if (r < 0)
6306 return log_error_errno(r, "Failed to get service-watchdog state: %s", bus_error_message(&error, r));
6307
6308 printf("%s\n", yes_no(!!b));
6309
6310 } else {
6311 /* set ServiceWatchdogs */
6312 assert(argc == 2);
6313
6314 b = parse_boolean(argv[1]);
6315 if (b < 0)
6316 return log_error_errno(b, "Failed to parse service-watchdogs argument: %m");
6317
6318 r = bus_set_property(bus, bus_systemd_mgr, "ServiceWatchdogs", &error, "b", b);
6319 if (r < 0)
6320 return log_error_errno(r, "Failed to set service-watchdog state: %s", bus_error_message(&error, r));
6321 }
6322
6323 return 0;
6324 }
6325
6326 static int set_environment(int argc, char *argv[], void *userdata) {
6327 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6328 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
6329 const char *method;
6330 sd_bus *bus;
6331 int r;
6332
6333 assert(argc > 1);
6334 assert(argv);
6335
6336 r = acquire_bus(BUS_MANAGER, &bus);
6337 if (r < 0)
6338 return r;
6339
6340 polkit_agent_open_maybe();
6341
6342 method = streq(argv[0], "set-environment")
6343 ? "SetEnvironment"
6344 : "UnsetEnvironment";
6345
6346 r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, method);
6347 if (r < 0)
6348 return bus_log_create_error(r);
6349
6350 r = sd_bus_message_append_strv(m, strv_skip(argv, 1));
6351 if (r < 0)
6352 return bus_log_create_error(r);
6353
6354 r = sd_bus_call(bus, m, 0, &error, NULL);
6355 if (r < 0)
6356 return log_error_errno(r, "Failed to set environment: %s", bus_error_message(&error, r));
6357
6358 return 0;
6359 }
6360
6361 static int import_environment(int argc, char *argv[], void *userdata) {
6362 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6363 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
6364 sd_bus *bus;
6365 int r;
6366
6367 r = acquire_bus(BUS_MANAGER, &bus);
6368 if (r < 0)
6369 return r;
6370
6371 polkit_agent_open_maybe();
6372
6373 r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "SetEnvironment");
6374 if (r < 0)
6375 return bus_log_create_error(r);
6376
6377 if (argc < 2)
6378 r = sd_bus_message_append_strv(m, environ);
6379 else {
6380 char **a, **b;
6381
6382 r = sd_bus_message_open_container(m, 'a', "s");
6383 if (r < 0)
6384 return bus_log_create_error(r);
6385
6386 STRV_FOREACH(a, strv_skip(argv, 1)) {
6387
6388 if (!env_name_is_valid(*a))
6389 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Not a valid environment variable name: %s", *a);
6390
6391 STRV_FOREACH(b, environ) {
6392 const char *eq;
6393
6394 eq = startswith(*b, *a);
6395 if (eq && *eq == '=') {
6396
6397 r = sd_bus_message_append(m, "s", *b);
6398 if (r < 0)
6399 return bus_log_create_error(r);
6400
6401 break;
6402 }
6403 }
6404 }
6405
6406 r = sd_bus_message_close_container(m);
6407 }
6408 if (r < 0)
6409 return bus_log_create_error(r);
6410
6411 r = sd_bus_call(bus, m, 0, &error, NULL);
6412 if (r < 0)
6413 return log_error_errno(r, "Failed to import environment: %s", bus_error_message(&error, r));
6414
6415 return 0;
6416 }
6417
6418 static int enable_sysv_units(const char *verb, char **args) {
6419 int r = 0;
6420
6421 #if HAVE_SYSV_COMPAT
6422 _cleanup_(lookup_paths_free) LookupPaths paths = {};
6423 unsigned f = 0;
6424
6425 /* Processes all SysV units, and reshuffles the array so that afterwards only the native units remain */
6426
6427 if (arg_scope != UNIT_FILE_SYSTEM)
6428 return 0;
6429
6430 if (getenv_bool("SYSTEMCTL_SKIP_SYSV") > 0)
6431 return 0;
6432
6433 if (!STR_IN_SET(verb,
6434 "enable",
6435 "disable",
6436 "is-enabled"))
6437 return 0;
6438
6439 r = lookup_paths_init(&paths, arg_scope, LOOKUP_PATHS_EXCLUDE_GENERATED, arg_root);
6440 if (r < 0)
6441 return r;
6442
6443 r = 0;
6444 while (args[f]) {
6445
6446 const char *argv[] = {
6447 ROOTLIBEXECDIR "/systemd-sysv-install",
6448 NULL, /* --root= */
6449 NULL, /* verb */
6450 NULL, /* service */
6451 NULL,
6452 };
6453
6454 _cleanup_free_ char *p = NULL, *q = NULL, *l = NULL, *v = NULL;
6455 bool found_native = false, found_sysv;
6456 const char *name;
6457 unsigned c = 1;
6458 pid_t pid;
6459 int j;
6460
6461 name = args[f++];
6462
6463 if (!endswith(name, ".service"))
6464 continue;
6465
6466 if (path_is_absolute(name))
6467 continue;
6468
6469 j = unit_file_exists(arg_scope, &paths, name);
6470 if (j < 0 && !IN_SET(j, -ELOOP, -ERFKILL, -EADDRNOTAVAIL))
6471 return log_error_errno(j, "Failed to look up unit file state: %m");
6472 found_native = j != 0;
6473
6474 /* If we have both a native unit and a SysV script, enable/disable them both (below); for is-enabled,
6475 * prefer the native unit */
6476 if (found_native && streq(verb, "is-enabled"))
6477 continue;
6478
6479 p = path_join(arg_root, SYSTEM_SYSVINIT_PATH, name);
6480 if (!p)
6481 return log_oom();
6482
6483 p[strlen(p) - STRLEN(".service")] = 0;
6484 found_sysv = access(p, F_OK) >= 0;
6485 if (!found_sysv)
6486 continue;
6487
6488 if (!arg_quiet) {
6489 if (found_native)
6490 log_info("Synchronizing state of %s with SysV service script with %s.", name, argv[0]);
6491 else
6492 log_info("%s is not a native service, redirecting to systemd-sysv-install.", name);
6493 }
6494
6495 if (!isempty(arg_root)) {
6496 q = strjoin("--root=", arg_root);
6497 if (!q)
6498 return log_oom();
6499
6500 argv[c++] = q;
6501 }
6502
6503 /* Let's copy the verb, since it's still pointing directly into the original argv[] array we
6504 * got passed, but safe_fork() is likely going to rewrite that for the new child */
6505 v = strdup(verb);
6506 if (!v)
6507 return log_oom();
6508
6509 argv[c++] = v;
6510 argv[c++] = basename(p);
6511 argv[c] = NULL;
6512
6513 l = strv_join((char**)argv, " ");
6514 if (!l)
6515 return log_oom();
6516
6517 if (!arg_quiet)
6518 log_info("Executing: %s", l);
6519
6520 j = safe_fork("(sysv-install)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG, &pid);
6521 if (j < 0)
6522 return j;
6523 if (j == 0) {
6524 /* Child */
6525 execv(argv[0], (char**) argv);
6526 log_error_errno(errno, "Failed to execute %s: %m", argv[0]);
6527 _exit(EXIT_FAILURE);
6528 }
6529
6530 j = wait_for_terminate_and_check("sysv-install", pid, WAIT_LOG_ABNORMAL);
6531 if (j < 0)
6532 return j;
6533 if (streq(verb, "is-enabled")) {
6534 if (j == EXIT_SUCCESS) {
6535 if (!arg_quiet)
6536 puts("enabled");
6537 r = 1;
6538 } else {
6539 if (!arg_quiet)
6540 puts("disabled");
6541 }
6542
6543 } else if (j != EXIT_SUCCESS)
6544 return -EBADE; /* We don't warn here, under the assumption the script already showed an explanation */
6545
6546 if (found_native)
6547 continue;
6548
6549 /* Remove this entry, so that we don't try enabling it as native unit */
6550 assert(f > 0);
6551 f--;
6552 assert(args[f] == name);
6553 strv_remove(args + f, name);
6554 }
6555
6556 #endif
6557 return r;
6558 }
6559
6560 static int mangle_names(const char *operation, char **original_names, char ***mangled_names) {
6561 char **i, **l, **name;
6562 int r;
6563
6564 l = i = new(char*, strv_length(original_names) + 1);
6565 if (!l)
6566 return log_oom();
6567
6568 STRV_FOREACH(name, original_names) {
6569
6570 /* When enabling units qualified path names are OK,
6571 * too, hence allow them explicitly. */
6572
6573 if (is_path(*name)) {
6574 *i = strdup(*name);
6575 if (!*i) {
6576 strv_free(l);
6577 return log_oom();
6578 }
6579 } else {
6580 r = unit_name_mangle_with_suffix(*name, operation,
6581 arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN,
6582 ".service", i);
6583 if (r < 0) {
6584 *i = NULL;
6585 strv_free(l);
6586 return log_error_errno(r, "Failed to mangle unit name: %m");
6587 }
6588 }
6589
6590 i++;
6591 }
6592
6593 *i = NULL;
6594 *mangled_names = l;
6595
6596 return 0;
6597 }
6598
6599 static int normalize_filenames(char **names) {
6600 char **u;
6601 int r;
6602
6603 STRV_FOREACH(u, names)
6604 if (!path_is_absolute(*u)) {
6605 char* normalized_path;
6606
6607 if (!isempty(arg_root))
6608 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
6609 "Non-absolute paths are not allowed when --root is used: %s",
6610 *u);
6611
6612 if (!strchr(*u,'/'))
6613 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
6614 "Link argument does contain at least one directory separator: %s",
6615 *u);
6616
6617 r = path_make_absolute_cwd(*u, &normalized_path);
6618 if (r < 0)
6619 return r;
6620
6621 free_and_replace(*u, normalized_path);
6622 }
6623
6624 return 0;
6625 }
6626
6627 static int normalize_names(char **names, bool warn_if_path) {
6628 char **u;
6629 bool was_path = false;
6630
6631 STRV_FOREACH(u, names) {
6632 int r;
6633
6634 if (!is_path(*u))
6635 continue;
6636
6637 r = free_and_strdup(u, basename(*u));
6638 if (r < 0)
6639 return log_error_errno(r, "Failed to normalize unit file path: %m");
6640
6641 was_path = true;
6642 }
6643
6644 if (warn_if_path && was_path)
6645 log_warning("Warning: Can't execute disable on the unit file path. Proceeding with the unit name.");
6646
6647 return 0;
6648 }
6649
6650 static int unit_exists(LookupPaths *lp, const char *unit) {
6651 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6652 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
6653 _cleanup_free_ char *path = NULL;
6654 static const struct bus_properties_map property_map[] = {
6655 { "LoadState", "s", NULL, offsetof(UnitStatusInfo, load_state) },
6656 { "ActiveState", "s", NULL, offsetof(UnitStatusInfo, active_state)},
6657 {},
6658 };
6659 UnitStatusInfo info = {};
6660 sd_bus *bus;
6661 int r;
6662
6663 if (unit_name_is_valid(unit, UNIT_NAME_TEMPLATE))
6664 return unit_find_template_path(unit, lp, NULL, NULL);
6665
6666 path = unit_dbus_path_from_name(unit);
6667 if (!path)
6668 return log_oom();
6669
6670 r = acquire_bus(BUS_MANAGER, &bus);
6671 if (r < 0)
6672 return r;
6673
6674 r = bus_map_all_properties(bus, "org.freedesktop.systemd1", path, property_map, 0, &error, &m, &info);
6675 if (r < 0)
6676 return log_error_errno(r, "Failed to get properties: %s", bus_error_message(&error, r));
6677
6678 return !streq_ptr(info.load_state, "not-found") || !streq_ptr(info.active_state, "inactive");
6679 }
6680
6681 static int enable_unit(int argc, char *argv[], void *userdata) {
6682 _cleanup_strv_free_ char **names = NULL;
6683 const char *verb = argv[0];
6684 UnitFileChange *changes = NULL;
6685 size_t n_changes = 0;
6686 int carries_install_info = -1;
6687 bool ignore_carries_install_info = arg_quiet;
6688 int r;
6689
6690 if (!argv[1])
6691 return 0;
6692
6693 r = mangle_names("to enable", strv_skip(argv, 1), &names);
6694 if (r < 0)
6695 return r;
6696
6697 r = enable_sysv_units(verb, names);
6698 if (r < 0)
6699 return r;
6700
6701 /* If the operation was fully executed by the SysV compat, let's finish early */
6702 if (strv_isempty(names)) {
6703 if (arg_no_reload || install_client_side())
6704 return 0;
6705 return daemon_reload(argc, argv, userdata);
6706 }
6707
6708 if (streq(verb, "disable")) {
6709 r = normalize_names(names, true);
6710 if (r < 0)
6711 return r;
6712 }
6713
6714 if (streq(verb, "link")) {
6715 r = normalize_filenames(names);
6716 if (r < 0)
6717 return r;
6718 }
6719
6720 if (install_client_side()) {
6721 UnitFileFlags flags;
6722
6723 flags = args_to_flags();
6724 if (streq(verb, "enable")) {
6725 r = unit_file_enable(arg_scope, flags, arg_root, names, &changes, &n_changes);
6726 carries_install_info = r;
6727 } else if (streq(verb, "disable"))
6728 r = unit_file_disable(arg_scope, flags, arg_root, names, &changes, &n_changes);
6729 else if (streq(verb, "reenable")) {
6730 r = unit_file_reenable(arg_scope, flags, arg_root, names, &changes, &n_changes);
6731 carries_install_info = r;
6732 } else if (streq(verb, "link"))
6733 r = unit_file_link(arg_scope, flags, arg_root, names, &changes, &n_changes);
6734 else if (streq(verb, "preset")) {
6735 r = unit_file_preset(arg_scope, flags, arg_root, names, arg_preset_mode, &changes, &n_changes);
6736 } else if (streq(verb, "mask"))
6737 r = unit_file_mask(arg_scope, flags, arg_root, names, &changes, &n_changes);
6738 else if (streq(verb, "unmask"))
6739 r = unit_file_unmask(arg_scope, flags, arg_root, names, &changes, &n_changes);
6740 else if (streq(verb, "revert"))
6741 r = unit_file_revert(arg_scope, arg_root, names, &changes, &n_changes);
6742 else
6743 assert_not_reached("Unknown verb");
6744
6745 unit_file_dump_changes(r, verb, changes, n_changes, arg_quiet);
6746 if (r < 0)
6747 goto finish;
6748 r = 0;
6749 } else {
6750 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL, *m = NULL;
6751 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6752 bool expect_carries_install_info = false;
6753 bool send_runtime = true, send_force = true, send_preset_mode = false;
6754 const char *method;
6755 sd_bus *bus;
6756
6757 if (STR_IN_SET(verb, "mask", "unmask")) {
6758 char **name;
6759 _cleanup_(lookup_paths_free) LookupPaths lp = {};
6760
6761 r = lookup_paths_init(&lp, arg_scope, 0, arg_root);
6762 if (r < 0)
6763 return r;
6764
6765 STRV_FOREACH(name, names) {
6766 r = unit_exists(&lp, *name);
6767 if (r < 0)
6768 return r;
6769 if (r == 0)
6770 log_notice("Unit %s does not exist, proceeding anyway.", *name);
6771 }
6772 }
6773
6774 r = acquire_bus(BUS_MANAGER, &bus);
6775 if (r < 0)
6776 return r;
6777
6778 polkit_agent_open_maybe();
6779
6780 if (streq(verb, "enable")) {
6781 method = "EnableUnitFiles";
6782 expect_carries_install_info = true;
6783 } else if (streq(verb, "disable")) {
6784 method = "DisableUnitFiles";
6785 send_force = false;
6786 } else if (streq(verb, "reenable")) {
6787 method = "ReenableUnitFiles";
6788 expect_carries_install_info = true;
6789 } else if (streq(verb, "link"))
6790 method = "LinkUnitFiles";
6791 else if (streq(verb, "preset")) {
6792
6793 if (arg_preset_mode != UNIT_FILE_PRESET_FULL) {
6794 method = "PresetUnitFilesWithMode";
6795 send_preset_mode = true;
6796 } else
6797 method = "PresetUnitFiles";
6798
6799 expect_carries_install_info = true;
6800 ignore_carries_install_info = true;
6801 } else if (streq(verb, "mask"))
6802 method = "MaskUnitFiles";
6803 else if (streq(verb, "unmask")) {
6804 method = "UnmaskUnitFiles";
6805 send_force = false;
6806 } else if (streq(verb, "revert")) {
6807 method = "RevertUnitFiles";
6808 send_runtime = send_force = false;
6809 } else
6810 assert_not_reached("Unknown verb");
6811
6812 r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, method);
6813 if (r < 0)
6814 return bus_log_create_error(r);
6815
6816 r = sd_bus_message_append_strv(m, names);
6817 if (r < 0)
6818 return bus_log_create_error(r);
6819
6820 if (send_preset_mode) {
6821 r = sd_bus_message_append(m, "s", unit_file_preset_mode_to_string(arg_preset_mode));
6822 if (r < 0)
6823 return bus_log_create_error(r);
6824 }
6825
6826 if (send_runtime) {
6827 r = sd_bus_message_append(m, "b", arg_runtime);
6828 if (r < 0)
6829 return bus_log_create_error(r);
6830 }
6831
6832 if (send_force) {
6833 r = sd_bus_message_append(m, "b", arg_force);
6834 if (r < 0)
6835 return bus_log_create_error(r);
6836 }
6837
6838 r = sd_bus_call(bus, m, 0, &error, &reply);
6839 if (r < 0)
6840 return log_error_errno(r, "Failed to %s unit: %s", verb, bus_error_message(&error, r));
6841
6842 if (expect_carries_install_info) {
6843 r = sd_bus_message_read(reply, "b", &carries_install_info);
6844 if (r < 0)
6845 return bus_log_parse_error(r);
6846 }
6847
6848 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
6849 if (r < 0)
6850 goto finish;
6851
6852 /* Try to reload if enabled */
6853 if (!arg_no_reload)
6854 r = daemon_reload(argc, argv, userdata);
6855 else
6856 r = 0;
6857 }
6858
6859 if (carries_install_info == 0 && !ignore_carries_install_info)
6860 log_notice("The unit files have no installation config (WantedBy=, RequiredBy=, Also=,\n"
6861 "Alias= settings in the [Install] section, and DefaultInstance= for template\n"
6862 "units). This means they are not meant to be enabled using systemctl.\n"
6863 " \n" /* trick: the space is needed so that the line does not get stripped from output */
6864 "Possible reasons for having this kind of units are:\n"
6865 "%1$s A unit may be statically enabled by being symlinked from another unit's\n"
6866 " .wants/ or .requires/ directory.\n"
6867 "%1$s A unit's purpose may be to act as a helper for some other unit which has\n"
6868 " a requirement dependency on it.\n"
6869 "%1$s A unit may be started when needed via activation (socket, path, timer,\n"
6870 " D-Bus, udev, scripted systemctl call, ...).\n"
6871 "%1$s In case of template units, the unit is meant to be enabled with some\n"
6872 " instance name specified.",
6873 special_glyph(SPECIAL_GLYPH_BULLET));
6874
6875 if (arg_now && STR_IN_SET(argv[0], "enable", "disable", "mask")) {
6876 sd_bus *bus;
6877 size_t len, i;
6878
6879 r = acquire_bus(BUS_MANAGER, &bus);
6880 if (r < 0)
6881 goto finish;
6882
6883 len = strv_length(names);
6884 {
6885 char *new_args[len + 2];
6886
6887 new_args[0] = (char*) (streq(argv[0], "enable") ? "start" : "stop");
6888 for (i = 0; i < len; i++)
6889 new_args[i + 1] = basename(names[i]);
6890 new_args[i + 1] = NULL;
6891
6892 r = start_unit(len + 1, new_args, userdata);
6893 }
6894 }
6895
6896 finish:
6897 unit_file_changes_free(changes, n_changes);
6898
6899 return r;
6900 }
6901
6902 static int add_dependency(int argc, char *argv[], void *userdata) {
6903 _cleanup_strv_free_ char **names = NULL;
6904 _cleanup_free_ char *target = NULL;
6905 const char *verb = argv[0];
6906 UnitFileChange *changes = NULL;
6907 size_t n_changes = 0;
6908 UnitDependency dep;
6909 int r = 0;
6910
6911 if (!argv[1])
6912 return 0;
6913
6914 r = unit_name_mangle_with_suffix(argv[1], "as target",
6915 arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN,
6916 ".target", &target);
6917 if (r < 0)
6918 return log_error_errno(r, "Failed to mangle unit name: %m");
6919
6920 r = mangle_names("as dependency", strv_skip(argv, 2), &names);
6921 if (r < 0)
6922 return r;
6923
6924 if (streq(verb, "add-wants"))
6925 dep = UNIT_WANTS;
6926 else if (streq(verb, "add-requires"))
6927 dep = UNIT_REQUIRES;
6928 else
6929 assert_not_reached("Unknown verb");
6930
6931 if (install_client_side()) {
6932 r = unit_file_add_dependency(arg_scope, args_to_flags(), arg_root, names, target, dep, &changes, &n_changes);
6933 unit_file_dump_changes(r, "add dependency on", changes, n_changes, arg_quiet);
6934
6935 if (r > 0)
6936 r = 0;
6937 } else {
6938 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL, *m = NULL;
6939 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6940 sd_bus *bus;
6941
6942 r = acquire_bus(BUS_MANAGER, &bus);
6943 if (r < 0)
6944 return r;
6945
6946 polkit_agent_open_maybe();
6947
6948 r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "AddDependencyUnitFiles");
6949 if (r < 0)
6950 return bus_log_create_error(r);
6951
6952 r = sd_bus_message_append_strv(m, names);
6953 if (r < 0)
6954 return bus_log_create_error(r);
6955
6956 r = sd_bus_message_append(m, "ssbb", target, unit_dependency_to_string(dep), arg_runtime, arg_force);
6957 if (r < 0)
6958 return bus_log_create_error(r);
6959
6960 r = sd_bus_call(bus, m, 0, &error, &reply);
6961 if (r < 0)
6962 return log_error_errno(r, "Failed to add dependency: %s", bus_error_message(&error, r));
6963
6964 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
6965 if (r < 0)
6966 goto finish;
6967
6968 if (arg_no_reload) {
6969 r = 0;
6970 goto finish;
6971 }
6972
6973 r = daemon_reload(argc, argv, userdata);
6974 }
6975
6976 finish:
6977 unit_file_changes_free(changes, n_changes);
6978
6979 return r;
6980 }
6981
6982 static int preset_all(int argc, char *argv[], void *userdata) {
6983 UnitFileChange *changes = NULL;
6984 size_t n_changes = 0;
6985 int r;
6986
6987 if (install_client_side()) {
6988 r = unit_file_preset_all(arg_scope, args_to_flags(), arg_root, arg_preset_mode, &changes, &n_changes);
6989 unit_file_dump_changes(r, "preset", changes, n_changes, arg_quiet);
6990
6991 if (r > 0)
6992 r = 0;
6993 } else {
6994 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6995 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
6996 sd_bus *bus;
6997
6998 r = acquire_bus(BUS_MANAGER, &bus);
6999 if (r < 0)
7000 return r;
7001
7002 polkit_agent_open_maybe();
7003
7004 r = bus_call_method(
7005 bus,
7006 bus_systemd_mgr,
7007 "PresetAllUnitFiles",
7008 &error,
7009 &reply,
7010 "sbb",
7011 unit_file_preset_mode_to_string(arg_preset_mode),
7012 arg_runtime,
7013 arg_force);
7014 if (r < 0)
7015 return log_error_errno(r, "Failed to preset all units: %s", bus_error_message(&error, r));
7016
7017 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
7018 if (r < 0)
7019 goto finish;
7020
7021 if (arg_no_reload) {
7022 r = 0;
7023 goto finish;
7024 }
7025
7026 r = daemon_reload(argc, argv, userdata);
7027 }
7028
7029 finish:
7030 unit_file_changes_free(changes, n_changes);
7031
7032 return r;
7033 }
7034
7035 static int show_installation_targets_client_side(const char *name) {
7036 UnitFileChange *changes = NULL;
7037 size_t n_changes = 0, i;
7038 UnitFileFlags flags;
7039 char **p;
7040 int r;
7041
7042 p = STRV_MAKE(name);
7043 flags = UNIT_FILE_DRY_RUN |
7044 (arg_runtime ? UNIT_FILE_RUNTIME : 0);
7045
7046 r = unit_file_disable(UNIT_FILE_SYSTEM, flags, NULL, p, &changes, &n_changes);
7047 if (r < 0)
7048 return log_error_errno(r, "Failed to get file links for %s: %m", name);
7049
7050 for (i = 0; i < n_changes; i++)
7051 if (changes[i].type == UNIT_FILE_UNLINK)
7052 printf(" %s\n", changes[i].path);
7053
7054 return 0;
7055 }
7056
7057 static int show_installation_targets(sd_bus *bus, const char *name) {
7058 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
7059 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
7060 const char *link;
7061 int r;
7062
7063 r = bus_call_method(bus, bus_systemd_mgr, "GetUnitFileLinks", &error, &reply, "sb", name, arg_runtime);
7064 if (r < 0)
7065 return log_error_errno(r, "Failed to get unit file links for %s: %s", name, bus_error_message(&error, r));
7066
7067 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "s");
7068 if (r < 0)
7069 return bus_log_parse_error(r);
7070
7071 while ((r = sd_bus_message_read(reply, "s", &link)) > 0)
7072 printf(" %s\n", link);
7073
7074 if (r < 0)
7075 return bus_log_parse_error(r);
7076
7077 r = sd_bus_message_exit_container(reply);
7078 if (r < 0)
7079 return bus_log_parse_error(r);
7080
7081 return 0;
7082 }
7083
7084 static int unit_is_enabled(int argc, char *argv[], void *userdata) {
7085 _cleanup_strv_free_ char **names = NULL;
7086 bool enabled;
7087 char **name;
7088 int r;
7089
7090 r = mangle_names("to check", strv_skip(argv, 1), &names);
7091 if (r < 0)
7092 return r;
7093
7094 r = enable_sysv_units(argv[0], names);
7095 if (r < 0)
7096 return r;
7097
7098 enabled = r > 0;
7099
7100 if (install_client_side()) {
7101 STRV_FOREACH(name, names) {
7102 UnitFileState state;
7103
7104 r = unit_file_get_state(arg_scope, arg_root, *name, &state);
7105 if (r < 0)
7106 return log_error_errno(r, "Failed to get unit file state for %s: %m", *name);
7107
7108 if (IN_SET(state,
7109 UNIT_FILE_ENABLED,
7110 UNIT_FILE_ENABLED_RUNTIME,
7111 UNIT_FILE_STATIC,
7112 UNIT_FILE_ALIAS,
7113 UNIT_FILE_INDIRECT,
7114 UNIT_FILE_GENERATED))
7115 enabled = true;
7116
7117 if (!arg_quiet) {
7118 puts(unit_file_state_to_string(state));
7119 if (arg_full) {
7120 r = show_installation_targets_client_side(*name);
7121 if (r < 0)
7122 return r;
7123 }
7124 }
7125 }
7126
7127 r = 0;
7128 } else {
7129 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
7130 sd_bus *bus;
7131
7132 r = acquire_bus(BUS_MANAGER, &bus);
7133 if (r < 0)
7134 return r;
7135
7136 STRV_FOREACH(name, names) {
7137 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
7138 const char *s;
7139
7140 r = bus_call_method(bus, bus_systemd_mgr, "GetUnitFileState", &error, &reply, "s", *name);
7141 if (r < 0)
7142 return log_error_errno(r, "Failed to get unit file state for %s: %s", *name, bus_error_message(&error, r));
7143
7144 r = sd_bus_message_read(reply, "s", &s);
7145 if (r < 0)
7146 return bus_log_parse_error(r);
7147
7148 if (STR_IN_SET(s, "enabled", "enabled-runtime", "static", "indirect", "generated"))
7149 enabled = true;
7150
7151 if (!arg_quiet) {
7152 puts(s);
7153 if (arg_full) {
7154 r = show_installation_targets(bus, *name);
7155 if (r < 0)
7156 return r;
7157 }
7158 }
7159 }
7160 }
7161
7162 return enabled ? EXIT_SUCCESS : EXIT_FAILURE;
7163 }
7164
7165 static int match_startup_finished(sd_bus_message *m, void *userdata, sd_bus_error *error) {
7166 char **state = userdata;
7167 int r;
7168
7169 assert(state);
7170
7171 r = bus_get_property_string(sd_bus_message_get_bus(m), bus_systemd_mgr, "SystemState", NULL, state);
7172
7173 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m)), r);
7174 return 0;
7175 }
7176
7177 static int is_system_running(int argc, char *argv[], void *userdata) {
7178 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
7179 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot_startup_finished = NULL;
7180 _cleanup_(sd_event_unrefp) sd_event* event = NULL;
7181 _cleanup_free_ char *state = NULL;
7182 sd_bus *bus;
7183 int r;
7184
7185 if (running_in_chroot() > 0 || (arg_transport == BUS_TRANSPORT_LOCAL && !sd_booted())) {
7186 if (!arg_quiet)
7187 puts("offline");
7188 return EXIT_FAILURE;
7189 }
7190
7191 r = acquire_bus(BUS_MANAGER, &bus);
7192 if (r < 0)
7193 return r;
7194
7195 if (arg_wait) {
7196 r = sd_event_default(&event);
7197 if (r >= 0)
7198 r = sd_bus_attach_event(bus, event, 0);
7199 if (r >= 0)
7200 r = bus_match_signal_async(
7201 bus,
7202 &slot_startup_finished,
7203 bus_systemd_mgr,
7204 "StartupFinished",
7205 match_startup_finished, NULL, &state);
7206 if (r < 0) {
7207 log_warning_errno(r, "Failed to request match for StartupFinished: %m");
7208 arg_wait = false;
7209 }
7210 }
7211
7212 r = bus_get_property_string(bus, bus_systemd_mgr, "SystemState", &error, &state);
7213 if (r < 0) {
7214 log_warning_errno(r, "Failed to query system state: %s", bus_error_message(&error, r));
7215
7216 if (!arg_quiet)
7217 puts("unknown");
7218 return EXIT_FAILURE;
7219 }
7220
7221 if (arg_wait && STR_IN_SET(state, "initializing", "starting")) {
7222 r = sd_event_loop(event);
7223 if (r < 0) {
7224 log_warning_errno(r, "Failed to get property from event loop: %m");
7225 if (!arg_quiet)
7226 puts("unknown");
7227 return EXIT_FAILURE;
7228 }
7229 }
7230
7231 if (!arg_quiet)
7232 puts(state);
7233
7234 return streq(state, "running") ? EXIT_SUCCESS : EXIT_FAILURE;
7235 }
7236
7237 static int create_edit_temp_file(const char *new_path, const char *original_path, char **ret_tmp_fn) {
7238 _cleanup_free_ char *t = NULL;
7239 int r;
7240
7241 assert(new_path);
7242 assert(original_path);
7243 assert(ret_tmp_fn);
7244
7245 r = tempfn_random(new_path, NULL, &t);
7246 if (r < 0)
7247 return log_error_errno(r, "Failed to determine temporary filename for \"%s\": %m", new_path);
7248
7249 r = mkdir_parents(new_path, 0755);
7250 if (r < 0)
7251 return log_error_errno(r, "Failed to create directories for \"%s\": %m", new_path);
7252
7253 r = copy_file(original_path, t, 0, 0644, 0, 0, COPY_REFLINK);
7254 if (r == -ENOENT) {
7255
7256 r = touch(t);
7257 if (r < 0)
7258 return log_error_errno(r, "Failed to create temporary file \"%s\": %m", t);
7259
7260 } else if (r < 0)
7261 return log_error_errno(r, "Failed to create temporary file for \"%s\": %m", new_path);
7262
7263 *ret_tmp_fn = TAKE_PTR(t);
7264
7265 return 0;
7266 }
7267
7268 static int get_file_to_edit(
7269 const LookupPaths *paths,
7270 const char *name,
7271 char **ret_path) {
7272
7273 _cleanup_free_ char *path = NULL, *run = NULL;
7274
7275 assert(name);
7276 assert(ret_path);
7277
7278 path = path_join(paths->persistent_config, name);
7279 if (!path)
7280 return log_oom();
7281
7282 if (arg_runtime) {
7283 run = path_join(paths->runtime_config, name);
7284 if (!run)
7285 return log_oom();
7286 }
7287
7288 if (arg_runtime) {
7289 if (access(path, F_OK) >= 0)
7290 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
7291 "Refusing to create \"%s\" because it would be overridden by \"%s\" anyway.",
7292 run, path);
7293
7294 *ret_path = TAKE_PTR(run);
7295 } else
7296 *ret_path = TAKE_PTR(path);
7297
7298 return 0;
7299 }
7300
7301 static int unit_file_create_new(
7302 const LookupPaths *paths,
7303 const char *unit_name,
7304 const char *suffix,
7305 char **ret_new_path,
7306 char **ret_tmp_path) {
7307
7308 _cleanup_free_ char *new_path = NULL, *tmp_path = NULL;
7309 const char *ending;
7310 int r;
7311
7312 assert(unit_name);
7313 assert(ret_new_path);
7314 assert(ret_tmp_path);
7315
7316 ending = strjoina(unit_name, suffix);
7317 r = get_file_to_edit(paths, ending, &new_path);
7318 if (r < 0)
7319 return r;
7320
7321 r = create_edit_temp_file(new_path, new_path, &tmp_path);
7322 if (r < 0)
7323 return r;
7324
7325 *ret_new_path = TAKE_PTR(new_path);
7326 *ret_tmp_path = TAKE_PTR(tmp_path);
7327
7328 return 0;
7329 }
7330
7331 static int unit_file_create_copy(
7332 const LookupPaths *paths,
7333 const char *unit_name,
7334 const char *fragment_path,
7335 char **ret_new_path,
7336 char **ret_tmp_path) {
7337
7338 _cleanup_free_ char *new_path = NULL, *tmp_path = NULL;
7339 int r;
7340
7341 assert(fragment_path);
7342 assert(unit_name);
7343 assert(ret_new_path);
7344 assert(ret_tmp_path);
7345
7346 r = get_file_to_edit(paths, unit_name, &new_path);
7347 if (r < 0)
7348 return r;
7349
7350 if (!path_equal(fragment_path, new_path) && access(new_path, F_OK) >= 0) {
7351 char response;
7352
7353 r = ask_char(&response, "yn", "\"%s\" already exists. Overwrite with \"%s\"? [(y)es, (n)o] ", new_path, fragment_path);
7354 if (r < 0)
7355 return r;
7356 if (response != 'y')
7357 return log_warning_errno(SYNTHETIC_ERRNO(EKEYREJECTED), "%s skipped.", unit_name);
7358 }
7359
7360 r = create_edit_temp_file(new_path, fragment_path, &tmp_path);
7361 if (r < 0)
7362 return r;
7363
7364 *ret_new_path = TAKE_PTR(new_path);
7365 *ret_tmp_path = TAKE_PTR(tmp_path);
7366
7367 return 0;
7368 }
7369
7370 static int run_editor(char **paths) {
7371 int r;
7372
7373 assert(paths);
7374
7375 r = safe_fork("(editor)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG|FORK_WAIT, NULL);
7376 if (r < 0)
7377 return r;
7378 if (r == 0) {
7379 char **editor_args = NULL, **tmp_path, **original_path;
7380 size_t n_editor_args = 0, i = 1, argc;
7381 const char **args, *editor, *p;
7382
7383 argc = strv_length(paths)/2 + 1;
7384
7385 /* SYSTEMD_EDITOR takes precedence over EDITOR which takes precedence over VISUAL
7386 * If neither SYSTEMD_EDITOR nor EDITOR nor VISUAL are present,
7387 * we try to execute well known editors
7388 */
7389 editor = getenv("SYSTEMD_EDITOR");
7390 if (!editor)
7391 editor = getenv("EDITOR");
7392 if (!editor)
7393 editor = getenv("VISUAL");
7394
7395 if (!isempty(editor)) {
7396 editor_args = strv_split(editor, WHITESPACE);
7397 if (!editor_args) {
7398 (void) log_oom();
7399 _exit(EXIT_FAILURE);
7400 }
7401 n_editor_args = strv_length(editor_args);
7402 argc += n_editor_args - 1;
7403 }
7404
7405 args = newa(const char*, argc + 1);
7406
7407 if (n_editor_args > 0) {
7408 args[0] = editor_args[0];
7409 for (; i < n_editor_args; i++)
7410 args[i] = editor_args[i];
7411 }
7412
7413 STRV_FOREACH_PAIR(original_path, tmp_path, paths)
7414 args[i++] = *tmp_path;
7415 args[i] = NULL;
7416
7417 if (n_editor_args > 0)
7418 execvp(args[0], (char* const*) args);
7419
7420 FOREACH_STRING(p, "editor", "nano", "vim", "vi") {
7421 args[0] = p;
7422 execvp(p, (char* const*) args);
7423 /* We do not fail if the editor doesn't exist
7424 * because we want to try each one of them before
7425 * failing.
7426 */
7427 if (errno != ENOENT) {
7428 log_error_errno(errno, "Failed to execute %s: %m", editor);
7429 _exit(EXIT_FAILURE);
7430 }
7431 }
7432
7433 log_error("Cannot edit unit(s), no editor available. Please set either $SYSTEMD_EDITOR, $EDITOR or $VISUAL.");
7434 _exit(EXIT_FAILURE);
7435 }
7436
7437 return 0;
7438 }
7439
7440 static int find_paths_to_edit(sd_bus *bus, char **names, char ***paths) {
7441 _cleanup_(lookup_paths_free) LookupPaths lp = {};
7442 char **name;
7443 int r;
7444
7445 assert(names);
7446 assert(paths);
7447
7448 r = lookup_paths_init(&lp, arg_scope, 0, arg_root);
7449 if (r < 0)
7450 return r;
7451
7452 STRV_FOREACH(name, names) {
7453 _cleanup_free_ char *path = NULL, *new_path = NULL, *tmp_path = NULL, *tmp_name = NULL;
7454 const char *unit_name;
7455
7456 r = unit_find_paths(bus, *name, &lp, false, &path, NULL);
7457 if (r == -EKEYREJECTED) {
7458 /* If loading of the unit failed server side complete, then the server won't tell us the unit
7459 * file path. In that case, find the file client side. */
7460 log_debug_errno(r, "Unit '%s' was not loaded correctly, retrying client-side.", *name);
7461 r = unit_find_paths(bus, *name, &lp, true, &path, NULL);
7462 }
7463 if (r == -ERFKILL)
7464 return log_error_errno(r, "Unit '%s' masked, cannot edit.", *name);
7465 if (r < 0)
7466 return r;
7467
7468 if (r == 0) {
7469 assert(!path);
7470
7471 if (!arg_force) {
7472 log_info("Run 'systemctl edit%s --force --full %s' to create a new unit.",
7473 arg_scope == UNIT_FILE_GLOBAL ? " --global" :
7474 arg_scope == UNIT_FILE_USER ? " --user" : "",
7475 *name);
7476 return -ENOENT;
7477 }
7478
7479 /* Create a new unit from scratch */
7480 unit_name = *name;
7481 r = unit_file_create_new(&lp, unit_name,
7482 arg_full ? NULL : ".d/override.conf",
7483 &new_path, &tmp_path);
7484 } else {
7485 assert(path);
7486
7487 unit_name = basename(path);
7488 /* We follow unit aliases, but we need to propagate the instance */
7489 if (unit_name_is_valid(*name, UNIT_NAME_INSTANCE) &&
7490 unit_name_is_valid(unit_name, UNIT_NAME_TEMPLATE)) {
7491 _cleanup_free_ char *instance = NULL;
7492
7493 r = unit_name_to_instance(*name, &instance);
7494 if (r < 0)
7495 return r;
7496
7497 r = unit_name_replace_instance(unit_name, instance, &tmp_name);
7498 if (r < 0)
7499 return r;
7500
7501 unit_name = tmp_name;
7502 }
7503
7504 if (arg_full)
7505 r = unit_file_create_copy(&lp, unit_name, path, &new_path, &tmp_path);
7506 else
7507 r = unit_file_create_new(&lp, unit_name, ".d/override.conf", &new_path, &tmp_path);
7508 }
7509 if (r < 0)
7510 return r;
7511
7512 r = strv_push_pair(paths, new_path, tmp_path);
7513 if (r < 0)
7514 return log_oom();
7515
7516 new_path = tmp_path = NULL;
7517 }
7518
7519 return 0;
7520 }
7521
7522 static int edit(int argc, char *argv[], void *userdata) {
7523 _cleanup_(lookup_paths_free) LookupPaths lp = {};
7524 _cleanup_strv_free_ char **names = NULL;
7525 _cleanup_strv_free_ char **paths = NULL;
7526 char **original, **tmp;
7527 sd_bus *bus;
7528 int r;
7529
7530 if (!on_tty())
7531 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot edit units if not on a tty.");
7532
7533 if (arg_transport != BUS_TRANSPORT_LOCAL)
7534 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot edit units remotely.");
7535
7536 r = lookup_paths_init(&lp, arg_scope, 0, arg_root);
7537 if (r < 0)
7538 return log_error_errno(r, "Failed to determine unit paths: %m");
7539
7540 r = acquire_bus(BUS_MANAGER, &bus);
7541 if (r < 0)
7542 return r;
7543
7544 r = expand_names(bus, strv_skip(argv, 1), NULL, &names, NULL);
7545 if (r < 0)
7546 return log_error_errno(r, "Failed to expand names: %m");
7547
7548 STRV_FOREACH(tmp, names) {
7549 r = unit_is_masked(bus, &lp, *tmp);
7550 if (r < 0)
7551 return r;
7552 if (r > 0)
7553 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot edit %s: unit is masked.", *tmp);
7554 }
7555
7556 r = find_paths_to_edit(bus, names, &paths);
7557 if (r < 0)
7558 return r;
7559
7560 if (strv_isempty(paths))
7561 return -ENOENT;
7562
7563 r = run_editor(paths);
7564 if (r < 0)
7565 goto end;
7566
7567 STRV_FOREACH_PAIR(original, tmp, paths) {
7568 /* If the temporary file is empty we ignore it.
7569 * This allows the user to cancel the modification.
7570 */
7571 if (null_or_empty_path(*tmp)) {
7572 log_warning("Editing \"%s\" canceled: temporary file is empty.", *original);
7573 continue;
7574 }
7575
7576 r = rename(*tmp, *original);
7577 if (r < 0) {
7578 r = log_error_errno(errno, "Failed to rename \"%s\" to \"%s\": %m", *tmp, *original);
7579 goto end;
7580 }
7581 }
7582
7583 r = 0;
7584
7585 if (!arg_no_reload && !install_client_side())
7586 r = daemon_reload(argc, argv, userdata);
7587
7588 end:
7589 STRV_FOREACH_PAIR(original, tmp, paths) {
7590 (void) unlink(*tmp);
7591
7592 /* Removing empty dropin dirs */
7593 if (!arg_full) {
7594 _cleanup_free_ char *dir;
7595
7596 dir = dirname_malloc(*original);
7597 if (!dir)
7598 return log_oom();
7599
7600 /* no need to check if the dir is empty, rmdir
7601 * does nothing if it is not the case.
7602 */
7603 (void) rmdir(dir);
7604 }
7605 }
7606
7607 return r;
7608 }
7609
7610 static int systemctl_help(void) {
7611 _cleanup_free_ char *link = NULL;
7612 int r;
7613
7614 (void) pager_open(arg_pager_flags);
7615
7616 r = terminal_urlify_man("systemctl", "1", &link);
7617 if (r < 0)
7618 return log_oom();
7619
7620 printf("%1$s [OPTIONS...] COMMAND ...\n\n"
7621 "%5$sQuery or send control commands to the system manager.%6$s\n"
7622 "\n%3$sUnit Commands:%4$s\n"
7623 " list-units [PATTERN...] List units currently in memory\n"
7624 " list-sockets [PATTERN...] List socket units currently in memory,\n"
7625 " ordered by address\n"
7626 " list-timers [PATTERN...] List timer units currently in memory,\n"
7627 " ordered by next elapse\n"
7628 " start UNIT... Start (activate) one or more units\n"
7629 " stop UNIT... Stop (deactivate) one or more units\n"
7630 " reload UNIT... Reload one or more units\n"
7631 " restart UNIT... Start or restart one or more units\n"
7632 " try-restart UNIT... Restart one or more units if active\n"
7633 " reload-or-restart UNIT... Reload one or more units if possible,\n"
7634 " otherwise start or restart\n"
7635 " try-reload-or-restart UNIT... If active, reload one or more units,\n"
7636 " if supported, otherwise restart\n"
7637 " isolate UNIT Start one unit and stop all others\n"
7638 " kill UNIT... Send signal to processes of a unit\n"
7639 " clean UNIT... Clean runtime, cache, state, logs or\n"
7640 " configuration of unit\n"
7641 " freeze PATTERN... Freeze execution of unit processes\n"
7642 " thaw PATTERN... Resume execution of a frozen unit\n"
7643 " is-active PATTERN... Check whether units are active\n"
7644 " is-failed PATTERN... Check whether units are failed\n"
7645 " status [PATTERN...|PID...] Show runtime status of one or more units\n"
7646 " show [PATTERN...|JOB...] Show properties of one or more\n"
7647 " units/jobs or the manager\n"
7648 " cat PATTERN... Show files and drop-ins of specified units\n"
7649 " set-property UNIT PROPERTY=VALUE... Sets one or more properties of a unit\n"
7650 " help PATTERN...|PID... Show manual for one or more units\n"
7651 " reset-failed [PATTERN...] Reset failed state for all, one, or more\n"
7652 " units\n"
7653 " list-dependencies [UNIT...] Recursively show units which are required\n"
7654 " or wanted by the units or by which those\n"
7655 " units are required or wanted"
7656 "\n%3$sUnit File Commands:%4$s\n"
7657 " list-unit-files [PATTERN...] List installed unit files\n"
7658 " enable [UNIT...|PATH...] Enable one or more unit files\n"
7659 " disable UNIT... Disable one or more unit files\n"
7660 " reenable UNIT... Reenable one or more unit files\n"
7661 " preset UNIT... Enable/disable one or more unit files\n"
7662 " based on preset configuration\n"
7663 " preset-all Enable/disable all unit files based on\n"
7664 " preset configuration\n"
7665 " is-enabled UNIT... Check whether unit files are enabled\n"
7666 " mask UNIT... Mask one or more units\n"
7667 " unmask UNIT... Unmask one or more units\n"
7668 " link PATH... Link one or more units files into\n"
7669 " the search path\n"
7670 " revert UNIT... Revert one or more unit files to vendor\n"
7671 " version\n"
7672 " add-wants TARGET UNIT... Add 'Wants' dependency for the target\n"
7673 " on specified one or more units\n"
7674 " add-requires TARGET UNIT... Add 'Requires' dependency for the target\n"
7675 " on specified one or more units\n"
7676 " edit UNIT... Edit one or more unit files\n"
7677 " get-default Get the name of the default target\n"
7678 " set-default TARGET Set the default target\n"
7679 "\n%3$sMachine Commands:%4$s\n"
7680 " list-machines [PATTERN...] List local containers and host\n"
7681 "\n%3$sJob Commands:%4$s\n"
7682 " list-jobs [PATTERN...] List jobs\n"
7683 " cancel [JOB...] Cancel all, one, or more jobs\n"
7684 "\n%3$sEnvironment Commands:%4$s\n"
7685 " show-environment Dump environment\n"
7686 " set-environment VARIABLE=VALUE... Set one or more environment variables\n"
7687 " unset-environment VARIABLE... Unset one or more environment variables\n"
7688 " import-environment [VARIABLE...] Import all or some environment variables\n"
7689 "\n%3$sManager State Commands:%4$s\n"
7690 " daemon-reload Reload systemd manager configuration\n"
7691 " daemon-reexec Reexecute systemd manager\n"
7692 " log-level [LEVEL] Get/set logging threshold for manager\n"
7693 " log-target [TARGET] Get/set logging target for manager\n"
7694 " service-watchdogs [BOOL] Get/set service watchdog state\n"
7695 "\n%3$sSystem Commands:%4$s\n"
7696 " is-system-running Check whether system is fully running\n"
7697 " default Enter system default mode\n"
7698 " rescue Enter system rescue mode\n"
7699 " emergency Enter system emergency mode\n"
7700 " halt Shut down and halt the system\n"
7701 " poweroff Shut down and power-off the system\n"
7702 " reboot Shut down and reboot the system\n"
7703 " kexec Shut down and reboot the system with kexec\n"
7704 " exit [EXIT_CODE] Request user instance or container exit\n"
7705 " switch-root ROOT [INIT] Change to a different root file system\n"
7706 " suspend Suspend the system\n"
7707 " hibernate Hibernate the system\n"
7708 " hybrid-sleep Hibernate and suspend the system\n"
7709 " suspend-then-hibernate Suspend the system, wake after a period of\n"
7710 " time, and hibernate"
7711 "\n%3$sOptions:%4$s\n"
7712 " -h --help Show this help\n"
7713 " --version Show package version\n"
7714 " --system Connect to system manager\n"
7715 " --user Connect to user service manager\n"
7716 " -H --host=[USER@]HOST Operate on remote host\n"
7717 " -M --machine=CONTAINER Operate on a local container\n"
7718 " -t --type=TYPE List units of a particular type\n"
7719 " --state=STATE List units with particular LOAD or SUB or ACTIVE state\n"
7720 " --failed Shorcut for --state=failed\n"
7721 " -p --property=NAME Show only properties by this name\n"
7722 " -P NAME Equivalent to --value --property=NAME\n"
7723 " -a --all Show all properties/all units currently in memory,\n"
7724 " including dead/empty ones. To list all units installed\n"
7725 " on the system, use 'list-unit-files' instead.\n"
7726 " -l --full Don't ellipsize unit names on output\n"
7727 " -r --recursive Show unit list of host and local containers\n"
7728 " --reverse Show reverse dependencies with 'list-dependencies'\n"
7729 " --with-dependencies Show unit dependencies with 'status', 'cat',\n"
7730 " 'list-units', and 'list-unit-files'.\n"
7731 " --job-mode=MODE Specify how to deal with already queued jobs, when\n"
7732 " queueing a new job\n"
7733 " -T --show-transaction When enqueuing a unit job, show full transaction\n"
7734 " --show-types When showing sockets, explicitly show their type\n"
7735 " --value When showing properties, only print the value\n"
7736 " -i --ignore-inhibitors When shutting down or sleeping, ignore inhibitors\n"
7737 " --kill-who=WHO Whom to send signal to\n"
7738 " -s --signal=SIGNAL Which signal to send\n"
7739 " --what=RESOURCES Which types of resources to remove\n"
7740 " --now Start or stop unit after enabling or disabling it\n"
7741 " --dry-run Only print what would be done\n"
7742 " Currently supported by verbs: halt, poweroff, reboot,\n"
7743 " kexec, suspend, hibernate, suspend-then-hibernate,\n"
7744 " hybrid-sleep, default, rescue, emergency, and exit.\n"
7745 " -q --quiet Suppress output\n"
7746 " --wait For (re)start, wait until service stopped again\n"
7747 " For is-system-running, wait until startup is completed\n"
7748 " --no-block Do not wait until operation finished\n"
7749 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7750 " --no-reload Don't reload daemon after en-/dis-abling unit files\n"
7751 " --no-legend Do not print a legend (column headers and hints)\n"
7752 " --no-pager Do not pipe output into a pager\n"
7753 " --no-ask-password Do not ask for system passwords\n"
7754 " --global Enable/disable/mask unit files globally\n"
7755 " --runtime Enable/disable/mask unit files temporarily until next\n"
7756 " reboot\n"
7757 " -f --force When enabling unit files, override existing symlinks\n"
7758 " When shutting down, execute action immediately\n"
7759 " --preset-mode= Apply only enable, only disable, or all presets\n"
7760 " --root=PATH Enable/disable/mask unit files in the specified root\n"
7761 " directory\n"
7762 " -n --lines=INTEGER Number of journal entries to show\n"
7763 " -o --output=STRING Change journal output mode (short, short-precise,\n"
7764 " short-iso, short-iso-precise, short-full,\n"
7765 " short-monotonic, short-unix,\n"
7766 " verbose, export, json, json-pretty, json-sse, cat)\n"
7767 " --firmware-setup Tell the firmware to show the setup menu on next boot\n"
7768 " --boot-loader-menu=TIME\n"
7769 " Boot into boot loader menu on next boot\n"
7770 " --boot-loader-entry=NAME\n"
7771 " Boot into a specific boot loader entry on next boot\n"
7772 " --plain Print unit dependencies as a list instead of a tree\n"
7773 "\nSee the %2$s for details.\n"
7774 , program_invocation_short_name
7775 , link
7776 , ansi_underline(), ansi_normal()
7777 , ansi_highlight(), ansi_normal()
7778 );
7779
7780 return 0;
7781 }
7782
7783 static int halt_help(void) {
7784 _cleanup_free_ char *link = NULL;
7785 int r;
7786
7787 r = terminal_urlify_man("halt", "8", &link);
7788 if (r < 0)
7789 return log_oom();
7790
7791 printf("%s [OPTIONS...]%s\n"
7792 "\n%s%s the system.%s\n"
7793 "\nOptions:\n"
7794 " --help Show this help\n"
7795 " --halt Halt the machine\n"
7796 " -p --poweroff Switch off the machine\n"
7797 " --reboot Reboot the machine\n"
7798 " -f --force Force immediate halt/power-off/reboot\n"
7799 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
7800 " -d --no-wtmp Don't write wtmp record\n"
7801 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7802 "\nSee the %s for details.\n"
7803 , program_invocation_short_name
7804 , arg_action == ACTION_REBOOT ? " [ARG]" : ""
7805 , ansi_highlight()
7806 , arg_action == ACTION_REBOOT ? "Reboot" :
7807 arg_action == ACTION_POWEROFF ? "Power off" :
7808 "Halt"
7809 , ansi_normal()
7810 , link
7811 );
7812
7813 return 0;
7814 }
7815
7816 static int shutdown_help(void) {
7817 _cleanup_free_ char *link = NULL;
7818 int r;
7819
7820 r = terminal_urlify_man("shutdown", "8", &link);
7821 if (r < 0)
7822 return log_oom();
7823
7824 printf("%s [OPTIONS...] [TIME] [WALL...]\n"
7825 "\n%sShut down the system.%s\n"
7826 "\nOptions:\n"
7827 " --help Show this help\n"
7828 " -H --halt Halt the machine\n"
7829 " -P --poweroff Power-off the machine\n"
7830 " -r --reboot Reboot the machine\n"
7831 " -h Equivalent to --poweroff, overridden by --halt\n"
7832 " -k Don't halt/power-off/reboot, just send warnings\n"
7833 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7834 " -c Cancel a pending shutdown\n"
7835 "\nSee the %s for details.\n"
7836 , program_invocation_short_name
7837 , ansi_highlight(), ansi_normal()
7838 , link
7839 );
7840
7841 return 0;
7842 }
7843
7844 static int telinit_help(void) {
7845 _cleanup_free_ char *link = NULL;
7846 int r;
7847
7848 r = terminal_urlify_man("telinit", "8", &link);
7849 if (r < 0)
7850 return log_oom();
7851
7852 printf("%s [OPTIONS...] COMMAND\n\n"
7853 "%sSend control commands to the init daemon.%s\n"
7854 "\nCommands:\n"
7855 " 0 Power-off the machine\n"
7856 " 6 Reboot the machine\n"
7857 " 2, 3, 4, 5 Start runlevelX.target unit\n"
7858 " 1, s, S Enter rescue mode\n"
7859 " q, Q Reload init daemon configuration\n"
7860 " u, U Reexecute init daemon\n"
7861 "\nOptions:\n"
7862 " --help Show this help\n"
7863 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7864 "\nSee the %s for details.\n"
7865 , program_invocation_short_name
7866 , ansi_highlight(), ansi_normal()
7867 , link
7868 );
7869
7870 return 0;
7871 }
7872
7873 static int runlevel_help(void) {
7874 _cleanup_free_ char *link = NULL;
7875 int r;
7876
7877 r = terminal_urlify_man("runlevel", "8", &link);
7878 if (r < 0)
7879 return log_oom();
7880
7881 printf("%s [OPTIONS...]\n"
7882 "\n%sPrints the previous and current runlevel of the init system.%s\n"
7883 "\nOptions:\n"
7884 " --help Show this help\n"
7885 "\nSee the %s for details.\n"
7886 , program_invocation_short_name
7887 , ansi_highlight(), ansi_normal()
7888 , link
7889 );
7890
7891 return 0;
7892 }
7893
7894 static void help_types(void) {
7895 if (!arg_no_legend)
7896 puts("Available unit types:");
7897
7898 DUMP_STRING_TABLE(unit_type, UnitType, _UNIT_TYPE_MAX);
7899 }
7900
7901 static void help_states(void) {
7902 if (!arg_no_legend)
7903 puts("Available unit load states:");
7904 DUMP_STRING_TABLE(unit_load_state, UnitLoadState, _UNIT_LOAD_STATE_MAX);
7905
7906 if (!arg_no_legend)
7907 puts("\nAvailable unit active states:");
7908 DUMP_STRING_TABLE(unit_active_state, UnitActiveState, _UNIT_ACTIVE_STATE_MAX);
7909
7910 if (!arg_no_legend)
7911 puts("\nAvailable unit file states:");
7912 DUMP_STRING_TABLE(unit_file_state, UnitFileState, _UNIT_FILE_STATE_MAX);
7913
7914 if (!arg_no_legend)
7915 puts("\nAvailable automount unit substates:");
7916 DUMP_STRING_TABLE(automount_state, AutomountState, _AUTOMOUNT_STATE_MAX);
7917
7918 if (!arg_no_legend)
7919 puts("\nAvailable device unit substates:");
7920 DUMP_STRING_TABLE(device_state, DeviceState, _DEVICE_STATE_MAX);
7921
7922 if (!arg_no_legend)
7923 puts("\nAvailable mount unit substates:");
7924 DUMP_STRING_TABLE(mount_state, MountState, _MOUNT_STATE_MAX);
7925
7926 if (!arg_no_legend)
7927 puts("\nAvailable path unit substates:");
7928 DUMP_STRING_TABLE(path_state, PathState, _PATH_STATE_MAX);
7929
7930 if (!arg_no_legend)
7931 puts("\nAvailable scope unit substates:");
7932 DUMP_STRING_TABLE(scope_state, ScopeState, _SCOPE_STATE_MAX);
7933
7934 if (!arg_no_legend)
7935 puts("\nAvailable service unit substates:");
7936 DUMP_STRING_TABLE(service_state, ServiceState, _SERVICE_STATE_MAX);
7937
7938 if (!arg_no_legend)
7939 puts("\nAvailable slice unit substates:");
7940 DUMP_STRING_TABLE(slice_state, SliceState, _SLICE_STATE_MAX);
7941
7942 if (!arg_no_legend)
7943 puts("\nAvailable socket unit substates:");
7944 DUMP_STRING_TABLE(socket_state, SocketState, _SOCKET_STATE_MAX);
7945
7946 if (!arg_no_legend)
7947 puts("\nAvailable swap unit substates:");
7948 DUMP_STRING_TABLE(swap_state, SwapState, _SWAP_STATE_MAX);
7949
7950 if (!arg_no_legend)
7951 puts("\nAvailable target unit substates:");
7952 DUMP_STRING_TABLE(target_state, TargetState, _TARGET_STATE_MAX);
7953
7954 if (!arg_no_legend)
7955 puts("\nAvailable timer unit substates:");
7956 DUMP_STRING_TABLE(timer_state, TimerState, _TIMER_STATE_MAX);
7957 }
7958
7959 static int help_boot_loader_entry(void) {
7960 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
7961 _cleanup_strv_free_ char **l = NULL;
7962 sd_bus *bus;
7963 char **i;
7964 int r;
7965
7966 r = acquire_bus(BUS_FULL, &bus);
7967 if (r < 0)
7968 return r;
7969
7970 r = bus_get_property_strv(bus, bus_login_mgr, "BootLoaderEntries", &error, &l);
7971 if (r < 0)
7972 return log_error_errno(r, "Failed to enumerate boot loader entries: %s", bus_error_message(&error, r));
7973
7974 if (strv_isempty(l))
7975 return log_error_errno(SYNTHETIC_ERRNO(ENODATA), "No boot loader entries discovered.");
7976
7977 STRV_FOREACH(i, l)
7978 puts(*i);
7979
7980 return 0;
7981 }
7982
7983 static int systemctl_parse_argv(int argc, char *argv[]) {
7984 enum {
7985 ARG_FAIL = 0x100,
7986 ARG_REVERSE,
7987 ARG_AFTER,
7988 ARG_BEFORE,
7989 ARG_DRY_RUN,
7990 ARG_SHOW_TYPES,
7991 ARG_IRREVERSIBLE,
7992 ARG_IGNORE_DEPENDENCIES,
7993 ARG_VALUE,
7994 ARG_VERSION,
7995 ARG_USER,
7996 ARG_SYSTEM,
7997 ARG_GLOBAL,
7998 ARG_NO_BLOCK,
7999 ARG_NO_LEGEND,
8000 ARG_NO_PAGER,
8001 ARG_NO_WALL,
8002 ARG_ROOT,
8003 ARG_NO_RELOAD,
8004 ARG_KILL_WHO,
8005 ARG_NO_ASK_PASSWORD,
8006 ARG_FAILED,
8007 ARG_RUNTIME,
8008 ARG_PLAIN,
8009 ARG_STATE,
8010 ARG_JOB_MODE,
8011 ARG_PRESET_MODE,
8012 ARG_FIRMWARE_SETUP,
8013 ARG_BOOT_LOADER_MENU,
8014 ARG_BOOT_LOADER_ENTRY,
8015 ARG_NOW,
8016 ARG_MESSAGE,
8017 ARG_WITH_DEPENDENCIES,
8018 ARG_WAIT,
8019 ARG_WHAT,
8020 ARG_REBOOT_ARG,
8021 };
8022
8023 static const struct option options[] = {
8024 { "help", no_argument, NULL, 'h' },
8025 { "version", no_argument, NULL, ARG_VERSION },
8026 { "type", required_argument, NULL, 't' },
8027 { "property", required_argument, NULL, 'p' },
8028 { "all", no_argument, NULL, 'a' },
8029 { "reverse", no_argument, NULL, ARG_REVERSE },
8030 { "after", no_argument, NULL, ARG_AFTER },
8031 { "before", no_argument, NULL, ARG_BEFORE },
8032 { "show-types", no_argument, NULL, ARG_SHOW_TYPES },
8033 { "failed", no_argument, NULL, ARG_FAILED }, /* compatibility only */
8034 { "full", no_argument, NULL, 'l' },
8035 { "job-mode", required_argument, NULL, ARG_JOB_MODE },
8036 { "fail", no_argument, NULL, ARG_FAIL }, /* compatibility only */
8037 { "irreversible", no_argument, NULL, ARG_IRREVERSIBLE }, /* compatibility only */
8038 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES }, /* compatibility only */
8039 { "ignore-inhibitors", no_argument, NULL, 'i' },
8040 { "value", no_argument, NULL, ARG_VALUE },
8041 { "user", no_argument, NULL, ARG_USER },
8042 { "system", no_argument, NULL, ARG_SYSTEM },
8043 { "global", no_argument, NULL, ARG_GLOBAL },
8044 { "wait", no_argument, NULL, ARG_WAIT },
8045 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
8046 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
8047 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
8048 { "no-wall", no_argument, NULL, ARG_NO_WALL },
8049 { "dry-run", no_argument, NULL, ARG_DRY_RUN },
8050 { "quiet", no_argument, NULL, 'q' },
8051 { "root", required_argument, NULL, ARG_ROOT },
8052 { "force", no_argument, NULL, 'f' },
8053 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
8054 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
8055 { "signal", required_argument, NULL, 's' },
8056 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
8057 { "host", required_argument, NULL, 'H' },
8058 { "machine", required_argument, NULL, 'M' },
8059 { "runtime", no_argument, NULL, ARG_RUNTIME },
8060 { "lines", required_argument, NULL, 'n' },
8061 { "output", required_argument, NULL, 'o' },
8062 { "plain", no_argument, NULL, ARG_PLAIN },
8063 { "state", required_argument, NULL, ARG_STATE },
8064 { "recursive", no_argument, NULL, 'r' },
8065 { "with-dependencies", no_argument, NULL, ARG_WITH_DEPENDENCIES },
8066 { "preset-mode", required_argument, NULL, ARG_PRESET_MODE },
8067 { "firmware-setup", no_argument, NULL, ARG_FIRMWARE_SETUP },
8068 { "boot-loader-menu", required_argument, NULL, ARG_BOOT_LOADER_MENU },
8069 { "boot-loader-entry", required_argument, NULL, ARG_BOOT_LOADER_ENTRY },
8070 { "now", no_argument, NULL, ARG_NOW },
8071 { "message", required_argument, NULL, ARG_MESSAGE },
8072 { "show-transaction", no_argument, NULL, 'T' },
8073 { "what", required_argument, NULL, ARG_WHAT },
8074 { "reboot-argument", required_argument, NULL, ARG_REBOOT_ARG },
8075 {}
8076 };
8077
8078 int c, r;
8079
8080 assert(argc >= 0);
8081 assert(argv);
8082
8083 /* we default to allowing interactive authorization only in systemctl (not in the legacy commands) */
8084 arg_ask_password = true;
8085
8086 while ((c = getopt_long(argc, argv, "ht:p:P:alqfs:H:M:n:o:iTr.::", options, NULL)) >= 0)
8087
8088 switch (c) {
8089
8090 case 'h':
8091 return systemctl_help();
8092
8093 case ARG_VERSION:
8094 return version();
8095
8096 case 't': {
8097 const char *p;
8098
8099 if (isempty(optarg))
8100 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8101 "--type= requires arguments.");
8102
8103 for (p = optarg;;) {
8104 _cleanup_free_ char *type = NULL;
8105
8106 r = extract_first_word(&p, &type, ",", 0);
8107 if (r < 0)
8108 return log_error_errno(r, "Failed to parse type: %s", optarg);
8109 if (r == 0)
8110 break;
8111
8112 if (streq(type, "help")) {
8113 help_types();
8114 return 0;
8115 }
8116
8117 if (unit_type_from_string(type) >= 0) {
8118 if (strv_consume(&arg_types, TAKE_PTR(type)) < 0)
8119 return log_oom();
8120 continue;
8121 }
8122
8123 /* It's much nicer to use --state= for
8124 * load states, but let's support this
8125 * in --types= too for compatibility
8126 * with old versions */
8127 if (unit_load_state_from_string(type) >= 0) {
8128 if (strv_consume(&arg_states, TAKE_PTR(type)) < 0)
8129 return log_oom();
8130 continue;
8131 }
8132
8133 log_error("Unknown unit type or load state '%s'.", type);
8134 return log_info_errno(SYNTHETIC_ERRNO(EINVAL),
8135 "Use -t help to see a list of allowed values.");
8136 }
8137
8138 break;
8139 }
8140
8141 case 'P':
8142 arg_value = true;
8143 _fallthrough_;
8144
8145 case 'p':
8146 /* Make sure that if the empty property list was specified, we won't show any
8147 properties. */
8148 if (isempty(optarg) && !arg_properties) {
8149 arg_properties = new0(char*, 1);
8150 if (!arg_properties)
8151 return log_oom();
8152 } else {
8153 const char *p;
8154
8155 for (p = optarg;;) {
8156 _cleanup_free_ char *prop = NULL;
8157
8158 r = extract_first_word(&p, &prop, ",", 0);
8159 if (r < 0)
8160 return log_error_errno(r, "Failed to parse property: %s", optarg);
8161 if (r == 0)
8162 break;
8163
8164 if (strv_consume(&arg_properties, TAKE_PTR(prop)) < 0)
8165 return log_oom();
8166 }
8167 }
8168
8169 /* If the user asked for a particular property, show it, even if it is empty. */
8170 arg_all = true;
8171
8172 break;
8173
8174 case 'a':
8175 arg_all = true;
8176 break;
8177
8178 case ARG_REVERSE:
8179 arg_dependency = DEPENDENCY_REVERSE;
8180 break;
8181
8182 case ARG_AFTER:
8183 arg_dependency = DEPENDENCY_AFTER;
8184 arg_jobs_after = true;
8185 break;
8186
8187 case ARG_BEFORE:
8188 arg_dependency = DEPENDENCY_BEFORE;
8189 arg_jobs_before = true;
8190 break;
8191
8192 case ARG_SHOW_TYPES:
8193 arg_show_types = true;
8194 break;
8195
8196 case ARG_VALUE:
8197 arg_value = true;
8198 break;
8199
8200 case ARG_JOB_MODE:
8201 arg_job_mode = optarg;
8202 break;
8203
8204 case ARG_FAIL:
8205 arg_job_mode = "fail";
8206 break;
8207
8208 case ARG_IRREVERSIBLE:
8209 arg_job_mode = "replace-irreversibly";
8210 break;
8211
8212 case ARG_IGNORE_DEPENDENCIES:
8213 arg_job_mode = "ignore-dependencies";
8214 break;
8215
8216 case ARG_USER:
8217 arg_scope = UNIT_FILE_USER;
8218 break;
8219
8220 case ARG_SYSTEM:
8221 arg_scope = UNIT_FILE_SYSTEM;
8222 break;
8223
8224 case ARG_GLOBAL:
8225 arg_scope = UNIT_FILE_GLOBAL;
8226 break;
8227
8228 case ARG_WAIT:
8229 arg_wait = true;
8230 break;
8231
8232 case ARG_NO_BLOCK:
8233 arg_no_block = true;
8234 break;
8235
8236 case ARG_NO_LEGEND:
8237 arg_no_legend = true;
8238 break;
8239
8240 case ARG_NO_PAGER:
8241 arg_pager_flags |= PAGER_DISABLE;
8242 break;
8243
8244 case ARG_NO_WALL:
8245 arg_no_wall = true;
8246 break;
8247
8248 case ARG_ROOT:
8249 r = parse_path_argument_and_warn(optarg, false, &arg_root);
8250 if (r < 0)
8251 return r;
8252 break;
8253
8254 case 'l':
8255 arg_full = true;
8256 break;
8257
8258 case ARG_FAILED:
8259 if (strv_extend(&arg_states, "failed") < 0)
8260 return log_oom();
8261
8262 break;
8263
8264 case ARG_DRY_RUN:
8265 arg_dry_run = true;
8266 break;
8267
8268 case 'q':
8269 arg_quiet = true;
8270 break;
8271
8272 case 'f':
8273 arg_force++;
8274 break;
8275
8276 case ARG_NO_RELOAD:
8277 arg_no_reload = true;
8278 break;
8279
8280 case ARG_KILL_WHO:
8281 arg_kill_who = optarg;
8282 break;
8283
8284 case 's':
8285 if (streq(optarg, "help")) {
8286 DUMP_STRING_TABLE(signal, int, _NSIG);
8287 return 0;
8288 }
8289
8290 arg_signal = signal_from_string(optarg);
8291 if (arg_signal < 0)
8292 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8293 "Failed to parse signal string %s.",
8294 optarg);
8295 break;
8296
8297 case ARG_NO_ASK_PASSWORD:
8298 arg_ask_password = false;
8299 break;
8300
8301 case 'H':
8302 arg_transport = BUS_TRANSPORT_REMOTE;
8303 arg_host = optarg;
8304 break;
8305
8306 case 'M':
8307 arg_transport = BUS_TRANSPORT_MACHINE;
8308 arg_host = optarg;
8309 break;
8310
8311 case ARG_RUNTIME:
8312 arg_runtime = true;
8313 break;
8314
8315 case 'n':
8316 if (safe_atou(optarg, &arg_lines) < 0)
8317 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8318 "Failed to parse lines '%s'",
8319 optarg);
8320 break;
8321
8322 case 'o':
8323 if (streq(optarg, "help")) {
8324 DUMP_STRING_TABLE(output_mode, OutputMode, _OUTPUT_MODE_MAX);
8325 return 0;
8326 }
8327
8328 arg_output = output_mode_from_string(optarg);
8329 if (arg_output < 0)
8330 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8331 "Unknown output '%s'.",
8332 optarg);
8333
8334 if (OUTPUT_MODE_IS_JSON(arg_output)) {
8335 arg_no_legend = true;
8336 arg_plain = true;
8337 }
8338 break;
8339
8340 case 'i':
8341 arg_ignore_inhibitors = true;
8342 break;
8343
8344 case ARG_PLAIN:
8345 arg_plain = true;
8346 break;
8347
8348 case ARG_FIRMWARE_SETUP:
8349 arg_firmware_setup = true;
8350 break;
8351
8352 case ARG_BOOT_LOADER_MENU:
8353
8354 r = parse_sec(optarg, &arg_boot_loader_menu);
8355 if (r < 0)
8356 return log_error_errno(r, "Failed to parse --boot-loader-menu= argument '%s': %m", optarg);
8357
8358 break;
8359
8360 case ARG_BOOT_LOADER_ENTRY:
8361
8362 if (streq(optarg, "help")) { /* Yes, this means, "help" is not a valid boot loader entry name we can deal with */
8363 r = help_boot_loader_entry();
8364 if (r < 0)
8365 return r;
8366
8367 return 0;
8368 }
8369
8370 arg_boot_loader_entry = empty_to_null(optarg);
8371 break;
8372
8373 case ARG_STATE: {
8374 const char *p;
8375
8376 if (isempty(optarg))
8377 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8378 "--state= requires arguments.");
8379
8380 for (p = optarg;;) {
8381 _cleanup_free_ char *s = NULL;
8382
8383 r = extract_first_word(&p, &s, ",", 0);
8384 if (r < 0)
8385 return log_error_errno(r, "Failed to parse state: %s", optarg);
8386 if (r == 0)
8387 break;
8388
8389 if (streq(s, "help")) {
8390 help_states();
8391 return 0;
8392 }
8393
8394 if (strv_consume(&arg_states, TAKE_PTR(s)) < 0)
8395 return log_oom();
8396 }
8397 break;
8398 }
8399
8400 case 'r':
8401 if (geteuid() != 0)
8402 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
8403 "--recursive requires root privileges.");
8404
8405 arg_recursive = true;
8406 break;
8407
8408 case ARG_PRESET_MODE:
8409 if (streq(optarg, "help")) {
8410 DUMP_STRING_TABLE(unit_file_preset_mode, UnitFilePresetMode, _UNIT_FILE_PRESET_MAX);
8411 return 0;
8412 }
8413
8414 arg_preset_mode = unit_file_preset_mode_from_string(optarg);
8415 if (arg_preset_mode < 0)
8416 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8417 "Failed to parse preset mode: %s.", optarg);
8418
8419 break;
8420
8421 case ARG_NOW:
8422 arg_now = true;
8423 break;
8424
8425 case ARG_MESSAGE:
8426 if (strv_extend(&arg_wall, optarg) < 0)
8427 return log_oom();
8428 break;
8429
8430 case 'T':
8431 arg_show_transaction = true;
8432 break;
8433
8434 case ARG_WITH_DEPENDENCIES:
8435 arg_with_dependencies = true;
8436 break;
8437
8438 case ARG_WHAT: {
8439 const char *p;
8440
8441 if (isempty(optarg))
8442 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--what= requires arguments.");
8443
8444 for (p = optarg;;) {
8445 _cleanup_free_ char *k = NULL;
8446
8447 r = extract_first_word(&p, &k, ",", 0);
8448 if (r < 0)
8449 return log_error_errno(r, "Failed to parse directory type: %s", optarg);
8450 if (r == 0)
8451 break;
8452
8453 if (streq(k, "help")) {
8454 puts("runtime\n"
8455 "state\n"
8456 "cache\n"
8457 "logs\n"
8458 "configuration");
8459 return 0;
8460 }
8461
8462 r = strv_consume(&arg_clean_what, TAKE_PTR(k));
8463 if (r < 0)
8464 return log_oom();
8465 }
8466
8467 break;
8468 }
8469
8470 case ARG_REBOOT_ARG:
8471 arg_reboot_argument = optarg;
8472 break;
8473
8474 case '.':
8475 /* Output an error mimicking getopt, and print a hint afterwards */
8476 log_error("%s: invalid option -- '.'", program_invocation_name);
8477 log_notice("Hint: to specify units starting with a dash, use \"--\":\n"
8478 " %s [OPTIONS...] COMMAND -- -.%s ...",
8479 program_invocation_name, optarg ?: "mount");
8480 _fallthrough_;
8481
8482 case '?':
8483 return -EINVAL;
8484
8485 default:
8486 assert_not_reached("Unhandled option");
8487 }
8488
8489 if (arg_transport != BUS_TRANSPORT_LOCAL && arg_scope != UNIT_FILE_SYSTEM)
8490 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8491 "Cannot access user instance remotely.");
8492
8493 if (arg_wait && arg_no_block)
8494 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8495 "--wait may not be combined with --no-block.");
8496
8497 return 1;
8498 }
8499
8500 static int halt_parse_argv(int argc, char *argv[]) {
8501 enum {
8502 ARG_HELP = 0x100,
8503 ARG_HALT,
8504 ARG_REBOOT,
8505 ARG_NO_WALL
8506 };
8507
8508 static const struct option options[] = {
8509 { "help", no_argument, NULL, ARG_HELP },
8510 { "halt", no_argument, NULL, ARG_HALT },
8511 { "poweroff", no_argument, NULL, 'p' },
8512 { "reboot", no_argument, NULL, ARG_REBOOT },
8513 { "force", no_argument, NULL, 'f' },
8514 { "wtmp-only", no_argument, NULL, 'w' },
8515 { "no-wtmp", no_argument, NULL, 'd' },
8516 { "no-sync", no_argument, NULL, 'n' },
8517 { "no-wall", no_argument, NULL, ARG_NO_WALL },
8518 {}
8519 };
8520
8521 int c, r, runlevel;
8522
8523 assert(argc >= 0);
8524 assert(argv);
8525
8526 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
8527 if (IN_SET(runlevel, '0', '6'))
8528 arg_force = 2;
8529
8530 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0)
8531 switch (c) {
8532
8533 case ARG_HELP:
8534 return halt_help();
8535
8536 case ARG_HALT:
8537 arg_action = ACTION_HALT;
8538 break;
8539
8540 case 'p':
8541 if (arg_action != ACTION_REBOOT)
8542 arg_action = ACTION_POWEROFF;
8543 break;
8544
8545 case ARG_REBOOT:
8546 arg_action = ACTION_REBOOT;
8547 break;
8548
8549 case 'f':
8550 arg_force = 2;
8551 break;
8552
8553 case 'w':
8554 arg_dry_run = true;
8555 break;
8556
8557 case 'd':
8558 arg_no_wtmp = true;
8559 break;
8560
8561 case 'n':
8562 arg_no_sync = true;
8563 break;
8564
8565 case ARG_NO_WALL:
8566 arg_no_wall = true;
8567 break;
8568
8569 case 'i':
8570 case 'h':
8571 /* Compatibility nops */
8572 break;
8573
8574 case '?':
8575 return -EINVAL;
8576
8577 default:
8578 assert_not_reached("Unhandled option");
8579 }
8580
8581 if (arg_action == ACTION_REBOOT && (argc == optind || argc == optind + 1)) {
8582 r = update_reboot_parameter_and_warn(argc == optind + 1 ? argv[optind] : NULL, false);
8583 if (r < 0)
8584 return r;
8585 } else if (optind < argc)
8586 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8587 "Too many arguments.");
8588
8589 return 1;
8590 }
8591
8592 static int shutdown_parse_argv(int argc, char *argv[]) {
8593 enum {
8594 ARG_HELP = 0x100,
8595 ARG_NO_WALL
8596 };
8597
8598 static const struct option options[] = {
8599 { "help", no_argument, NULL, ARG_HELP },
8600 { "halt", no_argument, NULL, 'H' },
8601 { "poweroff", no_argument, NULL, 'P' },
8602 { "reboot", no_argument, NULL, 'r' },
8603 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
8604 { "no-wall", no_argument, NULL, ARG_NO_WALL },
8605 {}
8606 };
8607
8608 char **wall = NULL;
8609 int c, r;
8610
8611 assert(argc >= 0);
8612 assert(argv);
8613
8614 while ((c = getopt_long(argc, argv, "HPrhkKat:fFc", options, NULL)) >= 0)
8615 switch (c) {
8616
8617 case ARG_HELP:
8618 return shutdown_help();
8619
8620 case 'H':
8621 arg_action = ACTION_HALT;
8622 break;
8623
8624 case 'P':
8625 arg_action = ACTION_POWEROFF;
8626 break;
8627
8628 case 'r':
8629 if (kexec_loaded())
8630 arg_action = ACTION_KEXEC;
8631 else
8632 arg_action = ACTION_REBOOT;
8633 break;
8634
8635 case 'K':
8636 arg_action = ACTION_KEXEC;
8637 break;
8638
8639 case 'h':
8640 if (arg_action != ACTION_HALT)
8641 arg_action = ACTION_POWEROFF;
8642 break;
8643
8644 case 'k':
8645 arg_dry_run = true;
8646 break;
8647
8648 case ARG_NO_WALL:
8649 arg_no_wall = true;
8650 break;
8651
8652 case 'a':
8653 case 't': /* Note that we also ignore any passed argument to -t, not just the -t itself */
8654 case 'f':
8655 case 'F':
8656 /* Compatibility nops */
8657 break;
8658
8659 case 'c':
8660 arg_action = ACTION_CANCEL_SHUTDOWN;
8661 break;
8662
8663 case '?':
8664 return -EINVAL;
8665
8666 default:
8667 assert_not_reached("Unhandled option");
8668 }
8669
8670 if (argc > optind && arg_action != ACTION_CANCEL_SHUTDOWN) {
8671 r = parse_shutdown_time_spec(argv[optind], &arg_when);
8672 if (r < 0) {
8673 log_error("Failed to parse time specification: %s", argv[optind]);
8674 return r;
8675 }
8676 } else
8677 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
8678
8679 if (argc > optind && arg_action == ACTION_CANCEL_SHUTDOWN)
8680 /* No time argument for shutdown cancel */
8681 wall = argv + optind;
8682 else if (argc > optind + 1)
8683 /* We skip the time argument */
8684 wall = argv + optind + 1;
8685
8686 if (wall) {
8687 arg_wall = strv_copy(wall);
8688 if (!arg_wall)
8689 return log_oom();
8690 }
8691
8692 optind = argc;
8693
8694 return 1;
8695 }
8696
8697 static int telinit_parse_argv(int argc, char *argv[]) {
8698 enum {
8699 ARG_HELP = 0x100,
8700 ARG_NO_WALL
8701 };
8702
8703 static const struct option options[] = {
8704 { "help", no_argument, NULL, ARG_HELP },
8705 { "no-wall", no_argument, NULL, ARG_NO_WALL },
8706 {}
8707 };
8708
8709 static const struct {
8710 char from;
8711 enum action to;
8712 } table[] = {
8713 { '0', ACTION_POWEROFF },
8714 { '6', ACTION_REBOOT },
8715 { '1', ACTION_RESCUE },
8716 { '2', ACTION_RUNLEVEL2 },
8717 { '3', ACTION_RUNLEVEL3 },
8718 { '4', ACTION_RUNLEVEL4 },
8719 { '5', ACTION_RUNLEVEL5 },
8720 { 's', ACTION_RESCUE },
8721 { 'S', ACTION_RESCUE },
8722 { 'q', ACTION_RELOAD },
8723 { 'Q', ACTION_RELOAD },
8724 { 'u', ACTION_REEXEC },
8725 { 'U', ACTION_REEXEC }
8726 };
8727
8728 unsigned i;
8729 int c;
8730
8731 assert(argc >= 0);
8732 assert(argv);
8733
8734 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0)
8735 switch (c) {
8736
8737 case ARG_HELP:
8738 return telinit_help();
8739
8740 case ARG_NO_WALL:
8741 arg_no_wall = true;
8742 break;
8743
8744 case '?':
8745 return -EINVAL;
8746
8747 default:
8748 assert_not_reached("Unhandled option");
8749 }
8750
8751 if (optind >= argc)
8752 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8753 "%s: required argument missing.",
8754 program_invocation_short_name);
8755
8756 if (optind + 1 < argc)
8757 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8758 "Too many arguments.");
8759
8760 if (strlen(argv[optind]) != 1)
8761 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8762 "Expected single character argument.");
8763
8764 for (i = 0; i < ELEMENTSOF(table); i++)
8765 if (table[i].from == argv[optind][0])
8766 break;
8767
8768 if (i >= ELEMENTSOF(table))
8769 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8770 "Unknown command '%s'.", argv[optind]);
8771
8772 arg_action = table[i].to;
8773
8774 optind++;
8775
8776 return 1;
8777 }
8778
8779 static int runlevel_parse_argv(int argc, char *argv[]) {
8780 enum {
8781 ARG_HELP = 0x100,
8782 };
8783
8784 static const struct option options[] = {
8785 { "help", no_argument, NULL, ARG_HELP },
8786 {}
8787 };
8788
8789 int c;
8790
8791 assert(argc >= 0);
8792 assert(argv);
8793
8794 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0)
8795 switch (c) {
8796
8797 case ARG_HELP:
8798 return runlevel_help();
8799
8800 case '?':
8801 return -EINVAL;
8802
8803 default:
8804 assert_not_reached("Unhandled option");
8805 }
8806
8807 if (optind < argc)
8808 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8809 "Too many arguments.");
8810
8811 return 1;
8812 }
8813
8814 static int parse_argv(int argc, char *argv[]) {
8815 assert(argc >= 0);
8816 assert(argv);
8817
8818 if (program_invocation_short_name) {
8819
8820 if (strstr(program_invocation_short_name, "halt")) {
8821 arg_action = ACTION_HALT;
8822 return halt_parse_argv(argc, argv);
8823
8824 } else if (strstr(program_invocation_short_name, "poweroff")) {
8825 arg_action = ACTION_POWEROFF;
8826 return halt_parse_argv(argc, argv);
8827
8828 } else if (strstr(program_invocation_short_name, "reboot")) {
8829 if (kexec_loaded())
8830 arg_action = ACTION_KEXEC;
8831 else
8832 arg_action = ACTION_REBOOT;
8833 return halt_parse_argv(argc, argv);
8834
8835 } else if (strstr(program_invocation_short_name, "shutdown")) {
8836 arg_action = ACTION_POWEROFF;
8837 return shutdown_parse_argv(argc, argv);
8838
8839 } else if (strstr(program_invocation_short_name, "init")) {
8840
8841 /* Matches invocations as "init" as well as "telinit", which are synonymous when run as PID !=
8842 * 1 on SysV.
8843 *
8844 * On SysV "telinit" was the official command to communicate with PID 1, but "init" would
8845 * redirect itself to "telinit" if called with PID != 1. We follow the same logic here still,
8846 * though we add one level of indirection, as we implement "telinit" in "systemctl". Hence, for
8847 * us if you invoke "init" you get "systemd", but it will execve() "systemctl" immediately with
8848 * argv[] unmodified if PID is != 1. If you invoke "telinit" you directly get "systemctl". In
8849 * both cases we shall do the same thing, which is why we do strstr(p_i_s_n, "init") here, as a
8850 * quick way to match both.
8851 *
8852 * Also see redirect_telinit() in src/core/main.c. */
8853
8854 if (sd_booted() > 0) {
8855 arg_action = _ACTION_INVALID;
8856 return telinit_parse_argv(argc, argv);
8857 } else {
8858 /* Hmm, so some other init system is running, we need to forward this request to
8859 * it. For now we simply guess that it is Upstart. */
8860
8861 (void) rlimit_nofile_safe();
8862 execv(TELINIT, argv);
8863
8864 return log_error_errno(SYNTHETIC_ERRNO(EIO),
8865 "Couldn't find an alternative telinit implementation to spawn.");
8866 }
8867
8868 } else if (strstr(program_invocation_short_name, "runlevel")) {
8869 arg_action = ACTION_RUNLEVEL;
8870 return runlevel_parse_argv(argc, argv);
8871 }
8872 }
8873
8874 arg_action = ACTION_SYSTEMCTL;
8875 return systemctl_parse_argv(argc, argv);
8876 }
8877
8878 #if HAVE_SYSV_COMPAT
8879 _pure_ static int action_to_runlevel(void) {
8880 static const char table[_ACTION_MAX] = {
8881 [ACTION_HALT] = '0',
8882 [ACTION_POWEROFF] = '0',
8883 [ACTION_REBOOT] = '6',
8884 [ACTION_RUNLEVEL2] = '2',
8885 [ACTION_RUNLEVEL3] = '3',
8886 [ACTION_RUNLEVEL4] = '4',
8887 [ACTION_RUNLEVEL5] = '5',
8888 [ACTION_RESCUE] = '1'
8889 };
8890
8891 assert(arg_action >= 0 && arg_action < _ACTION_MAX);
8892 return table[arg_action];
8893 }
8894 #endif
8895
8896 static int systemctl_main(int argc, char *argv[]) {
8897 static const Verb verbs[] = {
8898 { "list-units", VERB_ANY, VERB_ANY, VERB_DEFAULT|VERB_ONLINE_ONLY, list_units },
8899 { "list-unit-files", VERB_ANY, VERB_ANY, 0, list_unit_files },
8900 { "list-sockets", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, list_sockets },
8901 { "list-timers", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, list_timers },
8902 { "list-jobs", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, list_jobs },
8903 { "list-machines", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, list_machines },
8904 { "clear-jobs", VERB_ANY, 1, VERB_ONLINE_ONLY, trivial_method },
8905 { "cancel", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, cancel_job },
8906 { "start", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8907 { "stop", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8908 { "condstop", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with ALTLinux */
8909 { "reload", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8910 { "restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8911 { "try-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8912 { "reload-or-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8913 { "reload-or-try-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with old systemctl <= 228 */
8914 { "try-reload-or-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8915 { "force-reload", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with SysV */
8916 { "condreload", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with ALTLinux */
8917 { "condrestart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with RH */
8918 { "isolate", 2, 2, VERB_ONLINE_ONLY, start_unit },
8919 { "kill", 2, VERB_ANY, VERB_ONLINE_ONLY, kill_unit },
8920 { "clean", 2, VERB_ANY, VERB_ONLINE_ONLY, clean_or_freeze_unit },
8921 { "freeze", 2, VERB_ANY, VERB_ONLINE_ONLY, clean_or_freeze_unit },
8922 { "thaw", 2, VERB_ANY, VERB_ONLINE_ONLY, clean_or_freeze_unit },
8923 { "is-active", 2, VERB_ANY, VERB_ONLINE_ONLY, check_unit_active },
8924 { "check", 2, VERB_ANY, VERB_ONLINE_ONLY, check_unit_active }, /* deprecated alias of is-active */
8925 { "is-failed", 2, VERB_ANY, VERB_ONLINE_ONLY, check_unit_failed },
8926 { "show", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, show },
8927 { "cat", 2, VERB_ANY, VERB_ONLINE_ONLY, cat },
8928 { "status", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, show },
8929 { "help", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, show },
8930 { "daemon-reload", VERB_ANY, 1, VERB_ONLINE_ONLY, daemon_reload },
8931 { "daemon-reexec", VERB_ANY, 1, VERB_ONLINE_ONLY, daemon_reload },
8932 { "log-level", VERB_ANY, 2, VERB_ONLINE_ONLY, log_level },
8933 { "log-target", VERB_ANY, 2, VERB_ONLINE_ONLY, log_target },
8934 { "service-watchdogs", VERB_ANY, 2, VERB_ONLINE_ONLY, service_watchdogs },
8935 { "show-environment", VERB_ANY, 1, VERB_ONLINE_ONLY, show_environment },
8936 { "set-environment", 2, VERB_ANY, VERB_ONLINE_ONLY, set_environment },
8937 { "unset-environment", 2, VERB_ANY, VERB_ONLINE_ONLY, set_environment },
8938 { "import-environment", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, import_environment },
8939 { "halt", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8940 { "poweroff", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8941 { "reboot", VERB_ANY, 2, VERB_ONLINE_ONLY, start_system_special },
8942 { "kexec", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8943 { "suspend", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8944 { "hibernate", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8945 { "hybrid-sleep", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8946 { "suspend-then-hibernate",VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8947 { "default", VERB_ANY, 1, VERB_ONLINE_ONLY, start_special },
8948 { "rescue", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8949 { "emergency", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8950 { "exit", VERB_ANY, 2, VERB_ONLINE_ONLY, start_special },
8951 { "reset-failed", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, reset_failed },
8952 { "enable", 2, VERB_ANY, 0, enable_unit },
8953 { "disable", 2, VERB_ANY, 0, enable_unit },
8954 { "is-enabled", 2, VERB_ANY, 0, unit_is_enabled },
8955 { "reenable", 2, VERB_ANY, 0, enable_unit },
8956 { "preset", 2, VERB_ANY, 0, enable_unit },
8957 { "preset-all", VERB_ANY, 1, 0, preset_all },
8958 { "mask", 2, VERB_ANY, 0, enable_unit },
8959 { "unmask", 2, VERB_ANY, 0, enable_unit },
8960 { "link", 2, VERB_ANY, 0, enable_unit },
8961 { "revert", 2, VERB_ANY, 0, enable_unit },
8962 { "switch-root", 2, VERB_ANY, VERB_ONLINE_ONLY, switch_root },
8963 { "list-dependencies", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, list_dependencies },
8964 { "set-default", 2, 2, 0, set_default },
8965 { "get-default", VERB_ANY, 1, 0, get_default },
8966 { "set-property", 3, VERB_ANY, VERB_ONLINE_ONLY, set_property },
8967 { "is-system-running", VERB_ANY, 1, 0, is_system_running },
8968 { "add-wants", 3, VERB_ANY, 0, add_dependency },
8969 { "add-requires", 3, VERB_ANY, 0, add_dependency },
8970 { "edit", 2, VERB_ANY, VERB_ONLINE_ONLY, edit },
8971 {}
8972 };
8973
8974 const Verb *verb = verbs_find_verb(argv[optind], verbs);
8975 if (verb && (verb->flags & VERB_ONLINE_ONLY) && arg_root)
8976 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8977 "Verb '%s' cannot be used with --root=.",
8978 argv[optind] ?: verb->verb);
8979
8980 return dispatch_verb(argc, argv, verbs, NULL);
8981 }
8982
8983 static int reload_with_fallback(void) {
8984 /* First, try systemd via D-Bus. */
8985 if (daemon_reload(0, NULL, NULL) >= 0)
8986 return 0;
8987
8988 /* Nothing else worked, so let's try signals */
8989 assert(IN_SET(arg_action, ACTION_RELOAD, ACTION_REEXEC));
8990
8991 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0)
8992 return log_error_errno(errno, "kill() failed: %m");
8993
8994 return 0;
8995 }
8996
8997 static int start_with_fallback(void) {
8998 /* First, try systemd via D-Bus. */
8999 if (start_unit(0, NULL, NULL) == 0)
9000 return 0;
9001
9002 #if HAVE_SYSV_COMPAT
9003 /* Nothing else worked, so let's try /dev/initctl */
9004 if (talk_initctl(action_to_runlevel()) > 0)
9005 return 0;
9006 #endif
9007
9008 return log_error_errno(SYNTHETIC_ERRNO(EIO),
9009 "Failed to talk to init daemon.");
9010 }
9011
9012 static int halt_now(enum action a) {
9013 /* The kernel will automatically flush ATA disks and suchlike on reboot(), but the file systems need to be
9014 * synced explicitly in advance. */
9015 if (!arg_no_sync && !arg_dry_run)
9016 (void) sync();
9017
9018 /* Make sure C-A-D is handled by the kernel from this point on... */
9019 if (!arg_dry_run)
9020 (void) reboot(RB_ENABLE_CAD);
9021
9022 switch (a) {
9023
9024 case ACTION_HALT:
9025 if (!arg_quiet)
9026 log_info("Halting.");
9027 if (arg_dry_run)
9028 return 0;
9029 (void) reboot(RB_HALT_SYSTEM);
9030 return -errno;
9031
9032 case ACTION_POWEROFF:
9033 if (!arg_quiet)
9034 log_info("Powering off.");
9035 if (arg_dry_run)
9036 return 0;
9037 (void) reboot(RB_POWER_OFF);
9038 return -errno;
9039
9040 case ACTION_KEXEC:
9041 case ACTION_REBOOT:
9042 return reboot_with_parameter(REBOOT_FALLBACK |
9043 (arg_quiet ? 0 : REBOOT_LOG) |
9044 (arg_dry_run ? REBOOT_DRY_RUN : 0));
9045
9046 default:
9047 assert_not_reached("Unknown action.");
9048 }
9049 }
9050
9051 static int logind_schedule_shutdown(void) {
9052
9053 #if ENABLE_LOGIND
9054 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
9055 char date[FORMAT_TIMESTAMP_MAX];
9056 const char *action;
9057 sd_bus *bus;
9058 int r;
9059
9060 r = acquire_bus(BUS_FULL, &bus);
9061 if (r < 0)
9062 return r;
9063
9064 switch (arg_action) {
9065 case ACTION_HALT:
9066 action = "halt";
9067 break;
9068 case ACTION_POWEROFF:
9069 action = "poweroff";
9070 break;
9071 case ACTION_KEXEC:
9072 action = "kexec";
9073 break;
9074 case ACTION_EXIT:
9075 action = "exit";
9076 break;
9077 case ACTION_REBOOT:
9078 default:
9079 action = "reboot";
9080 break;
9081 }
9082
9083 if (arg_dry_run)
9084 action = strjoina("dry-", action);
9085
9086 (void) logind_set_wall_message();
9087
9088 r = bus_call_method(bus, bus_login_mgr, "ScheduleShutdown", &error, NULL, "st", action, arg_when);
9089 if (r < 0)
9090 return log_warning_errno(r, "Failed to call ScheduleShutdown in logind, proceeding with immediate shutdown: %s", bus_error_message(&error, r));
9091
9092 if (!arg_quiet)
9093 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.", format_timestamp(date, sizeof(date), arg_when));
9094 return 0;
9095 #else
9096 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS),
9097 "Cannot schedule shutdown without logind support, proceeding with immediate shutdown.");
9098 #endif
9099 }
9100
9101 static int halt_main(void) {
9102 int r;
9103
9104 r = logind_check_inhibitors(arg_action);
9105 if (r < 0)
9106 return r;
9107
9108 /* Delayed shutdown requested, and was successful */
9109 if (arg_when > 0 && logind_schedule_shutdown() == 0)
9110 return 0;
9111 /* no delay, or logind failed or is not at all available */
9112
9113 if (geteuid() != 0) {
9114 if (arg_dry_run || arg_force > 0) {
9115 (void) must_be_root();
9116 return -EPERM;
9117 }
9118
9119 /* Try logind if we are a normal user and no special
9120 * mode applies. Maybe polkit allows us to shutdown
9121 * the machine. */
9122 if (IN_SET(arg_action, ACTION_POWEROFF, ACTION_REBOOT, ACTION_HALT)) {
9123 r = logind_reboot(arg_action);
9124 if (r >= 0)
9125 return r;
9126 if (IN_SET(r, -EOPNOTSUPP, -EINPROGRESS))
9127 /* requested operation is not
9128 * supported on the local system or
9129 * already in progress */
9130 return r;
9131 /* on all other errors, try low-level operation */
9132 }
9133 }
9134
9135 /* In order to minimize the difference between operation with and
9136 * without logind, we explicitly enable non-blocking mode for this,
9137 * as logind's shutdown operations are always non-blocking. */
9138 arg_no_block = true;
9139
9140 if (!arg_dry_run && !arg_force)
9141 return start_with_fallback();
9142
9143 assert(geteuid() == 0);
9144
9145 if (!arg_no_wtmp) {
9146 if (sd_booted() > 0)
9147 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
9148 else {
9149 r = utmp_put_shutdown();
9150 if (r < 0)
9151 log_warning_errno(r, "Failed to write utmp record: %m");
9152 }
9153 }
9154
9155 if (arg_dry_run)
9156 return 0;
9157
9158 r = halt_now(arg_action);
9159 return log_error_errno(r, "Failed to reboot: %m");
9160 }
9161
9162 static int runlevel_main(void) {
9163 int r, runlevel, previous;
9164
9165 r = utmp_get_runlevel(&runlevel, &previous);
9166 if (r < 0) {
9167 puts("unknown");
9168 return r;
9169 }
9170
9171 printf("%c %c\n",
9172 previous <= 0 ? 'N' : previous,
9173 runlevel <= 0 ? 'N' : runlevel);
9174
9175 return 0;
9176 }
9177
9178 static int logind_cancel_shutdown(void) {
9179 #if ENABLE_LOGIND
9180 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
9181 sd_bus *bus;
9182 int r;
9183
9184 r = acquire_bus(BUS_FULL, &bus);
9185 if (r < 0)
9186 return r;
9187
9188 (void) logind_set_wall_message();
9189
9190 r = bus_call_method(bus, bus_login_mgr, "CancelScheduledShutdown", &error, NULL, NULL);
9191 if (r < 0)
9192 return log_warning_errno(r, "Failed to talk to logind, shutdown hasn't been cancelled: %s", bus_error_message(&error, r));
9193
9194 return 0;
9195 #else
9196 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS),
9197 "Not compiled with logind support, cannot cancel scheduled shutdowns.");
9198 #endif
9199 }
9200
9201 static int run(int argc, char *argv[]) {
9202 int r;
9203
9204 setlocale(LC_ALL, "");
9205 log_parse_environment();
9206 log_open();
9207
9208 /* The journal merging logic potentially needs a lot of fds. */
9209 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE);
9210
9211 sigbus_install();
9212
9213 /* Explicitly not on_tty() to avoid setting cached value.
9214 * This becomes relevant for piping output which might be
9215 * ellipsized. */
9216 original_stdout_is_tty = isatty(STDOUT_FILENO);
9217
9218 r = parse_argv(argc, argv);
9219 if (r <= 0)
9220 goto finish;
9221
9222 if (arg_action != ACTION_SYSTEMCTL && running_in_chroot() > 0) {
9223 if (!arg_quiet)
9224 log_info("Running in chroot, ignoring request.");
9225 r = 0;
9226 goto finish;
9227 }
9228
9229 /* systemctl_main() will print an error message for the bus
9230 * connection, but only if it needs to */
9231
9232 switch (arg_action) {
9233
9234 case ACTION_SYSTEMCTL:
9235 r = systemctl_main(argc, argv);
9236 break;
9237
9238 /* Legacy command aliases set arg_action. They provide some fallbacks,
9239 * e.g. to tell sysvinit to reboot after you have installed systemd
9240 * binaries. */
9241
9242 case ACTION_HALT:
9243 case ACTION_POWEROFF:
9244 case ACTION_REBOOT:
9245 case ACTION_KEXEC:
9246 r = halt_main();
9247 break;
9248
9249 case ACTION_RUNLEVEL2:
9250 case ACTION_RUNLEVEL3:
9251 case ACTION_RUNLEVEL4:
9252 case ACTION_RUNLEVEL5:
9253 case ACTION_RESCUE:
9254 r = start_with_fallback();
9255 break;
9256
9257 case ACTION_RELOAD:
9258 case ACTION_REEXEC:
9259 r = reload_with_fallback();
9260 break;
9261
9262 case ACTION_CANCEL_SHUTDOWN:
9263 r = logind_cancel_shutdown();
9264 break;
9265
9266 case ACTION_RUNLEVEL:
9267 r = runlevel_main();
9268 break;
9269
9270 case ACTION_EXIT:
9271 case ACTION_SUSPEND:
9272 case ACTION_HIBERNATE:
9273 case ACTION_HYBRID_SLEEP:
9274 case ACTION_SUSPEND_THEN_HIBERNATE:
9275 case ACTION_EMERGENCY:
9276 case ACTION_DEFAULT:
9277 /* systemctl verbs with no equivalent in the legacy commands.
9278 * These cannot appear in arg_action. Fall through. */
9279
9280 case _ACTION_INVALID:
9281 default:
9282 assert_not_reached("Unknown action");
9283 }
9284
9285 finish:
9286 release_busses();
9287
9288 /* Note that we return r here, not 0, so that we can implement the LSB-like return codes */
9289 return r;
9290 }
9291
9292 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);