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