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