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