]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/systemctl/systemctl.c
systemctl: rework --wait logic
[thirdparty/systemd.git] / src / systemctl / systemctl.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 Copyright © 2013 Marc-Antoine Perennou
4 ***/
5
6 #include <errno.h>
7 #include <fcntl.h>
8 #include <getopt.h>
9 #include <locale.h>
10 #include <stdbool.h>
11 #include <stddef.h>
12 #include <stdio.h>
13 #include <string.h>
14 #include <sys/prctl.h>
15 #include <sys/reboot.h>
16 #include <sys/socket.h>
17 #include <unistd.h>
18
19 #include "sd-bus.h"
20 #include "sd-daemon.h"
21 #include "sd-event.h"
22 #include "sd-login.h"
23
24 #include "alloc-util.h"
25 #include "bootspec.h"
26 #include "bus-common-errors.h"
27 #include "bus-error.h"
28 #include "bus-message.h"
29 #include "bus-unit-util.h"
30 #include "bus-util.h"
31 #include "cgroup-show.h"
32 #include "cgroup-util.h"
33 #include "copy.h"
34 #include "dropin.h"
35 #include "efivars.h"
36 #include "env-util.h"
37 #include "escape.h"
38 #include "exit-status.h"
39 #include "fd-util.h"
40 #include "fileio.h"
41 #include "format-util.h"
42 #include "fs-util.h"
43 #include "glob-util.h"
44 #include "hexdecoct.h"
45 #include "hostname-util.h"
46 #include "initreq.h"
47 #include "install.h"
48 #include "io-util.h"
49 #include "list.h"
50 #include "locale-util.h"
51 #include "log.h"
52 #include "logs-show.h"
53 #include "macro.h"
54 #include "main-func.h"
55 #include "mkdir.h"
56 #include "pager.h"
57 #include "parse-util.h"
58 #include "path-lookup.h"
59 #include "path-util.h"
60 #include "pretty-print.h"
61 #include "proc-cmdline.h"
62 #include "process-util.h"
63 #include "reboot-util.h"
64 #include "rlimit-util.h"
65 #include "set.h"
66 #include "sigbus.h"
67 #include "signal-util.h"
68 #include "socket-util.h"
69 #include "spawn-ask-password-agent.h"
70 #include "spawn-polkit-agent.h"
71 #include "special.h"
72 #include "stat-util.h"
73 #include "string-table.h"
74 #include "strv.h"
75 #include "terminal-util.h"
76 #include "unit-def.h"
77 #include "unit-name.h"
78 #include "user-util.h"
79 #include "util.h"
80 #include "utmp-wtmp.h"
81 #include "verbs.h"
82 #include "virt.h"
83
84 /* The init script exit status codes
85 0 program is running or service is OK
86 1 program is dead and /var/run pid file exists
87 2 program is dead and /var/lock lock file exists
88 3 program is not running
89 4 program or service status is unknown
90 5-99 reserved for future LSB use
91 100-149 reserved for distribution use
92 150-199 reserved for application use
93 200-254 reserved
94 */
95 enum {
96 EXIT_PROGRAM_RUNNING_OR_SERVICE_OK = 0,
97 EXIT_PROGRAM_DEAD_AND_PID_EXISTS = 1,
98 EXIT_PROGRAM_DEAD_AND_LOCK_FILE_EXISTS = 2,
99 EXIT_PROGRAM_NOT_RUNNING = 3,
100 EXIT_PROGRAM_OR_SERVICES_STATUS_UNKNOWN = 4,
101 };
102
103 static char **arg_types = NULL;
104 static char **arg_states = NULL;
105 static char **arg_properties = NULL;
106 static bool arg_all = false;
107 static enum dependency {
108 DEPENDENCY_FORWARD,
109 DEPENDENCY_REVERSE,
110 DEPENDENCY_AFTER,
111 DEPENDENCY_BEFORE,
112 _DEPENDENCY_MAX
113 } arg_dependency = DEPENDENCY_FORWARD;
114 static const char *arg_job_mode = "replace";
115 static UnitFileScope arg_scope = UNIT_FILE_SYSTEM;
116 static bool arg_wait = false;
117 static bool arg_no_block = false;
118 static bool arg_no_legend = false;
119 static PagerFlags arg_pager_flags = 0;
120 static bool arg_no_wtmp = false;
121 static bool arg_no_sync = false;
122 static bool arg_no_wall = false;
123 static bool arg_no_reload = false;
124 static bool arg_value = false;
125 static bool arg_show_types = false;
126 static bool arg_ignore_inhibitors = false;
127 static bool arg_dry_run = false;
128 static bool arg_quiet = false;
129 static bool arg_full = false;
130 static bool arg_recursive = false;
131 static int arg_force = 0;
132 static bool arg_ask_password = false;
133 static bool arg_runtime = false;
134 static UnitFilePresetMode arg_preset_mode = UNIT_FILE_PRESET_FULL;
135 static char **arg_wall = NULL;
136 static const char *arg_kill_who = NULL;
137 static int arg_signal = SIGTERM;
138 static char *arg_root = NULL;
139 static usec_t arg_when = 0;
140 static char *arg_esp_path = NULL;
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(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) ? TREE_VERTICAL : 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 ? TREE_RIGHT : 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(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(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_strv_free_ char **names = NULL;
3097 int r, ret = EXIT_SUCCESS;
3098 sd_bus *bus;
3099 char **name;
3100
3101 if (arg_wait && !STR_IN_SET(argv[0], "start", "restart")) {
3102 log_error("--wait may only be used with the 'start' or 'restart' commands.");
3103 return -EINVAL;
3104 }
3105
3106 /* we cannot do sender tracking on the private bus, so we need the full
3107 * one for RefUnit to implement --wait */
3108 r = acquire_bus(arg_wait ? BUS_FULL : BUS_MANAGER, &bus);
3109 if (r < 0)
3110 return r;
3111
3112 ask_password_agent_open_if_enabled();
3113 polkit_agent_open_maybe();
3114
3115 if (arg_action == ACTION_SYSTEMCTL) {
3116 enum action action;
3117
3118 action = verb_to_action(argv[0]);
3119
3120 if (action != _ACTION_INVALID) {
3121 method = "StartUnit";
3122 mode = action_table[action].mode;
3123 one_name = action_table[action].target;
3124 } else {
3125 if (streq(argv[0], "isolate")) {
3126 method = "StartUnit";
3127 mode = "isolate";
3128
3129 suffix = ".target";
3130 } else {
3131 method = verb_to_method(argv[0]);
3132 mode = arg_job_mode;
3133 }
3134 one_name = NULL;
3135 }
3136 } else {
3137 assert(arg_action >= 0 && arg_action < _ACTION_MAX);
3138 assert(action_table[arg_action].target);
3139 assert(action_table[arg_action].mode);
3140
3141 method = "StartUnit";
3142 mode = action_table[arg_action].mode;
3143 one_name = action_table[arg_action].target;
3144 }
3145
3146 if (one_name) {
3147 names = strv_new(one_name);
3148 if (!names)
3149 return log_oom();
3150 } else {
3151 r = expand_names(bus, strv_skip(argv, 1), suffix, &names);
3152 if (r < 0)
3153 return log_error_errno(r, "Failed to expand names: %m");
3154 }
3155
3156 if (!arg_no_block) {
3157 r = bus_wait_for_jobs_new(bus, &w);
3158 if (r < 0)
3159 return log_error_errno(r, "Could not watch jobs: %m");
3160 }
3161
3162 if (arg_wait) {
3163 wait_context.unit_paths = set_new(&string_hash_ops);
3164 if (!wait_context.unit_paths)
3165 return log_oom();
3166
3167 r = sd_bus_call_method_async(
3168 bus,
3169 NULL,
3170 "org.freedesktop.systemd1",
3171 "/org/freedesktop/systemd1",
3172 "org.freedesktop.systemd1.Manager",
3173 "Subscribe",
3174 NULL, NULL,
3175 NULL);
3176 if (r < 0)
3177 return log_error_errno(r, "Failed to enable subscription: %m");
3178 r = sd_event_default(&wait_context.event);
3179 if (r < 0)
3180 return log_error_errno(r, "Failed to allocate event loop: %m");
3181 r = sd_bus_attach_event(bus, wait_context.event, 0);
3182 if (r < 0)
3183 return log_error_errno(r, "Failed to attach bus to event loop: %m");
3184 }
3185
3186 STRV_FOREACH(name, names) {
3187 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3188
3189 r = start_unit_one(bus, method, *name, mode, &error, w, arg_wait ? &wait_context : NULL);
3190 if (ret == EXIT_SUCCESS && r < 0)
3191 ret = translate_bus_error_to_exit_status(r, &error);
3192 }
3193
3194 if (!arg_no_block) {
3195 const char* extra_args[4] = {};
3196 int arg_count = 0;
3197
3198 if (arg_scope != UNIT_FILE_SYSTEM)
3199 extra_args[arg_count++] = "--user";
3200
3201 assert(IN_SET(arg_transport, BUS_TRANSPORT_LOCAL, BUS_TRANSPORT_REMOTE, BUS_TRANSPORT_MACHINE));
3202 if (arg_transport == BUS_TRANSPORT_REMOTE) {
3203 extra_args[arg_count++] = "-H";
3204 extra_args[arg_count++] = arg_host;
3205 } else if (arg_transport == BUS_TRANSPORT_MACHINE) {
3206 extra_args[arg_count++] = "-M";
3207 extra_args[arg_count++] = arg_host;
3208 }
3209
3210 r = bus_wait_for_jobs(w, arg_quiet, extra_args);
3211 if (r < 0)
3212 return r;
3213
3214 /* When stopping units, warn if they can still be triggered by
3215 * another active unit (socket, path, timer) */
3216 if (!arg_quiet && streq(method, "StopUnit"))
3217 STRV_FOREACH(name, names)
3218 (void) check_triggering_units(bus, *name);
3219 }
3220
3221 if (ret == EXIT_SUCCESS && arg_wait && !set_isempty(wait_context.unit_paths)) {
3222 r = sd_event_loop(wait_context.event);
3223 if (r < 0)
3224 return log_error_errno(r, "Failed to run event loop: %m");
3225 if (wait_context.any_failed)
3226 ret = EXIT_FAILURE;
3227 }
3228
3229 return ret;
3230 }
3231
3232 #if ENABLE_LOGIND
3233 static int logind_set_wall_message(void) {
3234 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3235 sd_bus *bus;
3236 _cleanup_free_ char *m = NULL;
3237 int r;
3238
3239 r = acquire_bus(BUS_FULL, &bus);
3240 if (r < 0)
3241 return r;
3242
3243 m = strv_join(arg_wall, " ");
3244 if (!m)
3245 return log_oom();
3246
3247 log_debug("%s wall message \"%s\".", arg_dry_run ? "Would set" : "Setting", m);
3248 if (arg_dry_run)
3249 return 0;
3250
3251 r = sd_bus_call_method(
3252 bus,
3253 "org.freedesktop.login1",
3254 "/org/freedesktop/login1",
3255 "org.freedesktop.login1.Manager",
3256 "SetWallMessage",
3257 &error,
3258 NULL,
3259 "sb",
3260 m,
3261 !arg_no_wall);
3262
3263 if (r < 0)
3264 return log_warning_errno(r, "Failed to set wall message, ignoring: %s", bus_error_message(&error, r));
3265 return 0;
3266 }
3267 #endif
3268
3269 /* Ask systemd-logind, which might grant access to unprivileged users
3270 * through polkit */
3271 static int logind_reboot(enum action a) {
3272 #if ENABLE_LOGIND
3273 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3274 const char *method, *description;
3275 sd_bus *bus;
3276 int r;
3277
3278 r = acquire_bus(BUS_FULL, &bus);
3279 if (r < 0)
3280 return r;
3281
3282 switch (a) {
3283
3284 case ACTION_POWEROFF:
3285 method = "PowerOff";
3286 description = "power off system";
3287 break;
3288
3289 case ACTION_REBOOT:
3290 method = "Reboot";
3291 description = "reboot system";
3292 break;
3293
3294 case ACTION_HALT:
3295 method = "Halt";
3296 description = "halt system";
3297 break;
3298
3299 case ACTION_SUSPEND:
3300 method = "Suspend";
3301 description = "suspend system";
3302 break;
3303
3304 case ACTION_HIBERNATE:
3305 method = "Hibernate";
3306 description = "hibernate system";
3307 break;
3308
3309 case ACTION_HYBRID_SLEEP:
3310 method = "HybridSleep";
3311 description = "put system into hybrid sleep";
3312 break;
3313
3314 case ACTION_SUSPEND_THEN_HIBERNATE:
3315 method = "SuspendThenHibernate";
3316 description = "put system into suspend followed by hibernate";
3317 break;
3318
3319 default:
3320 return -EINVAL;
3321 }
3322
3323 polkit_agent_open_maybe();
3324 (void) logind_set_wall_message();
3325
3326 log_debug("%s org.freedesktop.login1.Manager %s dbus call.", arg_dry_run ? "Would execute" : "Executing", method);
3327 if (arg_dry_run)
3328 return 0;
3329
3330 r = sd_bus_call_method(
3331 bus,
3332 "org.freedesktop.login1",
3333 "/org/freedesktop/login1",
3334 "org.freedesktop.login1.Manager",
3335 method,
3336 &error,
3337 NULL,
3338 "b", arg_ask_password);
3339 if (r < 0)
3340 return log_error_errno(r, "Failed to %s via logind: %s", description, bus_error_message(&error, r));
3341
3342 return 0;
3343 #else
3344 return -ENOSYS;
3345 #endif
3346 }
3347
3348 static int logind_check_inhibitors(enum action a) {
3349 #if ENABLE_LOGIND
3350 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
3351 _cleanup_strv_free_ char **sessions = NULL;
3352 const char *what, *who, *why, *mode;
3353 uint32_t uid, pid;
3354 sd_bus *bus;
3355 unsigned c = 0;
3356 char **s;
3357 int r;
3358
3359 if (arg_ignore_inhibitors || arg_force > 0)
3360 return 0;
3361
3362 if (arg_when > 0)
3363 return 0;
3364
3365 if (geteuid() == 0)
3366 return 0;
3367
3368 if (!on_tty())
3369 return 0;
3370
3371 if (arg_transport != BUS_TRANSPORT_LOCAL)
3372 return 0;
3373
3374 r = acquire_bus(BUS_FULL, &bus);
3375 if (r < 0)
3376 return r;
3377
3378 r = sd_bus_call_method(
3379 bus,
3380 "org.freedesktop.login1",
3381 "/org/freedesktop/login1",
3382 "org.freedesktop.login1.Manager",
3383 "ListInhibitors",
3384 NULL,
3385 &reply,
3386 NULL);
3387 if (r < 0)
3388 /* If logind is not around, then there are no inhibitors... */
3389 return 0;
3390
3391 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssuu)");
3392 if (r < 0)
3393 return bus_log_parse_error(r);
3394
3395 while ((r = sd_bus_message_read(reply, "(ssssuu)", &what, &who, &why, &mode, &uid, &pid)) > 0) {
3396 _cleanup_free_ char *comm = NULL, *user = NULL;
3397 _cleanup_strv_free_ char **sv = NULL;
3398
3399 if (!streq(mode, "block"))
3400 continue;
3401
3402 sv = strv_split(what, ":");
3403 if (!sv)
3404 return log_oom();
3405
3406 if (!pid_is_valid((pid_t) pid)) {
3407 log_error("Invalid PID "PID_FMT".", (pid_t) pid);
3408 return -ERANGE;
3409 }
3410
3411 if (!strv_contains(sv,
3412 IN_SET(a,
3413 ACTION_HALT,
3414 ACTION_POWEROFF,
3415 ACTION_REBOOT,
3416 ACTION_KEXEC) ? "shutdown" : "sleep"))
3417 continue;
3418
3419 get_process_comm(pid, &comm);
3420 user = uid_to_name(uid);
3421
3422 log_warning("Operation inhibited by \"%s\" (PID "PID_FMT" \"%s\", user %s), reason is \"%s\".",
3423 who, (pid_t) pid, strna(comm), strna(user), why);
3424
3425 c++;
3426 }
3427 if (r < 0)
3428 return bus_log_parse_error(r);
3429
3430 r = sd_bus_message_exit_container(reply);
3431 if (r < 0)
3432 return bus_log_parse_error(r);
3433
3434 /* Check for current sessions */
3435 sd_get_sessions(&sessions);
3436 STRV_FOREACH(s, sessions) {
3437 _cleanup_free_ char *type = NULL, *tty = NULL, *seat = NULL, *user = NULL, *service = NULL, *class = NULL;
3438
3439 if (sd_session_get_uid(*s, &uid) < 0 || uid == getuid())
3440 continue;
3441
3442 if (sd_session_get_class(*s, &class) < 0 || !streq(class, "user"))
3443 continue;
3444
3445 if (sd_session_get_type(*s, &type) < 0 || !STR_IN_SET(type, "x11", "wayland", "tty", "mir"))
3446 continue;
3447
3448 sd_session_get_tty(*s, &tty);
3449 sd_session_get_seat(*s, &seat);
3450 sd_session_get_service(*s, &service);
3451 user = uid_to_name(uid);
3452
3453 log_warning("User %s is logged in on %s.", strna(user), isempty(tty) ? (isempty(seat) ? strna(service) : seat) : tty);
3454 c++;
3455 }
3456
3457 if (c <= 0)
3458 return 0;
3459
3460 log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'systemctl %s -i'.",
3461 action_table[a].verb);
3462
3463 return -EPERM;
3464 #else
3465 return 0;
3466 #endif
3467 }
3468
3469 static int logind_prepare_firmware_setup(void) {
3470 #if ENABLE_LOGIND
3471 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3472 sd_bus *bus;
3473 int r;
3474
3475 r = acquire_bus(BUS_FULL, &bus);
3476 if (r < 0)
3477 return r;
3478
3479 r = sd_bus_call_method(
3480 bus,
3481 "org.freedesktop.login1",
3482 "/org/freedesktop/login1",
3483 "org.freedesktop.login1.Manager",
3484 "SetRebootToFirmwareSetup",
3485 &error,
3486 NULL,
3487 "b", true);
3488 if (r < 0)
3489 return log_error_errno(r, "Cannot indicate to EFI to boot into setup mode: %s", bus_error_message(&error, r));
3490
3491 return 0;
3492 #else
3493 log_error("Cannot remotely indicate to EFI to boot into setup mode.");
3494 return -ENOSYS;
3495 #endif
3496 }
3497
3498 static int prepare_firmware_setup(void) {
3499 int r;
3500
3501 if (!arg_firmware_setup)
3502 return 0;
3503
3504 if (arg_transport == BUS_TRANSPORT_LOCAL) {
3505
3506 r = efi_set_reboot_to_firmware(true);
3507 if (r < 0)
3508 log_debug_errno(r, "Cannot indicate to EFI to boot into setup mode, will retry via logind: %m");
3509 else
3510 return r;
3511 }
3512
3513 return logind_prepare_firmware_setup();
3514 }
3515
3516 static int load_kexec_kernel(void) {
3517 _cleanup_(boot_config_free) BootConfig config = {};
3518 _cleanup_free_ char *where = NULL, *kernel = NULL, *initrd = NULL, *options = NULL;
3519 const BootEntry *e;
3520 pid_t pid;
3521 int r;
3522
3523 if (kexec_loaded()) {
3524 log_debug("Kexec kernel already loaded.");
3525 return 0;
3526 }
3527
3528 if (access(KEXEC, X_OK) < 0)
3529 return log_error_errno(errno, KEXEC" is not available: %m");
3530
3531 r = find_default_boot_entry(arg_esp_path, &where, &config, &e);
3532 if (r == -ENOKEY) /* find_default_boot_entry() doesn't warn about this case */
3533 return log_error_errno(r, "Cannot find the ESP partition mount point.");
3534 if (r < 0)
3535 /* But it logs about all these cases, hence don't log here again */
3536 return r;
3537
3538 if (strv_length(e->initrd) > 1) {
3539 log_error("Boot entry specifies multiple initrds, which is not supported currently.");
3540 return -EINVAL;
3541 }
3542
3543 kernel = path_join(where, e->kernel);
3544 if (!strv_isempty(e->initrd))
3545 initrd = path_join(where, *e->initrd);
3546 options = strv_join(e->options, " ");
3547 if (!options)
3548 return log_oom();
3549
3550 log_full(arg_quiet ? LOG_DEBUG : LOG_INFO,
3551 "%s "KEXEC" --load \"%s\" --append \"%s\"%s%s%s",
3552 arg_dry_run ? "Would run" : "Running",
3553 kernel,
3554 options,
3555 initrd ? " --initrd \"" : NULL, strempty(initrd), initrd ? "\"" : "");
3556 if (arg_dry_run)
3557 return 0;
3558
3559 r = safe_fork("(kexec)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_LOG, &pid);
3560 if (r < 0)
3561 return r;
3562 if (r == 0) {
3563 const char* const args[] = {
3564 KEXEC,
3565 "--load", kernel,
3566 "--append", options,
3567 initrd ? "--initrd" : NULL, initrd,
3568 NULL };
3569
3570 /* Child */
3571 execv(args[0], (char * const *) args);
3572 _exit(EXIT_FAILURE);
3573 }
3574
3575 r = wait_for_terminate_and_check("kexec", pid, WAIT_LOG);
3576 if (r < 0)
3577 return r;
3578 if (r > 0)
3579 /* Command failed */
3580 return -EPROTO;
3581 return 0;
3582 }
3583
3584 static int set_exit_code(uint8_t code) {
3585 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3586 sd_bus *bus;
3587 int r;
3588
3589 r = acquire_bus(BUS_MANAGER, &bus);
3590 if (r < 0)
3591 return r;
3592
3593 r = sd_bus_call_method(
3594 bus,
3595 "org.freedesktop.systemd1",
3596 "/org/freedesktop/systemd1",
3597 "org.freedesktop.systemd1.Manager",
3598 "SetExitCode",
3599 &error,
3600 NULL,
3601 "y", code);
3602 if (r < 0)
3603 return log_error_errno(r, "Failed to set exit code: %s", bus_error_message(&error, r));
3604
3605 return 0;
3606 }
3607
3608 static int start_special(int argc, char *argv[], void *userdata) {
3609 enum action a;
3610 int r;
3611 bool termination_action; /* an action that terminates the manager,
3612 * can be performed also by signal. */
3613
3614 assert(argv);
3615
3616 a = verb_to_action(argv[0]);
3617
3618 r = logind_check_inhibitors(a);
3619 if (r < 0)
3620 return r;
3621
3622 if (arg_force >= 2) {
3623 r = must_be_root();
3624 if (r < 0)
3625 return r;
3626 }
3627
3628 r = prepare_firmware_setup();
3629 if (r < 0)
3630 return r;
3631
3632 if (a == ACTION_REBOOT && argc > 1) {
3633 r = update_reboot_parameter_and_warn(argv[1]);
3634 if (r < 0)
3635 return r;
3636
3637 } else if (a == ACTION_KEXEC) {
3638 r = load_kexec_kernel();
3639 if (r < 0 && arg_force >= 1)
3640 log_notice("Failed to load kexec kernel, continuing without.");
3641 else if (r < 0)
3642 return r;
3643
3644 } else if (a == ACTION_EXIT && argc > 1) {
3645 uint8_t code;
3646
3647 /* If the exit code is not given on the command line,
3648 * don't reset it to zero: just keep it as it might
3649 * have been set previously. */
3650
3651 r = safe_atou8(argv[1], &code);
3652 if (r < 0)
3653 return log_error_errno(r, "Invalid exit code.");
3654
3655 r = set_exit_code(code);
3656 if (r < 0)
3657 return r;
3658 }
3659
3660 termination_action = IN_SET(a,
3661 ACTION_HALT,
3662 ACTION_POWEROFF,
3663 ACTION_REBOOT);
3664 if (termination_action && arg_force >= 2)
3665 return halt_now(a);
3666
3667 if (arg_force >= 1 &&
3668 (termination_action || IN_SET(a, ACTION_KEXEC, ACTION_EXIT)))
3669 r = trivial_method(argc, argv, userdata);
3670 else {
3671 /* First try logind, to allow authentication with polkit */
3672 if (IN_SET(a,
3673 ACTION_POWEROFF,
3674 ACTION_REBOOT,
3675 ACTION_HALT,
3676 ACTION_SUSPEND,
3677 ACTION_HIBERNATE,
3678 ACTION_HYBRID_SLEEP,
3679 ACTION_SUSPEND_THEN_HIBERNATE)) {
3680
3681 r = logind_reboot(a);
3682 if (r >= 0)
3683 return r;
3684 if (IN_SET(r, -EOPNOTSUPP, -EINPROGRESS))
3685 /* requested operation is not supported or already in progress */
3686 return r;
3687
3688 /* On all other errors, try low-level operation. In order to minimize the difference between
3689 * operation with and without logind, we explicitly enable non-blocking mode for this, as
3690 * logind's shutdown operations are always non-blocking. */
3691
3692 arg_no_block = true;
3693
3694 } else if (IN_SET(a, ACTION_EXIT, ACTION_KEXEC))
3695 /* Since exit/kexec are so close in behaviour to power-off/reboot, let's also make them
3696 * asynchronous, in order to not confuse the user needlessly with unexpected behaviour. */
3697 arg_no_block = true;
3698
3699 r = start_unit(argc, argv, userdata);
3700 }
3701
3702 if (termination_action && arg_force < 2 &&
3703 IN_SET(r, -ENOENT, -ETIMEDOUT))
3704 log_notice("It is possible to perform action directly, see discussion of --force --force in man:systemctl(1).");
3705
3706 return r;
3707 }
3708
3709 static int start_system_special(int argc, char *argv[], void *userdata) {
3710 /* Like start_special above, but raises an error when running in user mode */
3711
3712 if (arg_scope != UNIT_FILE_SYSTEM)
3713 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3714 "Bad action for %s mode.",
3715 arg_scope == UNIT_FILE_GLOBAL ? "--global" : "--user");
3716
3717 return start_special(argc, argv, userdata);
3718 }
3719
3720 static int check_unit_generic(int code, const UnitActiveState good_states[], int nb_states, char **args) {
3721 _cleanup_strv_free_ char **names = NULL;
3722 UnitActiveState active_state;
3723 sd_bus *bus;
3724 char **name;
3725 int r, i;
3726 bool found = false;
3727
3728 r = acquire_bus(BUS_MANAGER, &bus);
3729 if (r < 0)
3730 return r;
3731
3732 r = expand_names(bus, args, NULL, &names);
3733 if (r < 0)
3734 return log_error_errno(r, "Failed to expand names: %m");
3735
3736 STRV_FOREACH(name, names) {
3737 r = get_state_one_unit(bus, *name, &active_state);
3738 if (r < 0)
3739 return r;
3740
3741 if (!arg_quiet)
3742 puts(unit_active_state_to_string(active_state));
3743
3744 for (i = 0; i < nb_states; ++i)
3745 if (good_states[i] == active_state)
3746 found = true;
3747 }
3748
3749 /* use the given return code for the case that we won't find
3750 * any unit which matches the list */
3751 return found ? 0 : code;
3752 }
3753
3754 static int check_unit_active(int argc, char *argv[], void *userdata) {
3755 static const UnitActiveState states[] = {
3756 UNIT_ACTIVE,
3757 UNIT_RELOADING,
3758 };
3759
3760 /* According to LSB: 3, "program is not running" */
3761 return check_unit_generic(EXIT_PROGRAM_NOT_RUNNING, states, ELEMENTSOF(states), strv_skip(argv, 1));
3762 }
3763
3764 static int check_unit_failed(int argc, char *argv[], void *userdata) {
3765 static const UnitActiveState states[] = {
3766 UNIT_FAILED,
3767 };
3768
3769 return check_unit_generic(EXIT_PROGRAM_DEAD_AND_PID_EXISTS, states, ELEMENTSOF(states), strv_skip(argv, 1));
3770 }
3771
3772 static int kill_unit(int argc, char *argv[], void *userdata) {
3773 _cleanup_strv_free_ char **names = NULL;
3774 char *kill_who = NULL, **name;
3775 sd_bus *bus;
3776 int r, q;
3777
3778 r = acquire_bus(BUS_MANAGER, &bus);
3779 if (r < 0)
3780 return r;
3781
3782 polkit_agent_open_maybe();
3783
3784 if (!arg_kill_who)
3785 arg_kill_who = "all";
3786
3787 /* --fail was specified */
3788 if (streq(arg_job_mode, "fail"))
3789 kill_who = strjoina(arg_kill_who, "-fail");
3790
3791 r = expand_names(bus, strv_skip(argv, 1), NULL, &names);
3792 if (r < 0)
3793 return log_error_errno(r, "Failed to expand names: %m");
3794
3795 STRV_FOREACH(name, names) {
3796 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3797
3798 q = sd_bus_call_method(
3799 bus,
3800 "org.freedesktop.systemd1",
3801 "/org/freedesktop/systemd1",
3802 "org.freedesktop.systemd1.Manager",
3803 "KillUnit",
3804 &error,
3805 NULL,
3806 "ssi", *name, kill_who ? kill_who : arg_kill_who, arg_signal);
3807 if (q < 0) {
3808 log_error_errno(q, "Failed to kill unit %s: %s", *name, bus_error_message(&error, q));
3809 if (r == 0)
3810 r = q;
3811 }
3812 }
3813
3814 return r;
3815 }
3816
3817 typedef struct ExecStatusInfo {
3818 char *name;
3819
3820 char *path;
3821 char **argv;
3822
3823 bool ignore;
3824
3825 usec_t start_timestamp;
3826 usec_t exit_timestamp;
3827 pid_t pid;
3828 int code;
3829 int status;
3830
3831 LIST_FIELDS(struct ExecStatusInfo, exec);
3832 } ExecStatusInfo;
3833
3834 static void exec_status_info_free(ExecStatusInfo *i) {
3835 assert(i);
3836
3837 free(i->name);
3838 free(i->path);
3839 strv_free(i->argv);
3840 free(i);
3841 }
3842
3843 static int exec_status_info_deserialize(sd_bus_message *m, ExecStatusInfo *i) {
3844 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
3845 const char *path;
3846 uint32_t pid;
3847 int32_t code, status;
3848 int ignore, r;
3849
3850 assert(m);
3851 assert(i);
3852
3853 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_STRUCT, "sasbttttuii");
3854 if (r < 0)
3855 return bus_log_parse_error(r);
3856 else if (r == 0)
3857 return 0;
3858
3859 r = sd_bus_message_read(m, "s", &path);
3860 if (r < 0)
3861 return bus_log_parse_error(r);
3862
3863 i->path = strdup(path);
3864 if (!i->path)
3865 return log_oom();
3866
3867 r = sd_bus_message_read_strv(m, &i->argv);
3868 if (r < 0)
3869 return bus_log_parse_error(r);
3870
3871 r = sd_bus_message_read(m,
3872 "bttttuii",
3873 &ignore,
3874 &start_timestamp, &start_timestamp_monotonic,
3875 &exit_timestamp, &exit_timestamp_monotonic,
3876 &pid,
3877 &code, &status);
3878 if (r < 0)
3879 return bus_log_parse_error(r);
3880
3881 i->ignore = ignore;
3882 i->start_timestamp = (usec_t) start_timestamp;
3883 i->exit_timestamp = (usec_t) exit_timestamp;
3884 i->pid = (pid_t) pid;
3885 i->code = code;
3886 i->status = status;
3887
3888 r = sd_bus_message_exit_container(m);
3889 if (r < 0)
3890 return bus_log_parse_error(r);
3891
3892 return 1;
3893 }
3894
3895 typedef struct UnitCondition {
3896 char *name;
3897 char *param;
3898 bool trigger;
3899 bool negate;
3900 int tristate;
3901
3902 LIST_FIELDS(struct UnitCondition, conditions);
3903 } UnitCondition;
3904
3905 static void unit_condition_free(UnitCondition *c) {
3906 if (!c)
3907 return;
3908
3909 free(c->name);
3910 free(c->param);
3911 free(c);
3912 }
3913
3914 DEFINE_TRIVIAL_CLEANUP_FUNC(UnitCondition*, unit_condition_free);
3915
3916 typedef struct UnitStatusInfo {
3917 const char *id;
3918 const char *load_state;
3919 const char *active_state;
3920 const char *sub_state;
3921 const char *unit_file_state;
3922 const char *unit_file_preset;
3923
3924 const char *description;
3925 const char *following;
3926
3927 char **documentation;
3928
3929 const char *fragment_path;
3930 const char *source_path;
3931 const char *control_group;
3932
3933 char **dropin_paths;
3934
3935 const char *load_error;
3936 const char *result;
3937
3938 usec_t inactive_exit_timestamp;
3939 usec_t inactive_exit_timestamp_monotonic;
3940 usec_t active_enter_timestamp;
3941 usec_t active_exit_timestamp;
3942 usec_t inactive_enter_timestamp;
3943
3944 bool need_daemon_reload;
3945 bool transient;
3946
3947 /* Service */
3948 pid_t main_pid;
3949 pid_t control_pid;
3950 const char *status_text;
3951 const char *pid_file;
3952 bool running:1;
3953 int status_errno;
3954
3955 usec_t start_timestamp;
3956 usec_t exit_timestamp;
3957
3958 int exit_code, exit_status;
3959
3960 usec_t condition_timestamp;
3961 bool condition_result;
3962 LIST_HEAD(UnitCondition, conditions);
3963
3964 usec_t assert_timestamp;
3965 bool assert_result;
3966 bool failed_assert_trigger;
3967 bool failed_assert_negate;
3968 const char *failed_assert;
3969 const char *failed_assert_parameter;
3970 usec_t next_elapse_real;
3971 usec_t next_elapse_monotonic;
3972
3973 /* Socket */
3974 unsigned n_accepted;
3975 unsigned n_connections;
3976 unsigned n_refused;
3977 bool accept;
3978
3979 /* Pairs of type, path */
3980 char **listen;
3981
3982 /* Device */
3983 const char *sysfs_path;
3984
3985 /* Mount, Automount */
3986 const char *where;
3987
3988 /* Swap */
3989 const char *what;
3990
3991 /* CGroup */
3992 uint64_t memory_current;
3993 uint64_t memory_min;
3994 uint64_t memory_low;
3995 uint64_t memory_high;
3996 uint64_t memory_max;
3997 uint64_t memory_swap_max;
3998 uint64_t memory_limit;
3999 uint64_t cpu_usage_nsec;
4000 uint64_t tasks_current;
4001 uint64_t tasks_max;
4002
4003 uint64_t ip_ingress_bytes;
4004 uint64_t ip_egress_bytes;
4005
4006 LIST_HEAD(ExecStatusInfo, exec);
4007 } UnitStatusInfo;
4008
4009 static void unit_status_info_free(UnitStatusInfo *info) {
4010 ExecStatusInfo *p;
4011 UnitCondition *c;
4012
4013 strv_free(info->documentation);
4014 strv_free(info->dropin_paths);
4015 strv_free(info->listen);
4016
4017 while ((c = info->conditions)) {
4018 LIST_REMOVE(conditions, info->conditions, c);
4019 unit_condition_free(c);
4020 }
4021
4022 while ((p = info->exec)) {
4023 LIST_REMOVE(exec, info->exec, p);
4024 exec_status_info_free(p);
4025 }
4026 }
4027
4028 static void print_status_info(
4029 sd_bus *bus,
4030 UnitStatusInfo *i,
4031 bool *ellipsized) {
4032
4033 char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], since2[FORMAT_TIMESTAMP_MAX];
4034 const char *s1, *s2, *active_on, *active_off, *on, *off, *ss;
4035 _cleanup_free_ char *formatted_path = NULL;
4036 ExecStatusInfo *p;
4037 usec_t timestamp;
4038 const char *path;
4039 char **t, **t2;
4040 int r;
4041
4042 assert(i);
4043
4044 /* This shows pretty information about a unit. See
4045 * print_property() for a low-level property printer */
4046
4047 if (streq_ptr(i->active_state, "failed")) {
4048 active_on = ansi_highlight_red();
4049 active_off = ansi_normal();
4050 } else if (STRPTR_IN_SET(i->active_state, "active", "reloading")) {
4051 active_on = ansi_highlight_green();
4052 active_off = ansi_normal();
4053 } else
4054 active_on = active_off = "";
4055
4056 printf("%s%s%s %s", active_on, special_glyph(BLACK_CIRCLE), active_off, strna(i->id));
4057
4058 if (i->description && !streq_ptr(i->id, i->description))
4059 printf(" - %s", i->description);
4060
4061 printf("\n");
4062
4063 if (i->following)
4064 printf(" Follow: unit currently follows state of %s\n", i->following);
4065
4066 if (STRPTR_IN_SET(i->load_state, "error", "not-found", "bad-setting")) {
4067 on = ansi_highlight_red();
4068 off = ansi_normal();
4069 } else
4070 on = off = "";
4071
4072 path = i->source_path ?: i->fragment_path;
4073 if (path && terminal_urlify_path(path, NULL, &formatted_path) >= 0)
4074 path = formatted_path;
4075
4076 if (!isempty(i->load_error))
4077 printf(" Loaded: %s%s%s (Reason: %s)\n",
4078 on, strna(i->load_state), off, i->load_error);
4079 else if (path && !isempty(i->unit_file_state) && !isempty(i->unit_file_preset) &&
4080 !STR_IN_SET(i->unit_file_state, "generated", "transient"))
4081 printf(" Loaded: %s%s%s (%s; %s; vendor preset: %s)\n",
4082 on, strna(i->load_state), off, path, i->unit_file_state, i->unit_file_preset);
4083 else if (path && !isempty(i->unit_file_state))
4084 printf(" Loaded: %s%s%s (%s; %s)\n",
4085 on, strna(i->load_state), off, path, i->unit_file_state);
4086 else if (path)
4087 printf(" Loaded: %s%s%s (%s)\n",
4088 on, strna(i->load_state), off, path);
4089 else
4090 printf(" Loaded: %s%s%s\n",
4091 on, strna(i->load_state), off);
4092
4093 if (i->transient)
4094 printf("Transient: yes\n");
4095
4096 if (!strv_isempty(i->dropin_paths)) {
4097 _cleanup_free_ char *dir = NULL;
4098 bool last = false;
4099 char ** dropin;
4100
4101 STRV_FOREACH(dropin, i->dropin_paths) {
4102 _cleanup_free_ char *dropin_formatted = NULL;
4103 const char *df;
4104
4105 if (!dir || last) {
4106 printf(dir ? " " :
4107 " Drop-In: ");
4108
4109 dir = mfree(dir);
4110
4111 dir = dirname_malloc(*dropin);
4112 if (!dir) {
4113 log_oom();
4114 return;
4115 }
4116
4117 printf("%s\n"
4118 " %s", dir,
4119 special_glyph(TREE_RIGHT));
4120 }
4121
4122 last = ! (*(dropin + 1) && startswith(*(dropin + 1), dir));
4123
4124 if (terminal_urlify_path(*dropin, basename(*dropin), &dropin_formatted) >= 0)
4125 df = dropin_formatted;
4126 else
4127 df = *dropin;
4128
4129 printf("%s%s", df, last ? "\n" : ", ");
4130 }
4131 }
4132
4133 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
4134 if (ss)
4135 printf(" Active: %s%s (%s)%s",
4136 active_on, strna(i->active_state), ss, active_off);
4137 else
4138 printf(" Active: %s%s%s",
4139 active_on, strna(i->active_state), active_off);
4140
4141 if (!isempty(i->result) && !streq(i->result, "success"))
4142 printf(" (Result: %s)", i->result);
4143
4144 timestamp = STRPTR_IN_SET(i->active_state, "active", "reloading") ? i->active_enter_timestamp :
4145 STRPTR_IN_SET(i->active_state, "inactive", "failed") ? i->inactive_enter_timestamp :
4146 STRPTR_IN_SET(i->active_state, "activating") ? i->inactive_exit_timestamp :
4147 i->active_exit_timestamp;
4148
4149 s1 = format_timestamp_relative(since1, sizeof(since1), timestamp);
4150 s2 = format_timestamp(since2, sizeof(since2), timestamp);
4151
4152 if (s1)
4153 printf(" since %s; %s\n", s2, s1);
4154 else if (s2)
4155 printf(" since %s\n", s2);
4156 else
4157 printf("\n");
4158
4159 if (endswith(i->id, ".timer")) {
4160 char tstamp1[FORMAT_TIMESTAMP_RELATIVE_MAX],
4161 tstamp2[FORMAT_TIMESTAMP_MAX];
4162 const char *next_rel_time, *next_time;
4163 dual_timestamp nw, next = {i->next_elapse_real,
4164 i->next_elapse_monotonic};
4165 usec_t next_elapse;
4166
4167 printf(" Trigger: ");
4168
4169 dual_timestamp_get(&nw);
4170 next_elapse = calc_next_elapse(&nw, &next);
4171 next_rel_time = format_timestamp_relative(tstamp1, sizeof tstamp1, next_elapse);
4172 next_time = format_timestamp(tstamp2, sizeof tstamp2, next_elapse);
4173
4174 if (next_time && next_rel_time)
4175 printf("%s; %s\n", next_time, next_rel_time);
4176 else
4177 printf("n/a\n");
4178 }
4179
4180 if (!i->condition_result && i->condition_timestamp > 0) {
4181 UnitCondition *c;
4182 int n = 0;
4183
4184 s1 = format_timestamp_relative(since1, sizeof(since1), i->condition_timestamp);
4185 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
4186
4187 printf("Condition: start %scondition failed%s at %s%s%s\n",
4188 ansi_highlight_yellow(), ansi_normal(),
4189 s2, s1 ? "; " : "", strempty(s1));
4190
4191 LIST_FOREACH(conditions, c, i->conditions)
4192 if (c->tristate < 0)
4193 n++;
4194
4195 LIST_FOREACH(conditions, c, i->conditions)
4196 if (c->tristate < 0)
4197 printf(" %s %s=%s%s%s was not met\n",
4198 --n ? special_glyph(TREE_BRANCH) : special_glyph(TREE_RIGHT),
4199 c->name,
4200 c->trigger ? "|" : "",
4201 c->negate ? "!" : "",
4202 c->param);
4203 }
4204
4205 if (!i->assert_result && i->assert_timestamp > 0) {
4206 s1 = format_timestamp_relative(since1, sizeof(since1), i->assert_timestamp);
4207 s2 = format_timestamp(since2, sizeof(since2), i->assert_timestamp);
4208
4209 printf(" Assert: start %sassertion failed%s at %s%s%s\n",
4210 ansi_highlight_red(), ansi_normal(),
4211 s2, s1 ? "; " : "", strempty(s1));
4212 if (i->failed_assert_trigger)
4213 printf(" none of the trigger assertions were met\n");
4214 else if (i->failed_assert)
4215 printf(" %s=%s%s was not met\n",
4216 i->failed_assert,
4217 i->failed_assert_negate ? "!" : "",
4218 i->failed_assert_parameter);
4219 }
4220
4221 if (i->sysfs_path)
4222 printf(" Device: %s\n", i->sysfs_path);
4223 if (i->where)
4224 printf(" Where: %s\n", i->where);
4225 if (i->what)
4226 printf(" What: %s\n", i->what);
4227
4228 STRV_FOREACH(t, i->documentation) {
4229 _cleanup_free_ char *formatted = NULL;
4230 const char *q;
4231
4232 if (terminal_urlify(*t, NULL, &formatted) >= 0)
4233 q = formatted;
4234 else
4235 q = *t;
4236
4237 printf(" %*s %s\n", 9, t == i->documentation ? "Docs:" : "", q);
4238 }
4239
4240 STRV_FOREACH_PAIR(t, t2, i->listen)
4241 printf(" %*s %s (%s)\n", 9, t == i->listen ? "Listen:" : "", *t2, *t);
4242
4243 if (i->accept) {
4244 printf(" Accepted: %u; Connected: %u;", i->n_accepted, i->n_connections);
4245 if (i->n_refused)
4246 printf(" Refused: %u", i->n_refused);
4247 printf("\n");
4248 }
4249
4250 LIST_FOREACH(exec, p, i->exec) {
4251 _cleanup_free_ char *argv = NULL;
4252 bool good;
4253
4254 /* Only show exited processes here */
4255 if (p->code == 0)
4256 continue;
4257
4258 argv = strv_join(p->argv, " ");
4259 printf(" Process: "PID_FMT" %s=%s ", p->pid, p->name, strna(argv));
4260
4261 good = is_clean_exit(p->code, p->status, EXIT_CLEAN_DAEMON, NULL);
4262 if (!good) {
4263 on = ansi_highlight_red();
4264 off = ansi_normal();
4265 } else
4266 on = off = "";
4267
4268 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
4269
4270 if (p->code == CLD_EXITED) {
4271 const char *c;
4272
4273 printf("status=%i", p->status);
4274
4275 c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD);
4276 if (c)
4277 printf("/%s", c);
4278
4279 } else
4280 printf("signal=%s", signal_to_string(p->status));
4281
4282 printf(")%s\n", off);
4283
4284 if (i->main_pid == p->pid &&
4285 i->start_timestamp == p->start_timestamp &&
4286 i->exit_timestamp == p->start_timestamp)
4287 /* Let's not show this twice */
4288 i->main_pid = 0;
4289
4290 if (p->pid == i->control_pid)
4291 i->control_pid = 0;
4292 }
4293
4294 if (i->main_pid > 0 || i->control_pid > 0) {
4295 if (i->main_pid > 0) {
4296 printf(" Main PID: "PID_FMT, i->main_pid);
4297
4298 if (i->running) {
4299
4300 if (arg_transport == BUS_TRANSPORT_LOCAL) {
4301 _cleanup_free_ char *comm = NULL;
4302
4303 (void) get_process_comm(i->main_pid, &comm);
4304 if (comm)
4305 printf(" (%s)", comm);
4306 }
4307
4308 } else if (i->exit_code > 0) {
4309 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
4310
4311 if (i->exit_code == CLD_EXITED) {
4312 const char *c;
4313
4314 printf("status=%i", i->exit_status);
4315
4316 c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD);
4317 if (c)
4318 printf("/%s", c);
4319
4320 } else
4321 printf("signal=%s", signal_to_string(i->exit_status));
4322 printf(")");
4323 }
4324 }
4325
4326 if (i->control_pid > 0) {
4327 _cleanup_free_ char *c = NULL;
4328
4329 if (i->main_pid > 0)
4330 fputs("; Control PID: ", stdout);
4331 else
4332 fputs("Cntrl PID: ", stdout); /* if first in column, abbreviated so it fits alignment */
4333
4334 printf(PID_FMT, i->control_pid);
4335
4336 if (arg_transport == BUS_TRANSPORT_LOCAL) {
4337 (void) get_process_comm(i->control_pid, &c);
4338 if (c)
4339 printf(" (%s)", c);
4340 }
4341 }
4342
4343 printf("\n");
4344 }
4345
4346 if (i->status_text)
4347 printf(" Status: \"%s\"\n", i->status_text);
4348 if (i->status_errno > 0)
4349 printf(" Error: %i (%s)\n", i->status_errno, strerror(i->status_errno));
4350
4351 if (i->ip_ingress_bytes != (uint64_t) -1 && i->ip_egress_bytes != (uint64_t) -1) {
4352 char buf_in[FORMAT_BYTES_MAX], buf_out[FORMAT_BYTES_MAX];
4353
4354 printf(" IP: %s in, %s out\n",
4355 format_bytes(buf_in, sizeof(buf_in), i->ip_ingress_bytes),
4356 format_bytes(buf_out, sizeof(buf_out), i->ip_egress_bytes));
4357 }
4358
4359 if (i->tasks_current != (uint64_t) -1) {
4360 printf(" Tasks: %" PRIu64, i->tasks_current);
4361
4362 if (i->tasks_max != (uint64_t) -1)
4363 printf(" (limit: %" PRIu64 ")\n", i->tasks_max);
4364 else
4365 printf("\n");
4366 }
4367
4368 if (i->memory_current != (uint64_t) -1) {
4369 char buf[FORMAT_BYTES_MAX];
4370
4371 printf(" Memory: %s", format_bytes(buf, sizeof(buf), i->memory_current));
4372
4373 if (i->memory_min > 0 || i->memory_low > 0 ||
4374 i->memory_high != CGROUP_LIMIT_MAX || i->memory_max != CGROUP_LIMIT_MAX ||
4375 i->memory_swap_max != CGROUP_LIMIT_MAX ||
4376 i->memory_limit != CGROUP_LIMIT_MAX) {
4377 const char *prefix = "";
4378
4379 printf(" (");
4380 if (i->memory_min > 0) {
4381 printf("%smin: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_min));
4382 prefix = " ";
4383 }
4384 if (i->memory_low > 0) {
4385 printf("%slow: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_low));
4386 prefix = " ";
4387 }
4388 if (i->memory_high != CGROUP_LIMIT_MAX) {
4389 printf("%shigh: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_high));
4390 prefix = " ";
4391 }
4392 if (i->memory_max != CGROUP_LIMIT_MAX) {
4393 printf("%smax: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_max));
4394 prefix = " ";
4395 }
4396 if (i->memory_swap_max != CGROUP_LIMIT_MAX) {
4397 printf("%sswap max: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_swap_max));
4398 prefix = " ";
4399 }
4400 if (i->memory_limit != CGROUP_LIMIT_MAX) {
4401 printf("%slimit: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_limit));
4402 prefix = " ";
4403 }
4404 printf(")");
4405 }
4406 printf("\n");
4407 }
4408
4409 if (i->cpu_usage_nsec != (uint64_t) -1) {
4410 char buf[FORMAT_TIMESPAN_MAX];
4411 printf(" CPU: %s\n", format_timespan(buf, sizeof(buf), i->cpu_usage_nsec / NSEC_PER_USEC, USEC_PER_MSEC));
4412 }
4413
4414 if (i->control_group) {
4415 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4416 static const char prefix[] = " ";
4417 unsigned c;
4418
4419 printf(" CGroup: %s\n", i->control_group);
4420
4421 c = columns();
4422 if (c > sizeof(prefix) - 1)
4423 c -= sizeof(prefix) - 1;
4424 else
4425 c = 0;
4426
4427 r = unit_show_processes(bus, i->id, i->control_group, prefix, c, get_output_flags(), &error);
4428 if (r == -EBADR) {
4429 unsigned k = 0;
4430 pid_t extra[2];
4431
4432 /* Fallback for older systemd versions where the GetUnitProcesses() call is not yet available */
4433
4434 if (i->main_pid > 0)
4435 extra[k++] = i->main_pid;
4436
4437 if (i->control_pid > 0)
4438 extra[k++] = i->control_pid;
4439
4440 show_cgroup_and_extra(SYSTEMD_CGROUP_CONTROLLER, i->control_group, prefix, c, extra, k, get_output_flags());
4441 } else if (r < 0)
4442 log_warning_errno(r, "Failed to dump process list for '%s', ignoring: %s", i->id, bus_error_message(&error, r));
4443 }
4444
4445 if (i->id && arg_transport == BUS_TRANSPORT_LOCAL)
4446 show_journal_by_unit(
4447 stdout,
4448 i->id,
4449 arg_output,
4450 0,
4451 i->inactive_exit_timestamp_monotonic,
4452 arg_lines,
4453 getuid(),
4454 get_output_flags() | OUTPUT_BEGIN_NEWLINE,
4455 SD_JOURNAL_LOCAL_ONLY,
4456 arg_scope == UNIT_FILE_SYSTEM,
4457 ellipsized);
4458
4459 if (i->need_daemon_reload)
4460 warn_unit_file_changed(i->id);
4461 }
4462
4463 static void show_unit_help(UnitStatusInfo *i) {
4464 char **p;
4465
4466 assert(i);
4467
4468 if (!i->documentation) {
4469 log_info("Documentation for %s not known.", i->id);
4470 return;
4471 }
4472
4473 STRV_FOREACH(p, i->documentation)
4474 if (startswith(*p, "man:"))
4475 show_man_page(*p + 4, false);
4476 else
4477 log_info("Can't show: %s", *p);
4478 }
4479
4480 static int map_main_pid(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4481 UnitStatusInfo *i = userdata;
4482 uint32_t u;
4483 int r;
4484
4485 r = sd_bus_message_read(m, "u", &u);
4486 if (r < 0)
4487 return r;
4488
4489 i->main_pid = (pid_t) u;
4490 i->running = u > 0;
4491
4492 return 0;
4493 }
4494
4495 static int map_load_error(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4496 const char *message, **p = userdata;
4497 int r;
4498
4499 r = sd_bus_message_read(m, "(ss)", NULL, &message);
4500 if (r < 0)
4501 return r;
4502
4503 if (!isempty(message))
4504 *p = message;
4505
4506 return 0;
4507 }
4508
4509 static int map_listen(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4510 const char *type, *path;
4511 char ***p = userdata;
4512 int r;
4513
4514 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
4515 if (r < 0)
4516 return r;
4517
4518 while ((r = sd_bus_message_read(m, "(ss)", &type, &path)) > 0) {
4519
4520 r = strv_extend(p, type);
4521 if (r < 0)
4522 return r;
4523
4524 r = strv_extend(p, path);
4525 if (r < 0)
4526 return r;
4527 }
4528 if (r < 0)
4529 return r;
4530
4531 r = sd_bus_message_exit_container(m);
4532 if (r < 0)
4533 return r;
4534
4535 return 0;
4536 }
4537
4538 static int map_conditions(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4539 UnitStatusInfo *i = userdata;
4540 const char *cond, *param;
4541 int trigger, negate;
4542 int32_t state;
4543 int r;
4544
4545 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sbbsi)");
4546 if (r < 0)
4547 return r;
4548
4549 while ((r = sd_bus_message_read(m, "(sbbsi)", &cond, &trigger, &negate, &param, &state)) > 0) {
4550 _cleanup_(unit_condition_freep) UnitCondition *c = NULL;
4551
4552 c = new0(UnitCondition, 1);
4553 if (!c)
4554 return -ENOMEM;
4555
4556 c->name = strdup(cond);
4557 c->param = strdup(param);
4558 if (!c->name || !c->param)
4559 return -ENOMEM;
4560
4561 c->trigger = trigger;
4562 c->negate = negate;
4563 c->tristate = state;
4564
4565 LIST_PREPEND(conditions, i->conditions, c);
4566 c = NULL;
4567 }
4568 if (r < 0)
4569 return r;
4570
4571 r = sd_bus_message_exit_container(m);
4572 if (r < 0)
4573 return r;
4574
4575 return 0;
4576 }
4577
4578 static int map_asserts(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4579 UnitStatusInfo *i = userdata;
4580 const char *cond, *param;
4581 int trigger, negate;
4582 int32_t state;
4583 int r;
4584
4585 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sbbsi)");
4586 if (r < 0)
4587 return r;
4588
4589 while ((r = sd_bus_message_read(m, "(sbbsi)", &cond, &trigger, &negate, &param, &state)) > 0) {
4590 if (state < 0 && (!trigger || !i->failed_assert)) {
4591 i->failed_assert = cond;
4592 i->failed_assert_trigger = trigger;
4593 i->failed_assert_negate = negate;
4594 i->failed_assert_parameter = param;
4595 }
4596 }
4597 if (r < 0)
4598 return r;
4599
4600 r = sd_bus_message_exit_container(m);
4601 if (r < 0)
4602 return r;
4603
4604 return 0;
4605 }
4606
4607 static int map_exec(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4608 _cleanup_free_ ExecStatusInfo *info = NULL;
4609 ExecStatusInfo *last;
4610 UnitStatusInfo *i = userdata;
4611 int r;
4612
4613 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sasbttttuii)");
4614 if (r < 0)
4615 return r;
4616
4617 info = new0(ExecStatusInfo, 1);
4618 if (!info)
4619 return -ENOMEM;
4620
4621 LIST_FIND_TAIL(exec, i->exec, last);
4622
4623 while ((r = exec_status_info_deserialize(m, info)) > 0) {
4624
4625 info->name = strdup(member);
4626 if (!info->name)
4627 return -ENOMEM;
4628
4629 LIST_INSERT_AFTER(exec, i->exec, last, info);
4630 last = info;
4631
4632 info = new0(ExecStatusInfo, 1);
4633 if (!info)
4634 return -ENOMEM;
4635 }
4636 if (r < 0)
4637 return r;
4638
4639 r = sd_bus_message_exit_container(m);
4640 if (r < 0)
4641 return r;
4642
4643 return 0;
4644 }
4645
4646 static int print_property(const char *name, const char *expected_value, sd_bus_message *m, bool value, bool all) {
4647 char bus_type;
4648 const char *contents;
4649 int r;
4650
4651 assert(name);
4652 assert(m);
4653
4654 /* This is a low-level property printer, see
4655 * print_status_info() for the nicer output */
4656
4657 r = sd_bus_message_peek_type(m, &bus_type, &contents);
4658 if (r < 0)
4659 return r;
4660
4661 switch (bus_type) {
4662
4663 case SD_BUS_TYPE_STRUCT:
4664
4665 if (contents[0] == SD_BUS_TYPE_UINT32 && streq(name, "Job")) {
4666 uint32_t u;
4667
4668 r = sd_bus_message_read(m, "(uo)", &u, NULL);
4669 if (r < 0)
4670 return bus_log_parse_error(r);
4671
4672 if (u > 0)
4673 bus_print_property_value(name, expected_value, value, "%"PRIu32, u);
4674 else if (all)
4675 bus_print_property_value(name, expected_value, value, "%s", "");
4676
4677 return 1;
4678
4679 } else if (contents[0] == SD_BUS_TYPE_STRING && streq(name, "Unit")) {
4680 const char *s;
4681
4682 r = sd_bus_message_read(m, "(so)", &s, NULL);
4683 if (r < 0)
4684 return bus_log_parse_error(r);
4685
4686 if (all || !isempty(s))
4687 bus_print_property_value(name, expected_value, value, "%s", s);
4688
4689 return 1;
4690
4691 } else if (contents[0] == SD_BUS_TYPE_STRING && streq(name, "LoadError")) {
4692 const char *a = NULL, *b = NULL;
4693
4694 r = sd_bus_message_read(m, "(ss)", &a, &b);
4695 if (r < 0)
4696 return bus_log_parse_error(r);
4697
4698 if (all || !isempty(a) || !isempty(b))
4699 bus_print_property_value(name, expected_value, value, "%s \"%s\"", strempty(a), strempty(b));
4700
4701 return 1;
4702 } else if (streq_ptr(name, "SystemCallFilter")) {
4703 _cleanup_strv_free_ char **l = NULL;
4704 int whitelist;
4705
4706 r = sd_bus_message_enter_container(m, 'r', "bas");
4707 if (r < 0)
4708 return bus_log_parse_error(r);
4709
4710 r = sd_bus_message_read(m, "b", &whitelist);
4711 if (r < 0)
4712 return bus_log_parse_error(r);
4713
4714 r = sd_bus_message_read_strv(m, &l);
4715 if (r < 0)
4716 return bus_log_parse_error(r);
4717
4718 r = sd_bus_message_exit_container(m);
4719 if (r < 0)
4720 return bus_log_parse_error(r);
4721
4722 if (all || whitelist || !strv_isempty(l)) {
4723 bool first = true;
4724 char **i;
4725
4726 if (!value) {
4727 fputs(name, stdout);
4728 fputc('=', stdout);
4729 }
4730
4731 if (!whitelist)
4732 fputc('~', stdout);
4733
4734 STRV_FOREACH(i, l) {
4735 if (first)
4736 first = false;
4737 else
4738 fputc(' ', stdout);
4739
4740 fputs(*i, stdout);
4741 }
4742 fputc('\n', stdout);
4743 }
4744
4745 return 1;
4746 }
4747
4748 break;
4749
4750 case SD_BUS_TYPE_ARRAY:
4751
4752 if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "EnvironmentFiles")) {
4753 const char *path;
4754 int ignore;
4755
4756 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sb)");
4757 if (r < 0)
4758 return bus_log_parse_error(r);
4759
4760 while ((r = sd_bus_message_read(m, "(sb)", &path, &ignore)) > 0)
4761 bus_print_property_value(name, expected_value, value, "%s (ignore_errors=%s)", path, yes_no(ignore));
4762
4763 if (r < 0)
4764 return bus_log_parse_error(r);
4765
4766 r = sd_bus_message_exit_container(m);
4767 if (r < 0)
4768 return bus_log_parse_error(r);
4769
4770 return 1;
4771
4772 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "Paths")) {
4773 const char *type, *path;
4774
4775 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
4776 if (r < 0)
4777 return bus_log_parse_error(r);
4778
4779 while ((r = sd_bus_message_read(m, "(ss)", &type, &path)) > 0)
4780 bus_print_property_value(name, expected_value, value, "%s (%s)", path, type);
4781 if (r < 0)
4782 return bus_log_parse_error(r);
4783
4784 r = sd_bus_message_exit_container(m);
4785 if (r < 0)
4786 return bus_log_parse_error(r);
4787
4788 return 1;
4789
4790 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "Listen")) {
4791 const char *type, *path;
4792
4793 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
4794 if (r < 0)
4795 return bus_log_parse_error(r);
4796
4797 while ((r = sd_bus_message_read(m, "(ss)", &type, &path)) > 0)
4798 bus_print_property_value(name, expected_value, value, "%s (%s)", path, type);
4799 if (r < 0)
4800 return bus_log_parse_error(r);
4801
4802 r = sd_bus_message_exit_container(m);
4803 if (r < 0)
4804 return bus_log_parse_error(r);
4805
4806 return 1;
4807
4808 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "TimersMonotonic")) {
4809 const char *base;
4810 uint64_t v, next_elapse;
4811
4812 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(stt)");
4813 if (r < 0)
4814 return bus_log_parse_error(r);
4815
4816 while ((r = sd_bus_message_read(m, "(stt)", &base, &v, &next_elapse)) > 0) {
4817 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
4818
4819 bus_print_property_value(name, expected_value, value, "{ %s=%s ; next_elapse=%s }", base,
4820 format_timespan(timespan1, sizeof(timespan1), v, 0),
4821 format_timespan(timespan2, sizeof(timespan2), next_elapse, 0));
4822 }
4823 if (r < 0)
4824 return bus_log_parse_error(r);
4825
4826 r = sd_bus_message_exit_container(m);
4827 if (r < 0)
4828 return bus_log_parse_error(r);
4829
4830 return 1;
4831
4832 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "TimersCalendar")) {
4833 const char *base, *spec;
4834 uint64_t next_elapse;
4835
4836 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sst)");
4837 if (r < 0)
4838 return bus_log_parse_error(r);
4839
4840 while ((r = sd_bus_message_read(m, "(sst)", &base, &spec, &next_elapse)) > 0) {
4841 char timestamp[FORMAT_TIMESTAMP_MAX];
4842
4843 bus_print_property_value(name, expected_value, value, "{ %s=%s ; next_elapse=%s }", base, spec,
4844 format_timestamp(timestamp, sizeof(timestamp), next_elapse));
4845 }
4846 if (r < 0)
4847 return bus_log_parse_error(r);
4848
4849 r = sd_bus_message_exit_container(m);
4850 if (r < 0)
4851 return bus_log_parse_error(r);
4852
4853 return 1;
4854
4855 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && startswith(name, "Exec")) {
4856 ExecStatusInfo info = {};
4857
4858 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sasbttttuii)");
4859 if (r < 0)
4860 return bus_log_parse_error(r);
4861
4862 while ((r = exec_status_info_deserialize(m, &info)) > 0) {
4863 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
4864 _cleanup_free_ char *tt;
4865
4866 tt = strv_join(info.argv, " ");
4867
4868 bus_print_property_value(name, expected_value, value,
4869 "{ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT" ; code=%s ; status=%i%s%s }",
4870 strna(info.path),
4871 strna(tt),
4872 yes_no(info.ignore),
4873 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
4874 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
4875 info.pid,
4876 sigchld_code_to_string(info.code),
4877 info.status,
4878 info.code == CLD_EXITED ? "" : "/",
4879 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
4880
4881 free(info.path);
4882 strv_free(info.argv);
4883 zero(info);
4884 }
4885
4886 r = sd_bus_message_exit_container(m);
4887 if (r < 0)
4888 return bus_log_parse_error(r);
4889
4890 return 1;
4891
4892 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "DeviceAllow")) {
4893 const char *path, *rwm;
4894
4895 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
4896 if (r < 0)
4897 return bus_log_parse_error(r);
4898
4899 while ((r = sd_bus_message_read(m, "(ss)", &path, &rwm)) > 0)
4900 bus_print_property_value(name, expected_value, value, "%s %s", strna(path), strna(rwm));
4901 if (r < 0)
4902 return bus_log_parse_error(r);
4903
4904 r = sd_bus_message_exit_container(m);
4905 if (r < 0)
4906 return bus_log_parse_error(r);
4907
4908 return 1;
4909
4910 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN &&
4911 STR_IN_SET(name, "IODeviceWeight", "BlockIODeviceWeight")) {
4912 const char *path;
4913 uint64_t weight;
4914
4915 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(st)");
4916 if (r < 0)
4917 return bus_log_parse_error(r);
4918
4919 while ((r = sd_bus_message_read(m, "(st)", &path, &weight)) > 0)
4920 bus_print_property_value(name, expected_value, value, "%s %"PRIu64, strna(path), weight);
4921 if (r < 0)
4922 return bus_log_parse_error(r);
4923
4924 r = sd_bus_message_exit_container(m);
4925 if (r < 0)
4926 return bus_log_parse_error(r);
4927
4928 return 1;
4929
4930 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN &&
4931 (cgroup_io_limit_type_from_string(name) >= 0 ||
4932 STR_IN_SET(name, "BlockIOReadBandwidth", "BlockIOWriteBandwidth"))) {
4933 const char *path;
4934 uint64_t bandwidth;
4935
4936 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(st)");
4937 if (r < 0)
4938 return bus_log_parse_error(r);
4939
4940 while ((r = sd_bus_message_read(m, "(st)", &path, &bandwidth)) > 0)
4941 bus_print_property_value(name, expected_value, value, "%s %"PRIu64, strna(path), bandwidth);
4942 if (r < 0)
4943 return bus_log_parse_error(r);
4944
4945 r = sd_bus_message_exit_container(m);
4946 if (r < 0)
4947 return bus_log_parse_error(r);
4948
4949 return 1;
4950
4951 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN &&
4952 streq(name, "IODeviceLatencyTargetUSec")) {
4953 char ts[FORMAT_TIMESPAN_MAX];
4954 const char *path;
4955 uint64_t target;
4956
4957 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(st)");
4958 if (r < 0)
4959 return bus_log_parse_error(r);
4960
4961 while ((r = sd_bus_message_read(m, "(st)", &path, &target)) > 0)
4962 bus_print_property_value(name, expected_value, value, "%s %s", strna(path),
4963 format_timespan(ts, sizeof(ts), target, 1));
4964 if (r < 0)
4965 return bus_log_parse_error(r);
4966
4967 r = sd_bus_message_exit_container(m);
4968 if (r < 0)
4969 return bus_log_parse_error(r);
4970
4971 return 1;
4972
4973 } else if (contents[0] == SD_BUS_TYPE_BYTE && streq(name, "StandardInputData")) {
4974 _cleanup_free_ char *h = NULL;
4975 const void *p;
4976 size_t sz;
4977 ssize_t n;
4978
4979 r = sd_bus_message_read_array(m, 'y', &p, &sz);
4980 if (r < 0)
4981 return bus_log_parse_error(r);
4982
4983 n = base64mem(p, sz, &h);
4984 if (n < 0)
4985 return log_oom();
4986
4987 bus_print_property_value(name, expected_value, value, "%s", h);
4988
4989 return 1;
4990 }
4991
4992 break;
4993 }
4994
4995 return 0;
4996 }
4997
4998 typedef enum SystemctlShowMode{
4999 SYSTEMCTL_SHOW_PROPERTIES,
5000 SYSTEMCTL_SHOW_STATUS,
5001 SYSTEMCTL_SHOW_HELP,
5002 _SYSTEMCTL_SHOW_MODE_MAX,
5003 _SYSTEMCTL_SHOW_MODE_INVALID = -1,
5004 } SystemctlShowMode;
5005
5006 static const char* const systemctl_show_mode_table[_SYSTEMCTL_SHOW_MODE_MAX] = {
5007 [SYSTEMCTL_SHOW_PROPERTIES] = "show",
5008 [SYSTEMCTL_SHOW_STATUS] = "status",
5009 [SYSTEMCTL_SHOW_HELP] = "help",
5010 };
5011
5012 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(systemctl_show_mode, SystemctlShowMode);
5013
5014 static int show_one(
5015 sd_bus *bus,
5016 const char *path,
5017 const char *unit,
5018 SystemctlShowMode show_mode,
5019 bool *new_line,
5020 bool *ellipsized) {
5021
5022 static const struct bus_properties_map property_map[] = {
5023 { "LoadState", "s", NULL, offsetof(UnitStatusInfo, load_state) },
5024 { "ActiveState", "s", NULL, offsetof(UnitStatusInfo, active_state) },
5025 { "Documentation", "as", NULL, offsetof(UnitStatusInfo, documentation) },
5026 {}
5027 }, status_map[] = {
5028 { "Id", "s", NULL, offsetof(UnitStatusInfo, id) },
5029 { "LoadState", "s", NULL, offsetof(UnitStatusInfo, load_state) },
5030 { "ActiveState", "s", NULL, offsetof(UnitStatusInfo, active_state) },
5031 { "SubState", "s", NULL, offsetof(UnitStatusInfo, sub_state) },
5032 { "UnitFileState", "s", NULL, offsetof(UnitStatusInfo, unit_file_state) },
5033 { "UnitFilePreset", "s", NULL, offsetof(UnitStatusInfo, unit_file_preset) },
5034 { "Description", "s", NULL, offsetof(UnitStatusInfo, description) },
5035 { "Following", "s", NULL, offsetof(UnitStatusInfo, following) },
5036 { "Documentation", "as", NULL, offsetof(UnitStatusInfo, documentation) },
5037 { "FragmentPath", "s", NULL, offsetof(UnitStatusInfo, fragment_path) },
5038 { "SourcePath", "s", NULL, offsetof(UnitStatusInfo, source_path) },
5039 { "ControlGroup", "s", NULL, offsetof(UnitStatusInfo, control_group) },
5040 { "DropInPaths", "as", NULL, offsetof(UnitStatusInfo, dropin_paths) },
5041 { "LoadError", "(ss)", map_load_error, offsetof(UnitStatusInfo, load_error) },
5042 { "Result", "s", NULL, offsetof(UnitStatusInfo, result) },
5043 { "InactiveExitTimestamp", "t", NULL, offsetof(UnitStatusInfo, inactive_exit_timestamp) },
5044 { "InactiveExitTimestampMonotonic", "t", NULL, offsetof(UnitStatusInfo, inactive_exit_timestamp_monotonic) },
5045 { "ActiveEnterTimestamp", "t", NULL, offsetof(UnitStatusInfo, active_enter_timestamp) },
5046 { "ActiveExitTimestamp", "t", NULL, offsetof(UnitStatusInfo, active_exit_timestamp) },
5047 { "InactiveEnterTimestamp", "t", NULL, offsetof(UnitStatusInfo, inactive_enter_timestamp) },
5048 { "NeedDaemonReload", "b", NULL, offsetof(UnitStatusInfo, need_daemon_reload) },
5049 { "Transient", "b", NULL, offsetof(UnitStatusInfo, transient) },
5050 { "ExecMainPID", "u", NULL, offsetof(UnitStatusInfo, main_pid) },
5051 { "MainPID", "u", map_main_pid, 0 },
5052 { "ControlPID", "u", NULL, offsetof(UnitStatusInfo, control_pid) },
5053 { "StatusText", "s", NULL, offsetof(UnitStatusInfo, status_text) },
5054 { "PIDFile", "s", NULL, offsetof(UnitStatusInfo, pid_file) },
5055 { "StatusErrno", "i", NULL, offsetof(UnitStatusInfo, status_errno) },
5056 { "ExecMainStartTimestamp", "t", NULL, offsetof(UnitStatusInfo, start_timestamp) },
5057 { "ExecMainExitTimestamp", "t", NULL, offsetof(UnitStatusInfo, exit_timestamp) },
5058 { "ExecMainCode", "i", NULL, offsetof(UnitStatusInfo, exit_code) },
5059 { "ExecMainStatus", "i", NULL, offsetof(UnitStatusInfo, exit_status) },
5060 { "ConditionTimestamp", "t", NULL, offsetof(UnitStatusInfo, condition_timestamp) },
5061 { "ConditionResult", "b", NULL, offsetof(UnitStatusInfo, condition_result) },
5062 { "Conditions", "a(sbbsi)", map_conditions, 0 },
5063 { "AssertTimestamp", "t", NULL, offsetof(UnitStatusInfo, assert_timestamp) },
5064 { "AssertResult", "b", NULL, offsetof(UnitStatusInfo, assert_result) },
5065 { "Asserts", "a(sbbsi)", map_asserts, 0 },
5066 { "NextElapseUSecRealtime", "t", NULL, offsetof(UnitStatusInfo, next_elapse_real) },
5067 { "NextElapseUSecMonotonic", "t", NULL, offsetof(UnitStatusInfo, next_elapse_monotonic) },
5068 { "NAccepted", "u", NULL, offsetof(UnitStatusInfo, n_accepted) },
5069 { "NConnections", "u", NULL, offsetof(UnitStatusInfo, n_connections) },
5070 { "NRefused", "u", NULL, offsetof(UnitStatusInfo, n_refused) },
5071 { "Accept", "b", NULL, offsetof(UnitStatusInfo, accept) },
5072 { "Listen", "a(ss)", map_listen, offsetof(UnitStatusInfo, listen) },
5073 { "SysFSPath", "s", NULL, offsetof(UnitStatusInfo, sysfs_path) },
5074 { "Where", "s", NULL, offsetof(UnitStatusInfo, where) },
5075 { "What", "s", NULL, offsetof(UnitStatusInfo, what) },
5076 { "MemoryCurrent", "t", NULL, offsetof(UnitStatusInfo, memory_current) },
5077 { "MemoryMin", "t", NULL, offsetof(UnitStatusInfo, memory_min) },
5078 { "MemoryLow", "t", NULL, offsetof(UnitStatusInfo, memory_low) },
5079 { "MemoryHigh", "t", NULL, offsetof(UnitStatusInfo, memory_high) },
5080 { "MemoryMax", "t", NULL, offsetof(UnitStatusInfo, memory_max) },
5081 { "MemorySwapMax", "t", NULL, offsetof(UnitStatusInfo, memory_swap_max) },
5082 { "MemoryLimit", "t", NULL, offsetof(UnitStatusInfo, memory_limit) },
5083 { "CPUUsageNSec", "t", NULL, offsetof(UnitStatusInfo, cpu_usage_nsec) },
5084 { "TasksCurrent", "t", NULL, offsetof(UnitStatusInfo, tasks_current) },
5085 { "TasksMax", "t", NULL, offsetof(UnitStatusInfo, tasks_max) },
5086 { "IPIngressBytes", "t", NULL, offsetof(UnitStatusInfo, ip_ingress_bytes) },
5087 { "IPEgressBytes", "t", NULL, offsetof(UnitStatusInfo, ip_egress_bytes) },
5088 { "ExecStartPre", "a(sasbttttuii)", map_exec, 0 },
5089 { "ExecStart", "a(sasbttttuii)", map_exec, 0 },
5090 { "ExecStartPost", "a(sasbttttuii)", map_exec, 0 },
5091 { "ExecReload", "a(sasbttttuii)", map_exec, 0 },
5092 { "ExecStopPre", "a(sasbttttuii)", map_exec, 0 },
5093 { "ExecStop", "a(sasbttttuii)", map_exec, 0 },
5094 { "ExecStopPost", "a(sasbttttuii)", map_exec, 0 },
5095 {}
5096 };
5097
5098 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
5099 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5100 _cleanup_set_free_ Set *found_properties = NULL;
5101 _cleanup_(unit_status_info_free) UnitStatusInfo info = {
5102 .memory_current = (uint64_t) -1,
5103 .memory_high = CGROUP_LIMIT_MAX,
5104 .memory_max = CGROUP_LIMIT_MAX,
5105 .memory_swap_max = CGROUP_LIMIT_MAX,
5106 .memory_limit = (uint64_t) -1,
5107 .cpu_usage_nsec = (uint64_t) -1,
5108 .tasks_current = (uint64_t) -1,
5109 .tasks_max = (uint64_t) -1,
5110 .ip_ingress_bytes = (uint64_t) -1,
5111 .ip_egress_bytes = (uint64_t) -1,
5112 };
5113 char **pp;
5114 int r;
5115
5116 assert(path);
5117 assert(new_line);
5118
5119 log_debug("Showing one %s", path);
5120
5121 r = bus_map_all_properties(
5122 bus,
5123 "org.freedesktop.systemd1",
5124 path,
5125 show_mode == SYSTEMCTL_SHOW_STATUS ? status_map : property_map,
5126 BUS_MAP_BOOLEAN_AS_BOOL,
5127 &error,
5128 &reply,
5129 &info);
5130 if (r < 0)
5131 return log_error_errno(r, "Failed to get properties: %s", bus_error_message(&error, r));
5132
5133 if (unit && streq_ptr(info.load_state, "not-found") && streq_ptr(info.active_state, "inactive")) {
5134 log_full(show_mode == SYSTEMCTL_SHOW_STATUS ? LOG_ERR : LOG_DEBUG,
5135 "Unit %s could not be found.", unit);
5136
5137 if (show_mode == SYSTEMCTL_SHOW_STATUS)
5138 return EXIT_PROGRAM_OR_SERVICES_STATUS_UNKNOWN;
5139 else if (show_mode == SYSTEMCTL_SHOW_HELP)
5140 return -ENOENT;
5141 }
5142
5143 if (*new_line)
5144 printf("\n");
5145
5146 *new_line = true;
5147
5148 if (show_mode == SYSTEMCTL_SHOW_STATUS) {
5149 print_status_info(bus, &info, ellipsized);
5150
5151 if (info.active_state && !STR_IN_SET(info.active_state, "active", "reloading"))
5152 return EXIT_PROGRAM_NOT_RUNNING;
5153
5154 return EXIT_PROGRAM_RUNNING_OR_SERVICE_OK;
5155
5156 } else if (show_mode == SYSTEMCTL_SHOW_HELP) {
5157 show_unit_help(&info);
5158 return 0;
5159 }
5160
5161 r = sd_bus_message_rewind(reply, true);
5162 if (r < 0)
5163 return log_error_errno(r, "Failed to rewind: %s", bus_error_message(&error, r));
5164
5165 r = bus_message_print_all_properties(reply, print_property, arg_properties, arg_value, arg_all, &found_properties);
5166 if (r < 0)
5167 return bus_log_parse_error(r);
5168
5169 STRV_FOREACH(pp, arg_properties)
5170 if (!set_contains(found_properties, *pp))
5171 log_debug("Property %s does not exist.", *pp);
5172
5173 return 0;
5174 }
5175
5176 static int get_unit_dbus_path_by_pid(
5177 sd_bus *bus,
5178 uint32_t pid,
5179 char **unit) {
5180
5181 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5182 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
5183 char *u;
5184 int r;
5185
5186 r = sd_bus_call_method(
5187 bus,
5188 "org.freedesktop.systemd1",
5189 "/org/freedesktop/systemd1",
5190 "org.freedesktop.systemd1.Manager",
5191 "GetUnitByPID",
5192 &error,
5193 &reply,
5194 "u", pid);
5195 if (r < 0)
5196 return log_error_errno(r, "Failed to get unit for PID %"PRIu32": %s", pid, bus_error_message(&error, r));
5197
5198 r = sd_bus_message_read(reply, "o", &u);
5199 if (r < 0)
5200 return bus_log_parse_error(r);
5201
5202 u = strdup(u);
5203 if (!u)
5204 return log_oom();
5205
5206 *unit = u;
5207 return 0;
5208 }
5209
5210 static int show_all(
5211 sd_bus *bus,
5212 bool *new_line,
5213 bool *ellipsized) {
5214
5215 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
5216 _cleanup_free_ UnitInfo *unit_infos = NULL;
5217 const UnitInfo *u;
5218 unsigned c;
5219 int r, ret = 0;
5220
5221 r = get_unit_list(bus, NULL, NULL, &unit_infos, 0, &reply);
5222 if (r < 0)
5223 return r;
5224
5225 (void) pager_open(arg_pager_flags);
5226
5227 c = (unsigned) r;
5228
5229 typesafe_qsort(unit_infos, c, compare_unit_info);
5230
5231 for (u = unit_infos; u < unit_infos + c; u++) {
5232 _cleanup_free_ char *p = NULL;
5233
5234 p = unit_dbus_path_from_name(u->id);
5235 if (!p)
5236 return log_oom();
5237
5238 r = show_one(bus, p, u->id, SYSTEMCTL_SHOW_STATUS, new_line, ellipsized);
5239 if (r < 0)
5240 return r;
5241 else if (r > 0 && ret == 0)
5242 ret = r;
5243 }
5244
5245 return ret;
5246 }
5247
5248 static int show_system_status(sd_bus *bus) {
5249 char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], since2[FORMAT_TIMESTAMP_MAX];
5250 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5251 _cleanup_(machine_info_clear) struct machine_info mi = {};
5252 _cleanup_free_ char *hn = NULL;
5253 const char *on, *off;
5254 int r;
5255
5256 hn = gethostname_malloc();
5257 if (!hn)
5258 return log_oom();
5259
5260 r = bus_map_all_properties(
5261 bus,
5262 "org.freedesktop.systemd1",
5263 "/org/freedesktop/systemd1",
5264 machine_info_property_map,
5265 BUS_MAP_STRDUP,
5266 &error,
5267 NULL,
5268 &mi);
5269 if (r < 0)
5270 return log_error_errno(r, "Failed to read server status: %s", bus_error_message(&error, r));
5271
5272 if (streq_ptr(mi.state, "degraded")) {
5273 on = ansi_highlight_red();
5274 off = ansi_normal();
5275 } else if (streq_ptr(mi.state, "running")) {
5276 on = ansi_highlight_green();
5277 off = ansi_normal();
5278 } else {
5279 on = ansi_highlight_yellow();
5280 off = ansi_normal();
5281 }
5282
5283 printf("%s%s%s %s\n", on, special_glyph(BLACK_CIRCLE), off, arg_host ? arg_host : hn);
5284
5285 printf(" State: %s%s%s\n",
5286 on, strna(mi.state), off);
5287
5288 printf(" Jobs: %" PRIu32 " queued\n", mi.n_jobs);
5289 printf(" Failed: %" PRIu32 " units\n", mi.n_failed_units);
5290
5291 printf(" Since: %s; %s\n",
5292 format_timestamp(since2, sizeof(since2), mi.timestamp),
5293 format_timestamp_relative(since1, sizeof(since1), mi.timestamp));
5294
5295 printf(" CGroup: %s\n", mi.control_group ?: "/");
5296 if (IN_SET(arg_transport,
5297 BUS_TRANSPORT_LOCAL,
5298 BUS_TRANSPORT_MACHINE)) {
5299 static const char prefix[] = " ";
5300 unsigned c;
5301
5302 c = columns();
5303 if (c > sizeof(prefix) - 1)
5304 c -= sizeof(prefix) - 1;
5305 else
5306 c = 0;
5307
5308 show_cgroup(SYSTEMD_CGROUP_CONTROLLER, strempty(mi.control_group), prefix, c, get_output_flags());
5309 }
5310
5311 return 0;
5312 }
5313
5314 static int show(int argc, char *argv[], void *userdata) {
5315 bool new_line = false, ellipsized = false;
5316 SystemctlShowMode show_mode;
5317 int r, ret = 0;
5318 sd_bus *bus;
5319
5320 assert(argv);
5321
5322 show_mode = systemctl_show_mode_from_string(argv[0]);
5323 if (show_mode < 0)
5324 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
5325 "Invalid argument.");
5326
5327 if (show_mode == SYSTEMCTL_SHOW_HELP && argc <= 1)
5328 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
5329 "This command expects one or more unit names. Did you mean --help?");
5330
5331 r = acquire_bus(BUS_MANAGER, &bus);
5332 if (r < 0)
5333 return r;
5334
5335 (void) pager_open(arg_pager_flags);
5336
5337 /* If no argument is specified inspect the manager itself */
5338 if (show_mode == SYSTEMCTL_SHOW_PROPERTIES && argc <= 1)
5339 return show_one(bus, "/org/freedesktop/systemd1", NULL, show_mode, &new_line, &ellipsized);
5340
5341 if (show_mode == SYSTEMCTL_SHOW_STATUS && argc <= 1) {
5342
5343 show_system_status(bus);
5344 new_line = true;
5345
5346 if (arg_all)
5347 ret = show_all(bus, &new_line, &ellipsized);
5348 } else {
5349 _cleanup_free_ char **patterns = NULL;
5350 char **name;
5351
5352 STRV_FOREACH(name, strv_skip(argv, 1)) {
5353 _cleanup_free_ char *path = NULL, *unit = NULL;
5354 uint32_t id;
5355
5356 if (safe_atou32(*name, &id) < 0) {
5357 if (strv_push(&patterns, *name) < 0)
5358 return log_oom();
5359
5360 continue;
5361 } else if (show_mode == SYSTEMCTL_SHOW_PROPERTIES) {
5362 /* Interpret as job id */
5363 if (asprintf(&path, "/org/freedesktop/systemd1/job/%u", id) < 0)
5364 return log_oom();
5365
5366 } else {
5367 /* Interpret as PID */
5368 r = get_unit_dbus_path_by_pid(bus, id, &path);
5369 if (r < 0) {
5370 ret = r;
5371 continue;
5372 }
5373
5374 r = unit_name_from_dbus_path(path, &unit);
5375 if (r < 0)
5376 return log_oom();
5377 }
5378
5379 r = show_one(bus, path, unit, show_mode, &new_line, &ellipsized);
5380 if (r < 0)
5381 return r;
5382 else if (r > 0 && ret == 0)
5383 ret = r;
5384 }
5385
5386 if (!strv_isempty(patterns)) {
5387 _cleanup_strv_free_ char **names = NULL;
5388
5389 r = expand_names(bus, patterns, NULL, &names);
5390 if (r < 0)
5391 return log_error_errno(r, "Failed to expand names: %m");
5392
5393 STRV_FOREACH(name, names) {
5394 _cleanup_free_ char *path;
5395
5396 path = unit_dbus_path_from_name(*name);
5397 if (!path)
5398 return log_oom();
5399
5400 r = show_one(bus, path, *name, show_mode, &new_line, &ellipsized);
5401 if (r < 0)
5402 return r;
5403 if (r > 0 && ret == 0)
5404 ret = r;
5405 }
5406 }
5407 }
5408
5409 if (ellipsized && !arg_quiet)
5410 printf("Hint: Some lines were ellipsized, use -l to show in full.\n");
5411
5412 return ret;
5413 }
5414
5415 static int cat(int argc, char *argv[], void *userdata) {
5416 _cleanup_(lookup_paths_free) LookupPaths lp = {};
5417 _cleanup_strv_free_ char **names = NULL;
5418 char **name;
5419 sd_bus *bus;
5420 bool first = true;
5421 int r;
5422
5423 if (arg_transport != BUS_TRANSPORT_LOCAL) {
5424 log_error("Cannot remotely cat units.");
5425 return -EINVAL;
5426 }
5427
5428 r = lookup_paths_init(&lp, arg_scope, 0, arg_root);
5429 if (r < 0)
5430 return log_error_errno(r, "Failed to determine unit paths: %m");
5431
5432 r = acquire_bus(BUS_MANAGER, &bus);
5433 if (r < 0)
5434 return r;
5435
5436 r = expand_names(bus, strv_skip(argv, 1), NULL, &names);
5437 if (r < 0)
5438 return log_error_errno(r, "Failed to expand names: %m");
5439
5440 (void) pager_open(arg_pager_flags);
5441
5442 STRV_FOREACH(name, names) {
5443 _cleanup_free_ char *fragment_path = NULL;
5444 _cleanup_strv_free_ char **dropin_paths = NULL;
5445
5446 r = unit_find_paths(bus, *name, &lp, false, &fragment_path, &dropin_paths);
5447 if (r == -ERFKILL) {
5448 printf("%s# Unit %s is masked%s.\n",
5449 ansi_highlight_magenta(),
5450 *name,
5451 ansi_normal());
5452 continue;
5453 }
5454 if (r == -EKEYREJECTED) {
5455 printf("%s# Unit %s could not be loaded.%s\n",
5456 ansi_highlight_magenta(),
5457 *name,
5458 ansi_normal());
5459 continue;
5460 }
5461 if (r < 0)
5462 return r;
5463 if (r == 0)
5464 return -ENOENT;
5465
5466 if (first)
5467 first = false;
5468 else
5469 puts("");
5470
5471 if (need_daemon_reload(bus, *name) > 0) /* ignore errors (<0), this is informational output */
5472 fprintf(stderr,
5473 "%s# Warning: %s changed on disk, the version systemd has loaded is outdated.\n"
5474 "%s# This output shows the current version of the unit's original fragment and drop-in files.\n"
5475 "%s# If fragments or drop-ins were added or removed, they are not properly reflected in this output.\n"
5476 "%s# Run 'systemctl%s daemon-reload' to reload units.%s\n",
5477 ansi_highlight_red(),
5478 *name,
5479 ansi_highlight_red(),
5480 ansi_highlight_red(),
5481 ansi_highlight_red(),
5482 arg_scope == UNIT_FILE_SYSTEM ? "" : " --user",
5483 ansi_normal());
5484
5485 r = cat_files(fragment_path, dropin_paths, 0);
5486 if (r < 0)
5487 return r;
5488 }
5489
5490 return 0;
5491 }
5492
5493 static int set_property(int argc, char *argv[], void *userdata) {
5494 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
5495 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5496 _cleanup_free_ char *n = NULL;
5497 UnitType t;
5498 sd_bus *bus;
5499 int r;
5500
5501 r = acquire_bus(BUS_MANAGER, &bus);
5502 if (r < 0)
5503 return r;
5504
5505 polkit_agent_open_maybe();
5506
5507 r = sd_bus_message_new_method_call(
5508 bus,
5509 &m,
5510 "org.freedesktop.systemd1",
5511 "/org/freedesktop/systemd1",
5512 "org.freedesktop.systemd1.Manager",
5513 "SetUnitProperties");
5514 if (r < 0)
5515 return bus_log_create_error(r);
5516
5517 r = unit_name_mangle(argv[1], arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, &n);
5518 if (r < 0)
5519 return log_error_errno(r, "Failed to mangle unit name: %m");
5520
5521 t = unit_name_to_type(n);
5522 if (t < 0) {
5523 log_error("Invalid unit type: %s", n);
5524 return -EINVAL;
5525 }
5526
5527 r = sd_bus_message_append(m, "sb", n, arg_runtime);
5528 if (r < 0)
5529 return bus_log_create_error(r);
5530
5531 r = sd_bus_message_open_container(m, SD_BUS_TYPE_ARRAY, "(sv)");
5532 if (r < 0)
5533 return bus_log_create_error(r);
5534
5535 r = bus_append_unit_property_assignment_many(m, t, strv_skip(argv, 2));
5536 if (r < 0)
5537 return r;
5538
5539 r = sd_bus_message_close_container(m);
5540 if (r < 0)
5541 return bus_log_create_error(r);
5542
5543 r = sd_bus_call(bus, m, 0, &error, NULL);
5544 if (r < 0)
5545 return log_error_errno(r, "Failed to set unit properties on %s: %s", n, bus_error_message(&error, r));
5546
5547 return 0;
5548 }
5549
5550 static int daemon_reload(int argc, char *argv[], void *userdata) {
5551 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5552 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
5553 const char *method;
5554 sd_bus *bus;
5555 int r;
5556
5557 r = acquire_bus(BUS_MANAGER, &bus);
5558 if (r < 0)
5559 return r;
5560
5561 polkit_agent_open_maybe();
5562
5563 switch (arg_action) {
5564
5565 case ACTION_RELOAD:
5566 method = "Reload";
5567 break;
5568
5569 case ACTION_REEXEC:
5570 method = "Reexecute";
5571 break;
5572
5573 case ACTION_SYSTEMCTL:
5574 method = streq(argv[0], "daemon-reexec") ? "Reexecute" :
5575 /* "daemon-reload" */ "Reload";
5576 break;
5577
5578 default:
5579 assert_not_reached("Unexpected action");
5580 }
5581
5582 r = sd_bus_message_new_method_call(
5583 bus,
5584 &m,
5585 "org.freedesktop.systemd1",
5586 "/org/freedesktop/systemd1",
5587 "org.freedesktop.systemd1.Manager",
5588 method);
5589 if (r < 0)
5590 return bus_log_create_error(r);
5591
5592 /* Note we use an extra-long timeout here. This is because a reload or reexec means generators are rerun which
5593 * are timed out after DEFAULT_TIMEOUT_USEC. Let's use twice that time here, so that the generators can have
5594 * their timeout, and for everything else there's the same time budget in place. */
5595
5596 r = sd_bus_call(bus, m, DEFAULT_TIMEOUT_USEC * 2, &error, NULL);
5597
5598 /* On reexecution, we expect a disconnect, not a reply */
5599 if (IN_SET(r, -ETIMEDOUT, -ECONNRESET) && streq(method, "Reexecute"))
5600 r = 0;
5601
5602 if (r < 0 && arg_action == ACTION_SYSTEMCTL)
5603 return log_error_errno(r, "Failed to reload daemon: %s", bus_error_message(&error, r));
5604
5605 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
5606 * old ways of doing things, hence don't log any error in that case here. */
5607
5608 return r < 0 ? r : 0;
5609 }
5610
5611 static int trivial_method(int argc, char *argv[], void *userdata) {
5612 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5613 const char *method;
5614 sd_bus *bus;
5615 int r;
5616
5617 if (arg_dry_run)
5618 return 0;
5619
5620 r = acquire_bus(BUS_MANAGER, &bus);
5621 if (r < 0)
5622 return r;
5623
5624 polkit_agent_open_maybe();
5625
5626 method =
5627 streq(argv[0], "clear-jobs") ||
5628 streq(argv[0], "cancel") ? "ClearJobs" :
5629 streq(argv[0], "reset-failed") ? "ResetFailed" :
5630 streq(argv[0], "halt") ? "Halt" :
5631 streq(argv[0], "reboot") ? "Reboot" :
5632 streq(argv[0], "kexec") ? "KExec" :
5633 streq(argv[0], "exit") ? "Exit" :
5634 /* poweroff */ "PowerOff";
5635
5636 r = sd_bus_call_method(
5637 bus,
5638 "org.freedesktop.systemd1",
5639 "/org/freedesktop/systemd1",
5640 "org.freedesktop.systemd1.Manager",
5641 method,
5642 &error,
5643 NULL,
5644 NULL);
5645 if (r < 0 && arg_action == ACTION_SYSTEMCTL)
5646 return log_error_errno(r, "Failed to execute operation: %s", bus_error_message(&error, r));
5647
5648 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
5649 * old ways of doing things, hence don't log any error in that case here. */
5650
5651 return r < 0 ? r : 0;
5652 }
5653
5654 static int reset_failed(int argc, char *argv[], void *userdata) {
5655 _cleanup_strv_free_ char **names = NULL;
5656 sd_bus *bus;
5657 char **name;
5658 int r, q;
5659
5660 if (argc <= 1)
5661 return trivial_method(argc, argv, userdata);
5662
5663 r = acquire_bus(BUS_MANAGER, &bus);
5664 if (r < 0)
5665 return r;
5666
5667 polkit_agent_open_maybe();
5668
5669 r = expand_names(bus, strv_skip(argv, 1), NULL, &names);
5670 if (r < 0)
5671 return log_error_errno(r, "Failed to expand names: %m");
5672
5673 STRV_FOREACH(name, names) {
5674 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5675
5676 q = sd_bus_call_method(
5677 bus,
5678 "org.freedesktop.systemd1",
5679 "/org/freedesktop/systemd1",
5680 "org.freedesktop.systemd1.Manager",
5681 "ResetFailedUnit",
5682 &error,
5683 NULL,
5684 "s", *name);
5685 if (q < 0) {
5686 log_error_errno(q, "Failed to reset failed state of unit %s: %s", *name, bus_error_message(&error, q));
5687 if (r == 0)
5688 r = q;
5689 }
5690 }
5691
5692 return r;
5693 }
5694
5695 static int print_variable(const char *s) {
5696 const char *sep;
5697 _cleanup_free_ char *esc = NULL;
5698
5699 sep = strchr(s, '=');
5700 if (!sep)
5701 return log_error_errno(SYNTHETIC_ERRNO(EUCLEAN),
5702 "Invalid environment block");
5703
5704 esc = shell_maybe_quote(sep + 1, ESCAPE_POSIX);
5705 if (!esc)
5706 return log_oom();
5707
5708 printf("%.*s=%s\n", (int)(sep-s), s, esc);
5709 return 0;
5710 }
5711
5712 static int show_environment(int argc, char *argv[], void *userdata) {
5713 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5714 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
5715 const char *text;
5716 sd_bus *bus;
5717 int r;
5718
5719 r = acquire_bus(BUS_MANAGER, &bus);
5720 if (r < 0)
5721 return r;
5722
5723 (void) pager_open(arg_pager_flags);
5724
5725 r = sd_bus_get_property(
5726 bus,
5727 "org.freedesktop.systemd1",
5728 "/org/freedesktop/systemd1",
5729 "org.freedesktop.systemd1.Manager",
5730 "Environment",
5731 &error,
5732 &reply,
5733 "as");
5734 if (r < 0)
5735 return log_error_errno(r, "Failed to get environment: %s", bus_error_message(&error, r));
5736
5737 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "s");
5738 if (r < 0)
5739 return bus_log_parse_error(r);
5740
5741 while ((r = sd_bus_message_read_basic(reply, SD_BUS_TYPE_STRING, &text)) > 0) {
5742 r = print_variable(text);
5743 if (r < 0)
5744 return r;
5745 }
5746 if (r < 0)
5747 return bus_log_parse_error(r);
5748
5749 r = sd_bus_message_exit_container(reply);
5750 if (r < 0)
5751 return bus_log_parse_error(r);
5752
5753 return 0;
5754 }
5755
5756 static int switch_root(int argc, char *argv[], void *userdata) {
5757 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5758 _cleanup_free_ char *cmdline_init = NULL;
5759 const char *root, *init;
5760 sd_bus *bus;
5761 int r;
5762
5763 if (arg_transport != BUS_TRANSPORT_LOCAL) {
5764 log_error("Cannot switch root remotely.");
5765 return -EINVAL;
5766 }
5767
5768 if (argc < 2 || argc > 3) {
5769 log_error("Wrong number of arguments.");
5770 return -EINVAL;
5771 }
5772
5773 root = argv[1];
5774
5775 if (argc >= 3)
5776 init = argv[2];
5777 else {
5778 r = proc_cmdline_get_key("init", 0, &cmdline_init);
5779 if (r < 0)
5780 log_debug_errno(r, "Failed to parse /proc/cmdline: %m");
5781
5782 init = cmdline_init;
5783 }
5784
5785 init = empty_to_null(init);
5786 if (init) {
5787 const char *root_systemd_path = NULL, *root_init_path = NULL;
5788
5789 root_systemd_path = strjoina(root, "/" SYSTEMD_BINARY_PATH);
5790 root_init_path = strjoina(root, "/", init);
5791
5792 /* If the passed init is actually the same as the
5793 * systemd binary, then let's suppress it. */
5794 if (files_same(root_init_path, root_systemd_path, 0) > 0)
5795 init = NULL;
5796 }
5797
5798 /* Instruct PID1 to exclude us from its killing spree applied during
5799 * the transition. Otherwise we would exit with a failure status even
5800 * though the switch to the new root has succeed. */
5801 argv_cmdline[0] = '@';
5802
5803 r = acquire_bus(BUS_MANAGER, &bus);
5804 if (r < 0)
5805 return r;
5806
5807 /* If we are slow to exit after the root switch, the new systemd instance
5808 * will send us a signal to terminate. Just ignore it and exit normally.
5809 * This way the unit does not end up as failed.
5810 */
5811 r = ignore_signals(SIGTERM, -1);
5812 if (r < 0)
5813 log_warning_errno(r, "Failed to change disposition of SIGTERM to ignore: %m");
5814
5815 log_debug("Switching root - root: %s; init: %s", root, strna(init));
5816
5817 r = sd_bus_call_method(
5818 bus,
5819 "org.freedesktop.systemd1",
5820 "/org/freedesktop/systemd1",
5821 "org.freedesktop.systemd1.Manager",
5822 "SwitchRoot",
5823 &error,
5824 NULL,
5825 "ss", root, init);
5826 if (r < 0) {
5827 (void) default_signals(SIGTERM, -1);
5828
5829 return log_error_errno(r, "Failed to switch root: %s", bus_error_message(&error, r));
5830 }
5831
5832 return 0;
5833 }
5834
5835 static int set_environment(int argc, char *argv[], void *userdata) {
5836 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5837 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
5838 const char *method;
5839 sd_bus *bus;
5840 int r;
5841
5842 assert(argc > 1);
5843 assert(argv);
5844
5845 r = acquire_bus(BUS_MANAGER, &bus);
5846 if (r < 0)
5847 return r;
5848
5849 polkit_agent_open_maybe();
5850
5851 method = streq(argv[0], "set-environment")
5852 ? "SetEnvironment"
5853 : "UnsetEnvironment";
5854
5855 r = sd_bus_message_new_method_call(
5856 bus,
5857 &m,
5858 "org.freedesktop.systemd1",
5859 "/org/freedesktop/systemd1",
5860 "org.freedesktop.systemd1.Manager",
5861 method);
5862 if (r < 0)
5863 return bus_log_create_error(r);
5864
5865 r = sd_bus_message_append_strv(m, strv_skip(argv, 1));
5866 if (r < 0)
5867 return bus_log_create_error(r);
5868
5869 r = sd_bus_call(bus, m, 0, &error, NULL);
5870 if (r < 0)
5871 return log_error_errno(r, "Failed to set environment: %s", bus_error_message(&error, r));
5872
5873 return 0;
5874 }
5875
5876 static int import_environment(int argc, char *argv[], void *userdata) {
5877 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5878 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
5879 sd_bus *bus;
5880 int r;
5881
5882 r = acquire_bus(BUS_MANAGER, &bus);
5883 if (r < 0)
5884 return r;
5885
5886 polkit_agent_open_maybe();
5887
5888 r = sd_bus_message_new_method_call(
5889 bus,
5890 &m,
5891 "org.freedesktop.systemd1",
5892 "/org/freedesktop/systemd1",
5893 "org.freedesktop.systemd1.Manager",
5894 "SetEnvironment");
5895 if (r < 0)
5896 return bus_log_create_error(r);
5897
5898 if (argc < 2)
5899 r = sd_bus_message_append_strv(m, environ);
5900 else {
5901 char **a, **b;
5902
5903 r = sd_bus_message_open_container(m, 'a', "s");
5904 if (r < 0)
5905 return bus_log_create_error(r);
5906
5907 STRV_FOREACH(a, strv_skip(argv, 1)) {
5908
5909 if (!env_name_is_valid(*a)) {
5910 log_error("Not a valid environment variable name: %s", *a);
5911 return -EINVAL;
5912 }
5913
5914 STRV_FOREACH(b, environ) {
5915 const char *eq;
5916
5917 eq = startswith(*b, *a);
5918 if (eq && *eq == '=') {
5919
5920 r = sd_bus_message_append(m, "s", *b);
5921 if (r < 0)
5922 return bus_log_create_error(r);
5923
5924 break;
5925 }
5926 }
5927 }
5928
5929 r = sd_bus_message_close_container(m);
5930 }
5931 if (r < 0)
5932 return bus_log_create_error(r);
5933
5934 r = sd_bus_call(bus, m, 0, &error, NULL);
5935 if (r < 0)
5936 return log_error_errno(r, "Failed to import environment: %s", bus_error_message(&error, r));
5937
5938 return 0;
5939 }
5940
5941 static int enable_sysv_units(const char *verb, char **args) {
5942 int r = 0;
5943
5944 #if HAVE_SYSV_COMPAT
5945 _cleanup_(lookup_paths_free) LookupPaths paths = {};
5946 unsigned f = 0;
5947
5948 /* Processes all SysV units, and reshuffles the array so that afterwards only the native units remain */
5949
5950 if (arg_scope != UNIT_FILE_SYSTEM)
5951 return 0;
5952
5953 if (getenv_bool("SYSTEMCTL_SKIP_SYSV") > 0)
5954 return 0;
5955
5956 if (!STR_IN_SET(verb,
5957 "enable",
5958 "disable",
5959 "is-enabled"))
5960 return 0;
5961
5962 r = lookup_paths_init(&paths, arg_scope, LOOKUP_PATHS_EXCLUDE_GENERATED, arg_root);
5963 if (r < 0)
5964 return r;
5965
5966 r = 0;
5967 while (args[f]) {
5968
5969 const char *argv[] = {
5970 ROOTLIBEXECDIR "/systemd-sysv-install",
5971 NULL,
5972 NULL,
5973 NULL,
5974 NULL,
5975 };
5976
5977 _cleanup_free_ char *p = NULL, *q = NULL, *l = NULL;
5978 bool found_native = false, found_sysv;
5979 const char *name;
5980 unsigned c = 1;
5981 pid_t pid;
5982 int j;
5983
5984 name = args[f++];
5985
5986 if (!endswith(name, ".service"))
5987 continue;
5988
5989 if (path_is_absolute(name))
5990 continue;
5991
5992 j = unit_file_exists(arg_scope, &paths, name);
5993 if (j < 0 && !IN_SET(j, -ELOOP, -ERFKILL, -EADDRNOTAVAIL))
5994 return log_error_errno(j, "Failed to lookup unit file state: %m");
5995 found_native = j != 0;
5996
5997 /* If we have both a native unit and a SysV script, enable/disable them both (below); for is-enabled,
5998 * prefer the native unit */
5999 if (found_native && streq(verb, "is-enabled"))
6000 continue;
6001
6002 p = path_join(arg_root, SYSTEM_SYSVINIT_PATH, name);
6003 if (!p)
6004 return log_oom();
6005
6006 p[strlen(p) - STRLEN(".service")] = 0;
6007 found_sysv = access(p, F_OK) >= 0;
6008 if (!found_sysv)
6009 continue;
6010
6011 if (!arg_quiet) {
6012 if (found_native)
6013 log_info("Synchronizing state of %s with SysV service script with %s.", name, argv[0]);
6014 else
6015 log_info("%s is not a native service, redirecting to systemd-sysv-install.", name);
6016 }
6017
6018 if (!isempty(arg_root))
6019 argv[c++] = q = strappend("--root=", arg_root);
6020
6021 argv[c++] = verb;
6022 argv[c++] = basename(p);
6023 argv[c] = NULL;
6024
6025 l = strv_join((char**)argv, " ");
6026 if (!l)
6027 return log_oom();
6028
6029 if (!arg_quiet)
6030 log_info("Executing: %s", l);
6031
6032 j = safe_fork("(sysv-install)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_LOG, &pid);
6033 if (j < 0)
6034 return j;
6035 if (j == 0) {
6036 /* Child */
6037 execv(argv[0], (char**) argv);
6038 log_error_errno(errno, "Failed to execute %s: %m", argv[0]);
6039 _exit(EXIT_FAILURE);
6040 }
6041
6042 j = wait_for_terminate_and_check("sysv-install", pid, WAIT_LOG_ABNORMAL);
6043 if (j < 0)
6044 return j;
6045 if (streq(verb, "is-enabled")) {
6046 if (j == EXIT_SUCCESS) {
6047 if (!arg_quiet)
6048 puts("enabled");
6049 r = 1;
6050 } else {
6051 if (!arg_quiet)
6052 puts("disabled");
6053 }
6054
6055 } else if (j != EXIT_SUCCESS)
6056 return -EBADE; /* We don't warn here, under the assumption the script already showed an explanation */
6057
6058 if (found_native)
6059 continue;
6060
6061 /* Remove this entry, so that we don't try enabling it as native unit */
6062 assert(f > 0);
6063 f--;
6064 assert(args[f] == name);
6065 strv_remove(args, name);
6066 }
6067
6068 #endif
6069 return r;
6070 }
6071
6072 static int mangle_names(char **original_names, char ***mangled_names) {
6073 char **i, **l, **name;
6074 int r;
6075
6076 l = i = new(char*, strv_length(original_names) + 1);
6077 if (!l)
6078 return log_oom();
6079
6080 STRV_FOREACH(name, original_names) {
6081
6082 /* When enabling units qualified path names are OK,
6083 * too, hence allow them explicitly. */
6084
6085 if (is_path(*name)) {
6086 *i = strdup(*name);
6087 if (!*i) {
6088 strv_free(l);
6089 return log_oom();
6090 }
6091 } else {
6092 r = unit_name_mangle(*name, arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, i);
6093 if (r < 0) {
6094 *i = NULL;
6095 strv_free(l);
6096 return log_error_errno(r, "Failed to mangle unit name: %m");
6097 }
6098 }
6099
6100 i++;
6101 }
6102
6103 *i = NULL;
6104 *mangled_names = l;
6105
6106 return 0;
6107 }
6108
6109 static int normalize_filenames(char **names) {
6110 char **u;
6111 int r;
6112
6113 STRV_FOREACH(u, names)
6114 if (!path_is_absolute(*u)) {
6115 char* normalized_path;
6116
6117 if (!isempty(arg_root))
6118 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
6119 "Non-absolute paths are not allowed when --root is used: %s",
6120 *u);
6121
6122 if (!strchr(*u,'/'))
6123 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
6124 "Link argument does contain at least one directory separator: %s",
6125 *u);
6126
6127 r = path_make_absolute_cwd(*u, &normalized_path);
6128 if (r < 0)
6129 return r;
6130
6131 free_and_replace(*u, normalized_path);
6132 }
6133
6134 return 0;
6135 }
6136
6137 static int normalize_names(char **names, bool warn_if_path) {
6138 char **u;
6139 bool was_path = false;
6140
6141 STRV_FOREACH(u, names) {
6142 int r;
6143
6144 if (!is_path(*u))
6145 continue;
6146
6147 r = free_and_strdup(u, basename(*u));
6148 if (r < 0)
6149 return log_error_errno(r, "Failed to normalize unit file path: %m");
6150
6151 was_path = true;
6152 }
6153
6154 if (warn_if_path && was_path)
6155 log_warning("Warning: Can't execute disable on the unit file path. Proceeding with the unit name.");
6156
6157 return 0;
6158 }
6159
6160 static int unit_exists(LookupPaths *lp, const char *unit) {
6161 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6162 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
6163 _cleanup_free_ char *path = NULL;
6164 static const struct bus_properties_map property_map[] = {
6165 { "LoadState", "s", NULL, offsetof(UnitStatusInfo, load_state) },
6166 { "ActiveState", "s", NULL, offsetof(UnitStatusInfo, active_state)},
6167 {},
6168 };
6169 UnitStatusInfo info = {};
6170 sd_bus *bus;
6171 int r;
6172
6173 if (unit_name_is_valid(unit, UNIT_NAME_TEMPLATE))
6174 return unit_find_template_path(unit, lp, NULL, NULL);
6175
6176 path = unit_dbus_path_from_name(unit);
6177 if (!path)
6178 return log_oom();
6179
6180 r = acquire_bus(BUS_MANAGER, &bus);
6181 if (r < 0)
6182 return r;
6183
6184 r = bus_map_all_properties(bus, "org.freedesktop.systemd1", path, property_map, 0, &error, &m, &info);
6185 if (r < 0)
6186 return log_error_errno(r, "Failed to get properties: %s", bus_error_message(&error, r));
6187
6188 return !streq_ptr(info.load_state, "not-found") || !streq_ptr(info.active_state, "inactive");
6189 }
6190
6191 static int enable_unit(int argc, char *argv[], void *userdata) {
6192 _cleanup_strv_free_ char **names = NULL;
6193 const char *verb = argv[0];
6194 UnitFileChange *changes = NULL;
6195 size_t n_changes = 0;
6196 int carries_install_info = -1;
6197 bool ignore_carries_install_info = arg_quiet;
6198 int r;
6199
6200 if (!argv[1])
6201 return 0;
6202
6203 r = mangle_names(strv_skip(argv, 1), &names);
6204 if (r < 0)
6205 return r;
6206
6207 r = enable_sysv_units(verb, names);
6208 if (r < 0)
6209 return r;
6210
6211 /* If the operation was fully executed by the SysV compat, let's finish early */
6212 if (strv_isempty(names)) {
6213 if (arg_no_reload || install_client_side())
6214 return 0;
6215 return daemon_reload(argc, argv, userdata);
6216 }
6217
6218 if (streq(verb, "disable")) {
6219 r = normalize_names(names, true);
6220 if (r < 0)
6221 return r;
6222 }
6223
6224 if (streq(verb, "link")) {
6225 r = normalize_filenames(names);
6226 if (r < 0)
6227 return r;
6228 }
6229
6230 if (install_client_side()) {
6231 UnitFileFlags flags;
6232
6233 flags = args_to_flags();
6234 if (streq(verb, "enable")) {
6235 r = unit_file_enable(arg_scope, flags, arg_root, names, &changes, &n_changes);
6236 carries_install_info = r;
6237 } else if (streq(verb, "disable"))
6238 r = unit_file_disable(arg_scope, flags, arg_root, names, &changes, &n_changes);
6239 else if (streq(verb, "reenable")) {
6240 r = unit_file_reenable(arg_scope, flags, arg_root, names, &changes, &n_changes);
6241 carries_install_info = r;
6242 } else if (streq(verb, "link"))
6243 r = unit_file_link(arg_scope, flags, arg_root, names, &changes, &n_changes);
6244 else if (streq(verb, "preset")) {
6245 r = unit_file_preset(arg_scope, flags, arg_root, names, arg_preset_mode, &changes, &n_changes);
6246 } else if (streq(verb, "mask"))
6247 r = unit_file_mask(arg_scope, flags, arg_root, names, &changes, &n_changes);
6248 else if (streq(verb, "unmask"))
6249 r = unit_file_unmask(arg_scope, flags, arg_root, names, &changes, &n_changes);
6250 else if (streq(verb, "revert"))
6251 r = unit_file_revert(arg_scope, arg_root, names, &changes, &n_changes);
6252 else
6253 assert_not_reached("Unknown verb");
6254
6255 unit_file_dump_changes(r, verb, changes, n_changes, arg_quiet);
6256 if (r < 0)
6257 goto finish;
6258 r = 0;
6259 } else {
6260 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL, *m = NULL;
6261 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6262 bool expect_carries_install_info = false;
6263 bool send_runtime = true, send_force = true, send_preset_mode = false;
6264 const char *method;
6265 sd_bus *bus;
6266
6267 if (STR_IN_SET(verb, "mask", "unmask")) {
6268 char **name;
6269 _cleanup_(lookup_paths_free) LookupPaths lp = {};
6270
6271 r = lookup_paths_init(&lp, arg_scope, 0, arg_root);
6272 if (r < 0)
6273 return r;
6274
6275 STRV_FOREACH(name, names) {
6276 r = unit_exists(&lp, *name);
6277 if (r < 0)
6278 return r;
6279 if (r == 0)
6280 log_notice("Unit %s does not exist, proceeding anyway.", *name);
6281 }
6282 }
6283
6284 r = acquire_bus(BUS_MANAGER, &bus);
6285 if (r < 0)
6286 return r;
6287
6288 polkit_agent_open_maybe();
6289
6290 if (streq(verb, "enable")) {
6291 method = "EnableUnitFiles";
6292 expect_carries_install_info = true;
6293 } else if (streq(verb, "disable")) {
6294 method = "DisableUnitFiles";
6295 send_force = false;
6296 } else if (streq(verb, "reenable")) {
6297 method = "ReenableUnitFiles";
6298 expect_carries_install_info = true;
6299 } else if (streq(verb, "link"))
6300 method = "LinkUnitFiles";
6301 else if (streq(verb, "preset")) {
6302
6303 if (arg_preset_mode != UNIT_FILE_PRESET_FULL) {
6304 method = "PresetUnitFilesWithMode";
6305 send_preset_mode = true;
6306 } else
6307 method = "PresetUnitFiles";
6308
6309 expect_carries_install_info = true;
6310 ignore_carries_install_info = true;
6311 } else if (streq(verb, "mask"))
6312 method = "MaskUnitFiles";
6313 else if (streq(verb, "unmask")) {
6314 method = "UnmaskUnitFiles";
6315 send_force = false;
6316 } else if (streq(verb, "revert")) {
6317 method = "RevertUnitFiles";
6318 send_runtime = send_force = false;
6319 } else
6320 assert_not_reached("Unknown verb");
6321
6322 r = sd_bus_message_new_method_call(
6323 bus,
6324 &m,
6325 "org.freedesktop.systemd1",
6326 "/org/freedesktop/systemd1",
6327 "org.freedesktop.systemd1.Manager",
6328 method);
6329 if (r < 0)
6330 return bus_log_create_error(r);
6331
6332 r = sd_bus_message_append_strv(m, names);
6333 if (r < 0)
6334 return bus_log_create_error(r);
6335
6336 if (send_preset_mode) {
6337 r = sd_bus_message_append(m, "s", unit_file_preset_mode_to_string(arg_preset_mode));
6338 if (r < 0)
6339 return bus_log_create_error(r);
6340 }
6341
6342 if (send_runtime) {
6343 r = sd_bus_message_append(m, "b", arg_runtime);
6344 if (r < 0)
6345 return bus_log_create_error(r);
6346 }
6347
6348 if (send_force) {
6349 r = sd_bus_message_append(m, "b", arg_force);
6350 if (r < 0)
6351 return bus_log_create_error(r);
6352 }
6353
6354 r = sd_bus_call(bus, m, 0, &error, &reply);
6355 if (r < 0)
6356 return log_error_errno(r, "Failed to %s unit: %s", verb, bus_error_message(&error, r));
6357
6358 if (expect_carries_install_info) {
6359 r = sd_bus_message_read(reply, "b", &carries_install_info);
6360 if (r < 0)
6361 return bus_log_parse_error(r);
6362 }
6363
6364 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
6365 if (r < 0)
6366 goto finish;
6367
6368 /* Try to reload if enabled */
6369 if (!arg_no_reload)
6370 r = daemon_reload(argc, argv, userdata);
6371 else
6372 r = 0;
6373 }
6374
6375 if (carries_install_info == 0 && !ignore_carries_install_info)
6376 log_notice("The unit files have no installation config (WantedBy=, RequiredBy=, Also=,\n"
6377 "Alias= settings in the [Install] section, and DefaultInstance= for template\n"
6378 "units). This means they are not meant to be enabled using systemctl.\n \n"
6379 "Possible reasons for having this kind of units are:\n"
6380 "%1$s A unit may be statically enabled by being symlinked from another unit's\n"
6381 " .wants/ or .requires/ directory.\n"
6382 "%1$s A unit's purpose may be to act as a helper for some other unit which has\n"
6383 " a requirement dependency on it.\n"
6384 "%1$s A unit may be started when needed via activation (socket, path, timer,\n"
6385 " D-Bus, udev, scripted systemctl call, ...).\n"
6386 "%1$s In case of template units, the unit is meant to be enabled with some\n"
6387 " instance name specified.",
6388 special_glyph(BULLET));
6389
6390 if (arg_now && STR_IN_SET(argv[0], "enable", "disable", "mask")) {
6391 sd_bus *bus;
6392 size_t len, i;
6393
6394 r = acquire_bus(BUS_MANAGER, &bus);
6395 if (r < 0)
6396 goto finish;
6397
6398 len = strv_length(names);
6399 {
6400 char *new_args[len + 2];
6401
6402 new_args[0] = (char*) (streq(argv[0], "enable") ? "start" : "stop");
6403 for (i = 0; i < len; i++)
6404 new_args[i + 1] = basename(names[i]);
6405 new_args[i + 1] = NULL;
6406
6407 r = start_unit(len + 1, new_args, userdata);
6408 }
6409 }
6410
6411 finish:
6412 unit_file_changes_free(changes, n_changes);
6413
6414 return r;
6415 }
6416
6417 static int add_dependency(int argc, char *argv[], void *userdata) {
6418 _cleanup_strv_free_ char **names = NULL;
6419 _cleanup_free_ char *target = NULL;
6420 const char *verb = argv[0];
6421 UnitFileChange *changes = NULL;
6422 size_t n_changes = 0;
6423 UnitDependency dep;
6424 int r = 0;
6425
6426 if (!argv[1])
6427 return 0;
6428
6429 r = unit_name_mangle_with_suffix(argv[1], arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, ".target", &target);
6430 if (r < 0)
6431 return log_error_errno(r, "Failed to mangle unit name: %m");
6432
6433 r = mangle_names(strv_skip(argv, 2), &names);
6434 if (r < 0)
6435 return r;
6436
6437 if (streq(verb, "add-wants"))
6438 dep = UNIT_WANTS;
6439 else if (streq(verb, "add-requires"))
6440 dep = UNIT_REQUIRES;
6441 else
6442 assert_not_reached("Unknown verb");
6443
6444 if (install_client_side()) {
6445 r = unit_file_add_dependency(arg_scope, args_to_flags(), arg_root, names, target, dep, &changes, &n_changes);
6446 unit_file_dump_changes(r, "add dependency on", changes, n_changes, arg_quiet);
6447
6448 if (r > 0)
6449 r = 0;
6450 } else {
6451 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL, *m = NULL;
6452 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6453 sd_bus *bus;
6454
6455 r = acquire_bus(BUS_MANAGER, &bus);
6456 if (r < 0)
6457 return r;
6458
6459 polkit_agent_open_maybe();
6460
6461 r = sd_bus_message_new_method_call(
6462 bus,
6463 &m,
6464 "org.freedesktop.systemd1",
6465 "/org/freedesktop/systemd1",
6466 "org.freedesktop.systemd1.Manager",
6467 "AddDependencyUnitFiles");
6468 if (r < 0)
6469 return bus_log_create_error(r);
6470
6471 r = sd_bus_message_append_strv(m, names);
6472 if (r < 0)
6473 return bus_log_create_error(r);
6474
6475 r = sd_bus_message_append(m, "ssbb", target, unit_dependency_to_string(dep), arg_runtime, arg_force);
6476 if (r < 0)
6477 return bus_log_create_error(r);
6478
6479 r = sd_bus_call(bus, m, 0, &error, &reply);
6480 if (r < 0)
6481 return log_error_errno(r, "Failed to add dependency: %s", bus_error_message(&error, r));
6482
6483 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
6484 if (r < 0)
6485 goto finish;
6486
6487 if (arg_no_reload) {
6488 r = 0;
6489 goto finish;
6490 }
6491
6492 r = daemon_reload(argc, argv, userdata);
6493 }
6494
6495 finish:
6496 unit_file_changes_free(changes, n_changes);
6497
6498 return r;
6499 }
6500
6501 static int preset_all(int argc, char *argv[], void *userdata) {
6502 UnitFileChange *changes = NULL;
6503 size_t n_changes = 0;
6504 int r;
6505
6506 if (install_client_side()) {
6507 r = unit_file_preset_all(arg_scope, args_to_flags(), arg_root, arg_preset_mode, &changes, &n_changes);
6508 unit_file_dump_changes(r, "preset", changes, n_changes, arg_quiet);
6509
6510 if (r > 0)
6511 r = 0;
6512 } else {
6513 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6514 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
6515 sd_bus *bus;
6516
6517 r = acquire_bus(BUS_MANAGER, &bus);
6518 if (r < 0)
6519 return r;
6520
6521 polkit_agent_open_maybe();
6522
6523 r = sd_bus_call_method(
6524 bus,
6525 "org.freedesktop.systemd1",
6526 "/org/freedesktop/systemd1",
6527 "org.freedesktop.systemd1.Manager",
6528 "PresetAllUnitFiles",
6529 &error,
6530 &reply,
6531 "sbb",
6532 unit_file_preset_mode_to_string(arg_preset_mode),
6533 arg_runtime,
6534 arg_force);
6535 if (r < 0)
6536 return log_error_errno(r, "Failed to preset all units: %s", bus_error_message(&error, r));
6537
6538 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
6539 if (r < 0)
6540 goto finish;
6541
6542 if (arg_no_reload) {
6543 r = 0;
6544 goto finish;
6545 }
6546
6547 r = daemon_reload(argc, argv, userdata);
6548 }
6549
6550 finish:
6551 unit_file_changes_free(changes, n_changes);
6552
6553 return r;
6554 }
6555
6556 static int show_installation_targets_client_side(const char *name) {
6557 UnitFileChange *changes = NULL;
6558 size_t n_changes = 0, i;
6559 UnitFileFlags flags;
6560 char **p;
6561 int r;
6562
6563 p = STRV_MAKE(name);
6564 flags = UNIT_FILE_DRY_RUN |
6565 (arg_runtime ? UNIT_FILE_RUNTIME : 0);
6566
6567 r = unit_file_disable(UNIT_FILE_SYSTEM, flags, NULL, p, &changes, &n_changes);
6568 if (r < 0)
6569 return log_error_errno(r, "Failed to get file links for %s: %m", name);
6570
6571 for (i = 0; i < n_changes; i++)
6572 if (changes[i].type == UNIT_FILE_UNLINK)
6573 printf(" %s\n", changes[i].path);
6574
6575 return 0;
6576 }
6577
6578 static int show_installation_targets(sd_bus *bus, const char *name) {
6579 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
6580 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6581 const char *link;
6582 int r;
6583
6584 r = sd_bus_call_method(
6585 bus,
6586 "org.freedesktop.systemd1",
6587 "/org/freedesktop/systemd1",
6588 "org.freedesktop.systemd1.Manager",
6589 "GetUnitFileLinks",
6590 &error,
6591 &reply,
6592 "sb", name, arg_runtime);
6593 if (r < 0)
6594 return log_error_errno(r, "Failed to get unit file links for %s: %s", name, bus_error_message(&error, r));
6595
6596 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "s");
6597 if (r < 0)
6598 return bus_log_parse_error(r);
6599
6600 while ((r = sd_bus_message_read(reply, "s", &link)) > 0)
6601 printf(" %s\n", link);
6602
6603 if (r < 0)
6604 return bus_log_parse_error(r);
6605
6606 r = sd_bus_message_exit_container(reply);
6607 if (r < 0)
6608 return bus_log_parse_error(r);
6609
6610 return 0;
6611 }
6612
6613 static int unit_is_enabled(int argc, char *argv[], void *userdata) {
6614 _cleanup_strv_free_ char **names = NULL;
6615 bool enabled;
6616 char **name;
6617 int r;
6618
6619 r = mangle_names(strv_skip(argv, 1), &names);
6620 if (r < 0)
6621 return r;
6622
6623 r = enable_sysv_units(argv[0], names);
6624 if (r < 0)
6625 return r;
6626
6627 enabled = r > 0;
6628
6629 if (install_client_side()) {
6630 STRV_FOREACH(name, names) {
6631 UnitFileState state;
6632
6633 r = unit_file_get_state(arg_scope, arg_root, *name, &state);
6634 if (r < 0)
6635 return log_error_errno(r, "Failed to get unit file state for %s: %m", *name);
6636
6637 if (IN_SET(state,
6638 UNIT_FILE_ENABLED,
6639 UNIT_FILE_ENABLED_RUNTIME,
6640 UNIT_FILE_STATIC,
6641 UNIT_FILE_INDIRECT,
6642 UNIT_FILE_GENERATED))
6643 enabled = true;
6644
6645 if (!arg_quiet) {
6646 puts(unit_file_state_to_string(state));
6647 if (arg_full) {
6648 r = show_installation_targets_client_side(*name);
6649 if (r < 0)
6650 return r;
6651 }
6652 }
6653 }
6654
6655 r = 0;
6656 } else {
6657 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6658 sd_bus *bus;
6659
6660 r = acquire_bus(BUS_MANAGER, &bus);
6661 if (r < 0)
6662 return r;
6663
6664 STRV_FOREACH(name, names) {
6665 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
6666 const char *s;
6667
6668 r = sd_bus_call_method(
6669 bus,
6670 "org.freedesktop.systemd1",
6671 "/org/freedesktop/systemd1",
6672 "org.freedesktop.systemd1.Manager",
6673 "GetUnitFileState",
6674 &error,
6675 &reply,
6676 "s", *name);
6677 if (r < 0)
6678 return log_error_errno(r, "Failed to get unit file state for %s: %s", *name, bus_error_message(&error, r));
6679
6680 r = sd_bus_message_read(reply, "s", &s);
6681 if (r < 0)
6682 return bus_log_parse_error(r);
6683
6684 if (STR_IN_SET(s, "enabled", "enabled-runtime", "static", "indirect", "generated"))
6685 enabled = true;
6686
6687 if (!arg_quiet) {
6688 puts(s);
6689 if (arg_full) {
6690 r = show_installation_targets(bus, *name);
6691 if (r < 0)
6692 return r;
6693 }
6694 }
6695 }
6696 }
6697
6698 return enabled ? EXIT_SUCCESS : EXIT_FAILURE;
6699 }
6700
6701 static int match_startup_finished(sd_bus_message *m, void *userdata, sd_bus_error *error) {
6702 char **state = userdata;
6703 int r;
6704
6705 assert(state);
6706
6707 r = sd_bus_get_property_string(
6708 sd_bus_message_get_bus(m),
6709 "org.freedesktop.systemd1",
6710 "/org/freedesktop/systemd1",
6711 "org.freedesktop.systemd1.Manager",
6712 "SystemState",
6713 NULL,
6714 state);
6715
6716 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m)), r);
6717 return 0;
6718 }
6719
6720 static int is_system_running(int argc, char *argv[], void *userdata) {
6721 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6722 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot_startup_finished = NULL;
6723 _cleanup_(sd_event_unrefp) sd_event* event = NULL;
6724 _cleanup_free_ char *state = NULL;
6725 sd_bus *bus;
6726 int r;
6727
6728 if (running_in_chroot() > 0 || (arg_transport == BUS_TRANSPORT_LOCAL && !sd_booted())) {
6729 if (!arg_quiet)
6730 puts("offline");
6731 return EXIT_FAILURE;
6732 }
6733
6734 r = acquire_bus(BUS_MANAGER, &bus);
6735 if (r < 0)
6736 return r;
6737
6738 if (arg_wait) {
6739 r = sd_event_default(&event);
6740 if (r >= 0)
6741 r = sd_bus_attach_event(bus, event, 0);
6742 if (r >= 0)
6743 r = sd_bus_match_signal_async(
6744 bus,
6745 &slot_startup_finished,
6746 "org.freedesktop.systemd1",
6747 "/org/freedesktop/systemd1",
6748 "org.freedesktop.systemd1.Manager",
6749 "StartupFinished",
6750 match_startup_finished, NULL, &state);
6751 if (r < 0) {
6752 log_warning_errno(r, "Failed to request match for StartupFinished: %m");
6753 arg_wait = false;
6754 }
6755 }
6756
6757 r = sd_bus_get_property_string(
6758 bus,
6759 "org.freedesktop.systemd1",
6760 "/org/freedesktop/systemd1",
6761 "org.freedesktop.systemd1.Manager",
6762 "SystemState",
6763 &error,
6764 &state);
6765 if (r < 0) {
6766 log_warning_errno(r, "Failed to query system state: %s", bus_error_message(&error, r));
6767
6768 if (!arg_quiet)
6769 puts("unknown");
6770 return EXIT_FAILURE;
6771 }
6772
6773 if (arg_wait && STR_IN_SET(state, "initializing", "starting")) {
6774 r = sd_event_loop(event);
6775 if (r < 0) {
6776 log_warning_errno(r, "Failed to get property from event loop: %m");
6777 if (!arg_quiet)
6778 puts("unknown");
6779 return EXIT_FAILURE;
6780 }
6781 }
6782
6783 if (!arg_quiet)
6784 puts(state);
6785
6786 return streq(state, "running") ? EXIT_SUCCESS : EXIT_FAILURE;
6787 }
6788
6789 static int create_edit_temp_file(const char *new_path, const char *original_path, char **ret_tmp_fn) {
6790 _cleanup_free_ char *t = NULL;
6791 int r;
6792
6793 assert(new_path);
6794 assert(original_path);
6795 assert(ret_tmp_fn);
6796
6797 r = tempfn_random(new_path, NULL, &t);
6798 if (r < 0)
6799 return log_error_errno(r, "Failed to determine temporary filename for \"%s\": %m", new_path);
6800
6801 r = mkdir_parents(new_path, 0755);
6802 if (r < 0)
6803 return log_error_errno(r, "Failed to create directories for \"%s\": %m", new_path);
6804
6805 r = copy_file(original_path, t, 0, 0644, 0, COPY_REFLINK);
6806 if (r == -ENOENT) {
6807
6808 r = touch(t);
6809 if (r < 0)
6810 return log_error_errno(r, "Failed to create temporary file \"%s\": %m", t);
6811
6812 } else if (r < 0)
6813 return log_error_errno(r, "Failed to create temporary file for \"%s\": %m", new_path);
6814
6815 *ret_tmp_fn = TAKE_PTR(t);
6816
6817 return 0;
6818 }
6819
6820 static int get_file_to_edit(
6821 const LookupPaths *paths,
6822 const char *name,
6823 char **ret_path) {
6824
6825 _cleanup_free_ char *path = NULL, *run = NULL;
6826
6827 assert(name);
6828 assert(ret_path);
6829
6830 path = strjoin(paths->persistent_config, "/", name);
6831 if (!path)
6832 return log_oom();
6833
6834 if (arg_runtime) {
6835 run = strjoin(paths->runtime_config, "/", name);
6836 if (!run)
6837 return log_oom();
6838 }
6839
6840 if (arg_runtime) {
6841 if (access(path, F_OK) >= 0)
6842 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
6843 "Refusing to create \"%s\" because it would be overridden by \"%s\" anyway.",
6844 run, path);
6845
6846 *ret_path = TAKE_PTR(run);
6847 } else
6848 *ret_path = TAKE_PTR(path);
6849
6850 return 0;
6851 }
6852
6853 static int unit_file_create_new(
6854 const LookupPaths *paths,
6855 const char *unit_name,
6856 const char *suffix,
6857 char **ret_new_path,
6858 char **ret_tmp_path) {
6859
6860 _cleanup_free_ char *new_path = NULL, *tmp_path = NULL;
6861 const char *ending;
6862 int r;
6863
6864 assert(unit_name);
6865 assert(ret_new_path);
6866 assert(ret_tmp_path);
6867
6868 ending = strjoina(unit_name, suffix);
6869 r = get_file_to_edit(paths, ending, &new_path);
6870 if (r < 0)
6871 return r;
6872
6873 r = create_edit_temp_file(new_path, new_path, &tmp_path);
6874 if (r < 0)
6875 return r;
6876
6877 *ret_new_path = TAKE_PTR(new_path);
6878 *ret_tmp_path = TAKE_PTR(tmp_path);
6879
6880 return 0;
6881 }
6882
6883 static int unit_file_create_copy(
6884 const LookupPaths *paths,
6885 const char *unit_name,
6886 const char *fragment_path,
6887 char **ret_new_path,
6888 char **ret_tmp_path) {
6889
6890 _cleanup_free_ char *new_path = NULL, *tmp_path = NULL;
6891 int r;
6892
6893 assert(fragment_path);
6894 assert(unit_name);
6895 assert(ret_new_path);
6896 assert(ret_tmp_path);
6897
6898 r = get_file_to_edit(paths, unit_name, &new_path);
6899 if (r < 0)
6900 return r;
6901
6902 if (!path_equal(fragment_path, new_path) && access(new_path, F_OK) >= 0) {
6903 char response;
6904
6905 r = ask_char(&response, "yn", "\"%s\" already exists. Overwrite with \"%s\"? [(y)es, (n)o] ", new_path, fragment_path);
6906 if (r < 0)
6907 return r;
6908 if (response != 'y')
6909 return log_warning_errno(SYNTHETIC_ERRNO(EKEYREJECTED), "%s skipped.", unit_name);
6910 }
6911
6912 r = create_edit_temp_file(new_path, fragment_path, &tmp_path);
6913 if (r < 0)
6914 return r;
6915
6916 *ret_new_path = TAKE_PTR(new_path);
6917 *ret_tmp_path = TAKE_PTR(tmp_path);
6918
6919 return 0;
6920 }
6921
6922 static int run_editor(char **paths) {
6923 int r;
6924
6925 assert(paths);
6926
6927 r = safe_fork("(editor)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_LOG|FORK_WAIT, NULL);
6928 if (r < 0)
6929 return r;
6930 if (r == 0) {
6931 char **editor_args = NULL, **tmp_path, **original_path, *p;
6932 size_t n_editor_args = 0, i = 1, argc;
6933 const char **args, *editor;
6934
6935 argc = strv_length(paths)/2 + 1;
6936
6937 /* SYSTEMD_EDITOR takes precedence over EDITOR which takes precedence over VISUAL
6938 * If neither SYSTEMD_EDITOR nor EDITOR nor VISUAL are present,
6939 * we try to execute well known editors
6940 */
6941 editor = getenv("SYSTEMD_EDITOR");
6942 if (!editor)
6943 editor = getenv("EDITOR");
6944 if (!editor)
6945 editor = getenv("VISUAL");
6946
6947 if (!isempty(editor)) {
6948 editor_args = strv_split(editor, WHITESPACE);
6949 if (!editor_args) {
6950 (void) log_oom();
6951 _exit(EXIT_FAILURE);
6952 }
6953 n_editor_args = strv_length(editor_args);
6954 argc += n_editor_args - 1;
6955 }
6956
6957 args = newa(const char*, argc + 1);
6958
6959 if (n_editor_args > 0) {
6960 args[0] = editor_args[0];
6961 for (; i < n_editor_args; i++)
6962 args[i] = editor_args[i];
6963 }
6964
6965 STRV_FOREACH_PAIR(original_path, tmp_path, paths)
6966 args[i++] = *tmp_path;
6967 args[i] = NULL;
6968
6969 if (n_editor_args > 0)
6970 execvp(args[0], (char* const*) args);
6971
6972 FOREACH_STRING(p, "editor", "nano", "vim", "vi") {
6973 args[0] = p;
6974 execvp(p, (char* const*) args);
6975 /* We do not fail if the editor doesn't exist
6976 * because we want to try each one of them before
6977 * failing.
6978 */
6979 if (errno != ENOENT) {
6980 log_error_errno(errno, "Failed to execute %s: %m", editor);
6981 _exit(EXIT_FAILURE);
6982 }
6983 }
6984
6985 log_error("Cannot edit unit(s), no editor available. Please set either $SYSTEMD_EDITOR, $EDITOR or $VISUAL.");
6986 _exit(EXIT_FAILURE);
6987 }
6988
6989 return 0;
6990 }
6991
6992 static int find_paths_to_edit(sd_bus *bus, char **names, char ***paths) {
6993 _cleanup_(lookup_paths_free) LookupPaths lp = {};
6994 char **name;
6995 int r;
6996
6997 assert(names);
6998 assert(paths);
6999
7000 r = lookup_paths_init(&lp, arg_scope, 0, arg_root);
7001 if (r < 0)
7002 return r;
7003
7004 STRV_FOREACH(name, names) {
7005 _cleanup_free_ char *path = NULL, *new_path = NULL, *tmp_path = NULL, *tmp_name = NULL;
7006 const char *unit_name;
7007
7008 r = unit_find_paths(bus, *name, &lp, false, &path, NULL);
7009 if (r == -EKEYREJECTED) {
7010 /* If loading of the unit failed server side complete, then the server won't tell us the unit
7011 * file path. In that case, find the file client side. */
7012 log_debug_errno(r, "Unit '%s' was not loaded correctly, retrying client-side.", *name);
7013 r = unit_find_paths(bus, *name, &lp, true, &path, NULL);
7014 }
7015 if (r == -ERFKILL)
7016 return log_error_errno(r, "Unit '%s' masked, cannot edit.", *name);
7017 if (r < 0)
7018 return r;
7019
7020 if (r == 0) {
7021 assert(!path);
7022
7023 if (!arg_force) {
7024 log_info("Run 'systemctl edit%s --force --full %s' to create a new unit.",
7025 arg_scope == UNIT_FILE_GLOBAL ? " --global" :
7026 arg_scope == UNIT_FILE_USER ? " --user" : "",
7027 *name);
7028 return -ENOENT;
7029 }
7030
7031 /* Create a new unit from scratch */
7032 unit_name = *name;
7033 r = unit_file_create_new(&lp, unit_name,
7034 arg_full ? NULL : ".d/override.conf",
7035 &new_path, &tmp_path);
7036 } else {
7037 assert(path);
7038
7039 unit_name = basename(path);
7040 /* We follow unit aliases, but we need to propagate the instance */
7041 if (unit_name_is_valid(*name, UNIT_NAME_INSTANCE) &&
7042 unit_name_is_valid(unit_name, UNIT_NAME_TEMPLATE)) {
7043 _cleanup_free_ char *instance = NULL;
7044
7045 r = unit_name_to_instance(*name, &instance);
7046 if (r < 0)
7047 return r;
7048
7049 r = unit_name_replace_instance(unit_name, instance, &tmp_name);
7050 if (r < 0)
7051 return r;
7052
7053 unit_name = tmp_name;
7054 }
7055
7056 if (arg_full)
7057 r = unit_file_create_copy(&lp, unit_name, path, &new_path, &tmp_path);
7058 else
7059 r = unit_file_create_new(&lp, unit_name, ".d/override.conf", &new_path, &tmp_path);
7060 }
7061 if (r < 0)
7062 return r;
7063
7064 r = strv_push_pair(paths, new_path, tmp_path);
7065 if (r < 0)
7066 return log_oom();
7067
7068 new_path = tmp_path = NULL;
7069 }
7070
7071 return 0;
7072 }
7073
7074 static int edit(int argc, char *argv[], void *userdata) {
7075 _cleanup_(lookup_paths_free) LookupPaths lp = {};
7076 _cleanup_strv_free_ char **names = NULL;
7077 _cleanup_strv_free_ char **paths = NULL;
7078 char **original, **tmp;
7079 sd_bus *bus;
7080 int r;
7081
7082 if (!on_tty()) {
7083 log_error("Cannot edit units if not on a tty.");
7084 return -EINVAL;
7085 }
7086
7087 if (arg_transport != BUS_TRANSPORT_LOCAL) {
7088 log_error("Cannot edit units remotely.");
7089 return -EINVAL;
7090 }
7091
7092 r = lookup_paths_init(&lp, arg_scope, 0, arg_root);
7093 if (r < 0)
7094 return log_error_errno(r, "Failed to determine unit paths: %m");
7095
7096 r = acquire_bus(BUS_MANAGER, &bus);
7097 if (r < 0)
7098 return r;
7099
7100 r = expand_names(bus, strv_skip(argv, 1), NULL, &names);
7101 if (r < 0)
7102 return log_error_errno(r, "Failed to expand names: %m");
7103
7104 STRV_FOREACH(tmp, names) {
7105 r = unit_is_masked(bus, &lp, *tmp);
7106 if (r < 0)
7107 return r;
7108 if (r > 0) {
7109 log_error("Cannot edit %s: unit is masked.", *tmp);
7110 return -EINVAL;
7111 }
7112 }
7113
7114 r = find_paths_to_edit(bus, names, &paths);
7115 if (r < 0)
7116 return r;
7117
7118 if (strv_isempty(paths))
7119 return -ENOENT;
7120
7121 r = run_editor(paths);
7122 if (r < 0)
7123 goto end;
7124
7125 STRV_FOREACH_PAIR(original, tmp, paths) {
7126 /* If the temporary file is empty we ignore it.
7127 * This allows the user to cancel the modification.
7128 */
7129 if (null_or_empty_path(*tmp)) {
7130 log_warning("Editing \"%s\" canceled: temporary file is empty.", *original);
7131 continue;
7132 }
7133
7134 r = rename(*tmp, *original);
7135 if (r < 0) {
7136 r = log_error_errno(errno, "Failed to rename \"%s\" to \"%s\": %m", *tmp, *original);
7137 goto end;
7138 }
7139 }
7140
7141 r = 0;
7142
7143 if (!arg_no_reload && !install_client_side())
7144 r = daemon_reload(argc, argv, userdata);
7145
7146 end:
7147 STRV_FOREACH_PAIR(original, tmp, paths) {
7148 (void) unlink(*tmp);
7149
7150 /* Removing empty dropin dirs */
7151 if (!arg_full) {
7152 _cleanup_free_ char *dir;
7153
7154 dir = dirname_malloc(*original);
7155 if (!dir)
7156 return log_oom();
7157
7158 /* no need to check if the dir is empty, rmdir
7159 * does nothing if it is not the case.
7160 */
7161 (void) rmdir(dir);
7162 }
7163 }
7164
7165 return r;
7166 }
7167
7168 static int systemctl_help(void) {
7169 _cleanup_free_ char *link = NULL;
7170 int r;
7171
7172 (void) pager_open(arg_pager_flags);
7173
7174 r = terminal_urlify_man("systemctl", "1", &link);
7175 if (r < 0)
7176 return log_oom();
7177
7178 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
7179 "Query or send control commands to the systemd manager.\n\n"
7180 " -h --help Show this help\n"
7181 " --version Show package version\n"
7182 " --system Connect to system manager\n"
7183 " --user Connect to user service manager\n"
7184 " -H --host=[USER@]HOST\n"
7185 " Operate on remote host\n"
7186 " -M --machine=CONTAINER\n"
7187 " Operate on local container\n"
7188 " -t --type=TYPE List units of a particular type\n"
7189 " --state=STATE List units with particular LOAD or SUB or ACTIVE state\n"
7190 " -p --property=NAME Show only properties by this name\n"
7191 " -a --all Show all properties/all units currently in memory,\n"
7192 " including dead/empty ones. To list all units installed on\n"
7193 " the system, use the 'list-unit-files' command instead.\n"
7194 " --failed Same as --state=failed\n"
7195 " -l --full Don't ellipsize unit names on output\n"
7196 " -r --recursive Show unit list of host and local containers\n"
7197 " --reverse Show reverse dependencies with 'list-dependencies'\n"
7198 " --job-mode=MODE Specify how to deal with already queued jobs, when\n"
7199 " queueing a new job\n"
7200 " --show-types When showing sockets, explicitly show their type\n"
7201 " --value When showing properties, only print the value\n"
7202 " -i --ignore-inhibitors\n"
7203 " When shutting down or sleeping, ignore inhibitors\n"
7204 " --kill-who=WHO Who to send signal to\n"
7205 " -s --signal=SIGNAL Which signal to send\n"
7206 " --now Start or stop unit in addition to enabling or disabling it\n"
7207 " --dry-run Only print what would be done\n"
7208 " -q --quiet Suppress output\n"
7209 " --wait For (re)start, wait until service stopped again\n"
7210 " For is-system-running, wait until startup is completed\n"
7211 " --no-block Do not wait until operation finished\n"
7212 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7213 " --no-reload Don't reload daemon after en-/dis-abling unit files\n"
7214 " --no-legend Do not print a legend (column headers and hints)\n"
7215 " --no-pager Do not pipe output into a pager\n"
7216 " --no-ask-password\n"
7217 " Do not ask for system passwords\n"
7218 " --global Enable/disable/mask unit files globally\n"
7219 " --runtime Enable/disable/mask unit files temporarily until next\n"
7220 " reboot\n"
7221 " -f --force When enabling unit files, override existing symlinks\n"
7222 " When shutting down, execute action immediately\n"
7223 " --preset-mode= Apply only enable, only disable, or all presets\n"
7224 " --root=PATH Enable/disable/mask unit files in the specified root\n"
7225 " directory\n"
7226 " -n --lines=INTEGER Number of journal entries to show\n"
7227 " -o --output=STRING Change journal output mode (short, short-precise,\n"
7228 " short-iso, short-iso-precise, short-full,\n"
7229 " short-monotonic, short-unix,\n"
7230 " verbose, export, json, json-pretty, json-sse, cat)\n"
7231 " --firmware-setup Tell the firmware to show the setup menu on next boot\n"
7232 " --plain Print unit dependencies as a list instead of a tree\n\n"
7233 "Unit Commands:\n"
7234 " list-units [PATTERN...] List units currently in memory\n"
7235 " list-sockets [PATTERN...] List socket units currently in memory,\n"
7236 " ordered by address\n"
7237 " list-timers [PATTERN...] List timer units currently in memory,\n"
7238 " ordered by next elapse\n"
7239 " start UNIT... Start (activate) one or more units\n"
7240 " stop UNIT... Stop (deactivate) one or more units\n"
7241 " reload UNIT... Reload one or more units\n"
7242 " restart UNIT... Start or restart one or more units\n"
7243 " try-restart UNIT... Restart one or more units if active\n"
7244 " reload-or-restart UNIT... Reload one or more units if possible,\n"
7245 " otherwise start or restart\n"
7246 " try-reload-or-restart UNIT... If active, reload one or more units,\n"
7247 " if supported, otherwise restart\n"
7248 " isolate UNIT Start one unit and stop all others\n"
7249 " kill UNIT... Send signal to processes of a unit\n"
7250 " is-active PATTERN... Check whether units are active\n"
7251 " is-failed PATTERN... Check whether units are failed\n"
7252 " status [PATTERN...|PID...] Show runtime status of one or more units\n"
7253 " show [PATTERN...|JOB...] Show properties of one or more\n"
7254 " units/jobs or the manager\n"
7255 " cat PATTERN... Show files and drop-ins of specified units\n"
7256 " set-property UNIT PROPERTY=VALUE... Sets one or more properties of a unit\n"
7257 " help PATTERN...|PID... Show manual for one or more units\n"
7258 " reset-failed [PATTERN...] Reset failed state for all, one, or more\n"
7259 " units\n"
7260 " list-dependencies [UNIT] Recursively show units which are required\n"
7261 " or wanted by this unit or by which this\n"
7262 " unit is required or wanted\n\n"
7263 "Unit File Commands:\n"
7264 " list-unit-files [PATTERN...] List installed unit files\n"
7265 " enable [UNIT...|PATH...] Enable one or more unit files\n"
7266 " disable UNIT... Disable one or more unit files\n"
7267 " reenable UNIT... Reenable one or more unit files\n"
7268 " preset UNIT... Enable/disable one or more unit files\n"
7269 " based on preset configuration\n"
7270 " preset-all Enable/disable all unit files based on\n"
7271 " preset configuration\n"
7272 " is-enabled UNIT... Check whether unit files are enabled\n"
7273 " mask UNIT... Mask one or more units\n"
7274 " unmask UNIT... Unmask one or more units\n"
7275 " link PATH... Link one or more units files into\n"
7276 " the search path\n"
7277 " revert UNIT... Revert one or more unit files to vendor\n"
7278 " version\n"
7279 " add-wants TARGET UNIT... Add 'Wants' dependency for the target\n"
7280 " on specified one or more units\n"
7281 " add-requires TARGET UNIT... Add 'Requires' dependency for the target\n"
7282 " on specified one or more units\n"
7283 " edit UNIT... Edit one or more unit files\n"
7284 " get-default Get the name of the default target\n"
7285 " set-default TARGET Set the default target\n\n"
7286 "Machine Commands:\n"
7287 " list-machines [PATTERN...] List local containers and host\n\n"
7288 "Job Commands:\n"
7289 " list-jobs [PATTERN...] List jobs\n"
7290 " cancel [JOB...] Cancel all, one, or more jobs\n\n"
7291 "Environment Commands:\n"
7292 " show-environment Dump environment\n"
7293 " set-environment VARIABLE=VALUE... Set one or more environment variables\n"
7294 " unset-environment VARIABLE... Unset one or more environment variables\n"
7295 " import-environment [VARIABLE...] Import all or some environment variables\n\n"
7296 "Manager Lifecycle Commands:\n"
7297 " daemon-reload Reload systemd manager configuration\n"
7298 " daemon-reexec Reexecute systemd manager\n\n"
7299 "System Commands:\n"
7300 " is-system-running Check whether system is fully running\n"
7301 " default Enter system default mode\n"
7302 " rescue Enter system rescue mode\n"
7303 " emergency Enter system emergency mode\n"
7304 " halt Shut down and halt the system\n"
7305 " poweroff Shut down and power-off the system\n"
7306 " reboot [ARG] Shut down and reboot the system\n"
7307 " kexec Shut down and reboot the system with kexec\n"
7308 " exit [EXIT_CODE] Request user instance or container exit\n"
7309 " switch-root ROOT [INIT] Change to a different root file system\n"
7310 " suspend Suspend the system\n"
7311 " hibernate Hibernate the system\n"
7312 " hybrid-sleep Hibernate and suspend the system\n"
7313 " suspend-then-hibernate Suspend the system, wake after a period of\n"
7314 " time and put it into hibernate\n"
7315 "\nSee the %s for details.\n"
7316 , program_invocation_short_name
7317 , link
7318 );
7319
7320 return 0;
7321 }
7322
7323 static int halt_help(void) {
7324 _cleanup_free_ char *link = NULL;
7325 int r;
7326
7327 r = terminal_urlify_man("halt", "8", &link);
7328 if (r < 0)
7329 return log_oom();
7330
7331 printf("%s [OPTIONS...]%s\n\n"
7332 "%s the system.\n\n"
7333 " --help Show this help\n"
7334 " --halt Halt the machine\n"
7335 " -p --poweroff Switch off the machine\n"
7336 " --reboot Reboot the machine\n"
7337 " -f --force Force immediate halt/power-off/reboot\n"
7338 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
7339 " -d --no-wtmp Don't write wtmp record\n"
7340 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7341 "\nSee the %s for details.\n"
7342 , program_invocation_short_name
7343 , arg_action == ACTION_REBOOT ? " [ARG]" : "",
7344 arg_action == ACTION_REBOOT ? "Reboot" :
7345 arg_action == ACTION_POWEROFF ? "Power off" :
7346 "Halt"
7347 , link
7348 );
7349
7350 return 0;
7351 }
7352
7353 static int shutdown_help(void) {
7354 _cleanup_free_ char *link = NULL;
7355 int r;
7356
7357 r = terminal_urlify_man("shutdown", "8", &link);
7358 if (r < 0)
7359 return log_oom();
7360
7361 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
7362 "Shut down the system.\n\n"
7363 " --help Show this help\n"
7364 " -H --halt Halt the machine\n"
7365 " -P --poweroff Power-off the machine\n"
7366 " -r --reboot Reboot the machine\n"
7367 " -h Equivalent to --poweroff, overridden by --halt\n"
7368 " -k Don't halt/power-off/reboot, just send warnings\n"
7369 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7370 " -c Cancel a pending shutdown\n"
7371 "\nSee the %s for details.\n"
7372 , program_invocation_short_name
7373 , link
7374 );
7375
7376 return 0;
7377 }
7378
7379 static int telinit_help(void) {
7380 _cleanup_free_ char *link = NULL;
7381 int r;
7382
7383 r = terminal_urlify_man("telinit", "8", &link);
7384 if (r < 0)
7385 return log_oom();
7386
7387 printf("%s [OPTIONS...] {COMMAND}\n\n"
7388 "Send control commands to the init daemon.\n\n"
7389 " --help Show this help\n"
7390 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
7391 "Commands:\n"
7392 " 0 Power-off the machine\n"
7393 " 6 Reboot the machine\n"
7394 " 2, 3, 4, 5 Start runlevelX.target unit\n"
7395 " 1, s, S Enter rescue mode\n"
7396 " q, Q Reload init daemon configuration\n"
7397 " u, U Reexecute init daemon\n"
7398 "\nSee the %s for details.\n"
7399 , program_invocation_short_name
7400 , link
7401 );
7402
7403 return 0;
7404 }
7405
7406 static int runlevel_help(void) {
7407 _cleanup_free_ char *link = NULL;
7408 int r;
7409
7410 r = terminal_urlify_man("runlevel", "8", &link);
7411 if (r < 0)
7412 return log_oom();
7413
7414 printf("%s [OPTIONS...]\n\n"
7415 "Prints the previous and current runlevel of the init system.\n\n"
7416 " --help Show this help\n"
7417 "\nSee the %s for details.\n"
7418 , program_invocation_short_name
7419 , link
7420 );
7421
7422 return 0;
7423 }
7424
7425 static void help_types(void) {
7426 if (!arg_no_legend)
7427 puts("Available unit types:");
7428
7429 DUMP_STRING_TABLE(unit_type, UnitType, _UNIT_TYPE_MAX);
7430 }
7431
7432 static void help_states(void) {
7433 if (!arg_no_legend)
7434 puts("Available unit load states:");
7435 DUMP_STRING_TABLE(unit_load_state, UnitLoadState, _UNIT_LOAD_STATE_MAX);
7436
7437 if (!arg_no_legend)
7438 puts("\nAvailable unit active states:");
7439 DUMP_STRING_TABLE(unit_active_state, UnitActiveState, _UNIT_ACTIVE_STATE_MAX);
7440
7441 if (!arg_no_legend)
7442 puts("\nAvailable automount unit substates:");
7443 DUMP_STRING_TABLE(automount_state, AutomountState, _AUTOMOUNT_STATE_MAX);
7444
7445 if (!arg_no_legend)
7446 puts("\nAvailable device unit substates:");
7447 DUMP_STRING_TABLE(device_state, DeviceState, _DEVICE_STATE_MAX);
7448
7449 if (!arg_no_legend)
7450 puts("\nAvailable mount unit substates:");
7451 DUMP_STRING_TABLE(mount_state, MountState, _MOUNT_STATE_MAX);
7452
7453 if (!arg_no_legend)
7454 puts("\nAvailable path unit substates:");
7455 DUMP_STRING_TABLE(path_state, PathState, _PATH_STATE_MAX);
7456
7457 if (!arg_no_legend)
7458 puts("\nAvailable scope unit substates:");
7459 DUMP_STRING_TABLE(scope_state, ScopeState, _SCOPE_STATE_MAX);
7460
7461 if (!arg_no_legend)
7462 puts("\nAvailable service unit substates:");
7463 DUMP_STRING_TABLE(service_state, ServiceState, _SERVICE_STATE_MAX);
7464
7465 if (!arg_no_legend)
7466 puts("\nAvailable slice unit substates:");
7467 DUMP_STRING_TABLE(slice_state, SliceState, _SLICE_STATE_MAX);
7468
7469 if (!arg_no_legend)
7470 puts("\nAvailable socket unit substates:");
7471 DUMP_STRING_TABLE(socket_state, SocketState, _SOCKET_STATE_MAX);
7472
7473 if (!arg_no_legend)
7474 puts("\nAvailable swap unit substates:");
7475 DUMP_STRING_TABLE(swap_state, SwapState, _SWAP_STATE_MAX);
7476
7477 if (!arg_no_legend)
7478 puts("\nAvailable target unit substates:");
7479 DUMP_STRING_TABLE(target_state, TargetState, _TARGET_STATE_MAX);
7480
7481 if (!arg_no_legend)
7482 puts("\nAvailable timer unit substates:");
7483 DUMP_STRING_TABLE(timer_state, TimerState, _TIMER_STATE_MAX);
7484 }
7485
7486 static int systemctl_parse_argv(int argc, char *argv[]) {
7487 enum {
7488 ARG_FAIL = 0x100,
7489 ARG_REVERSE,
7490 ARG_AFTER,
7491 ARG_BEFORE,
7492 ARG_DRY_RUN,
7493 ARG_SHOW_TYPES,
7494 ARG_IRREVERSIBLE,
7495 ARG_IGNORE_DEPENDENCIES,
7496 ARG_VALUE,
7497 ARG_VERSION,
7498 ARG_USER,
7499 ARG_SYSTEM,
7500 ARG_GLOBAL,
7501 ARG_NO_BLOCK,
7502 ARG_NO_LEGEND,
7503 ARG_NO_PAGER,
7504 ARG_NO_WALL,
7505 ARG_ROOT,
7506 ARG_NO_RELOAD,
7507 ARG_KILL_WHO,
7508 ARG_NO_ASK_PASSWORD,
7509 ARG_FAILED,
7510 ARG_RUNTIME,
7511 ARG_PLAIN,
7512 ARG_STATE,
7513 ARG_JOB_MODE,
7514 ARG_PRESET_MODE,
7515 ARG_FIRMWARE_SETUP,
7516 ARG_NOW,
7517 ARG_MESSAGE,
7518 ARG_WAIT,
7519 };
7520
7521 static const struct option options[] = {
7522 { "help", no_argument, NULL, 'h' },
7523 { "version", no_argument, NULL, ARG_VERSION },
7524 { "type", required_argument, NULL, 't' },
7525 { "property", required_argument, NULL, 'p' },
7526 { "all", no_argument, NULL, 'a' },
7527 { "reverse", no_argument, NULL, ARG_REVERSE },
7528 { "after", no_argument, NULL, ARG_AFTER },
7529 { "before", no_argument, NULL, ARG_BEFORE },
7530 { "show-types", no_argument, NULL, ARG_SHOW_TYPES },
7531 { "failed", no_argument, NULL, ARG_FAILED }, /* compatibility only */
7532 { "full", no_argument, NULL, 'l' },
7533 { "job-mode", required_argument, NULL, ARG_JOB_MODE },
7534 { "fail", no_argument, NULL, ARG_FAIL }, /* compatibility only */
7535 { "irreversible", no_argument, NULL, ARG_IRREVERSIBLE }, /* compatibility only */
7536 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES }, /* compatibility only */
7537 { "ignore-inhibitors", no_argument, NULL, 'i' },
7538 { "value", no_argument, NULL, ARG_VALUE },
7539 { "user", no_argument, NULL, ARG_USER },
7540 { "system", no_argument, NULL, ARG_SYSTEM },
7541 { "global", no_argument, NULL, ARG_GLOBAL },
7542 { "wait", no_argument, NULL, ARG_WAIT },
7543 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
7544 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
7545 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
7546 { "no-wall", no_argument, NULL, ARG_NO_WALL },
7547 { "dry-run", no_argument, NULL, ARG_DRY_RUN },
7548 { "quiet", no_argument, NULL, 'q' },
7549 { "root", required_argument, NULL, ARG_ROOT },
7550 { "force", no_argument, NULL, 'f' },
7551 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
7552 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
7553 { "signal", required_argument, NULL, 's' },
7554 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
7555 { "host", required_argument, NULL, 'H' },
7556 { "machine", required_argument, NULL, 'M' },
7557 { "runtime", no_argument, NULL, ARG_RUNTIME },
7558 { "lines", required_argument, NULL, 'n' },
7559 { "output", required_argument, NULL, 'o' },
7560 { "plain", no_argument, NULL, ARG_PLAIN },
7561 { "state", required_argument, NULL, ARG_STATE },
7562 { "recursive", no_argument, NULL, 'r' },
7563 { "preset-mode", required_argument, NULL, ARG_PRESET_MODE },
7564 { "firmware-setup", no_argument, NULL, ARG_FIRMWARE_SETUP },
7565 { "now", no_argument, NULL, ARG_NOW },
7566 { "message", required_argument, NULL, ARG_MESSAGE },
7567 {}
7568 };
7569
7570 const char *p;
7571 int c, r;
7572
7573 assert(argc >= 0);
7574 assert(argv);
7575
7576 /* we default to allowing interactive authorization only in systemctl (not in the legacy commands) */
7577 arg_ask_password = true;
7578
7579 while ((c = getopt_long(argc, argv, "ht:p:alqfs:H:M:n:o:ir", options, NULL)) >= 0)
7580
7581 switch (c) {
7582
7583 case 'h':
7584 return systemctl_help();
7585
7586 case ARG_VERSION:
7587 return version();
7588
7589 case 't': {
7590 if (isempty(optarg))
7591 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
7592 "--type= requires arguments.");
7593
7594 for (p = optarg;;) {
7595 _cleanup_free_ char *type = NULL;
7596
7597 r = extract_first_word(&p, &type, ",", 0);
7598 if (r < 0)
7599 return log_error_errno(r, "Failed to parse type: %s", optarg);
7600 if (r == 0)
7601 break;
7602
7603 if (streq(type, "help")) {
7604 help_types();
7605 return 0;
7606 }
7607
7608 if (unit_type_from_string(type) >= 0) {
7609 if (strv_push(&arg_types, type) < 0)
7610 return log_oom();
7611 type = NULL;
7612 continue;
7613 }
7614
7615 /* It's much nicer to use --state= for
7616 * load states, but let's support this
7617 * in --types= too for compatibility
7618 * with old versions */
7619 if (unit_load_state_from_string(type) >= 0) {
7620 if (strv_push(&arg_states, type) < 0)
7621 return log_oom();
7622 type = NULL;
7623 continue;
7624 }
7625
7626 log_error("Unknown unit type or load state '%s'.", type);
7627 return log_info_errno(SYNTHETIC_ERRNO(EINVAL),
7628 "Use -t help to see a list of allowed values.");
7629 }
7630
7631 break;
7632 }
7633
7634 case 'p': {
7635 /* Make sure that if the empty property list
7636 was specified, we won't show any properties. */
7637 if (isempty(optarg) && !arg_properties) {
7638 arg_properties = new0(char*, 1);
7639 if (!arg_properties)
7640 return log_oom();
7641 } else
7642 for (p = optarg;;) {
7643 _cleanup_free_ char *prop = NULL;
7644
7645 r = extract_first_word(&p, &prop, ",", 0);
7646 if (r < 0)
7647 return log_error_errno(r, "Failed to parse property: %s", optarg);
7648 if (r == 0)
7649 break;
7650
7651 if (strv_push(&arg_properties, prop) < 0)
7652 return log_oom();
7653
7654 prop = NULL;
7655 }
7656
7657 /* If the user asked for a particular
7658 * property, show it to him, even if it is
7659 * empty. */
7660 arg_all = true;
7661
7662 break;
7663 }
7664
7665 case 'a':
7666 arg_all = true;
7667 break;
7668
7669 case ARG_REVERSE:
7670 arg_dependency = DEPENDENCY_REVERSE;
7671 break;
7672
7673 case ARG_AFTER:
7674 arg_dependency = DEPENDENCY_AFTER;
7675 arg_jobs_after = true;
7676 break;
7677
7678 case ARG_BEFORE:
7679 arg_dependency = DEPENDENCY_BEFORE;
7680 arg_jobs_before = true;
7681 break;
7682
7683 case ARG_SHOW_TYPES:
7684 arg_show_types = true;
7685 break;
7686
7687 case ARG_VALUE:
7688 arg_value = true;
7689 break;
7690
7691 case ARG_JOB_MODE:
7692 arg_job_mode = optarg;
7693 break;
7694
7695 case ARG_FAIL:
7696 arg_job_mode = "fail";
7697 break;
7698
7699 case ARG_IRREVERSIBLE:
7700 arg_job_mode = "replace-irreversibly";
7701 break;
7702
7703 case ARG_IGNORE_DEPENDENCIES:
7704 arg_job_mode = "ignore-dependencies";
7705 break;
7706
7707 case ARG_USER:
7708 arg_scope = UNIT_FILE_USER;
7709 break;
7710
7711 case ARG_SYSTEM:
7712 arg_scope = UNIT_FILE_SYSTEM;
7713 break;
7714
7715 case ARG_GLOBAL:
7716 arg_scope = UNIT_FILE_GLOBAL;
7717 break;
7718
7719 case ARG_WAIT:
7720 arg_wait = true;
7721 break;
7722
7723 case ARG_NO_BLOCK:
7724 arg_no_block = true;
7725 break;
7726
7727 case ARG_NO_LEGEND:
7728 arg_no_legend = true;
7729 break;
7730
7731 case ARG_NO_PAGER:
7732 arg_pager_flags |= PAGER_DISABLE;
7733 break;
7734
7735 case ARG_NO_WALL:
7736 arg_no_wall = true;
7737 break;
7738
7739 case ARG_ROOT:
7740 r = parse_path_argument_and_warn(optarg, false, &arg_root);
7741 if (r < 0)
7742 return r;
7743 break;
7744
7745 case 'l':
7746 arg_full = true;
7747 break;
7748
7749 case ARG_FAILED:
7750 if (strv_extend(&arg_states, "failed") < 0)
7751 return log_oom();
7752
7753 break;
7754
7755 case ARG_DRY_RUN:
7756 arg_dry_run = true;
7757 break;
7758
7759 case 'q':
7760 arg_quiet = true;
7761 break;
7762
7763 case 'f':
7764 arg_force++;
7765 break;
7766
7767 case ARG_NO_RELOAD:
7768 arg_no_reload = true;
7769 break;
7770
7771 case ARG_KILL_WHO:
7772 arg_kill_who = optarg;
7773 break;
7774
7775 case 's':
7776 if (streq(optarg, "help")) {
7777 DUMP_STRING_TABLE(signal, int, _NSIG);
7778 return 0;
7779 }
7780
7781 arg_signal = signal_from_string(optarg);
7782 if (arg_signal < 0)
7783 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
7784 "Failed to parse signal string %s.",
7785 optarg);
7786 break;
7787
7788 case ARG_NO_ASK_PASSWORD:
7789 arg_ask_password = false;
7790 break;
7791
7792 case 'H':
7793 arg_transport = BUS_TRANSPORT_REMOTE;
7794 arg_host = optarg;
7795 break;
7796
7797 case 'M':
7798 arg_transport = BUS_TRANSPORT_MACHINE;
7799 arg_host = optarg;
7800 break;
7801
7802 case ARG_RUNTIME:
7803 arg_runtime = true;
7804 break;
7805
7806 case 'n':
7807 if (safe_atou(optarg, &arg_lines) < 0)
7808 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
7809 "Failed to parse lines '%s'",
7810 optarg);
7811 break;
7812
7813 case 'o':
7814 if (streq(optarg, "help")) {
7815 DUMP_STRING_TABLE(output_mode, OutputMode, _OUTPUT_MODE_MAX);
7816 return 0;
7817 }
7818
7819 arg_output = output_mode_from_string(optarg);
7820 if (arg_output < 0)
7821 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
7822 "Unknown output '%s'.",
7823 optarg);
7824 break;
7825
7826 case 'i':
7827 arg_ignore_inhibitors = true;
7828 break;
7829
7830 case ARG_PLAIN:
7831 arg_plain = true;
7832 break;
7833
7834 case ARG_FIRMWARE_SETUP:
7835 arg_firmware_setup = true;
7836 break;
7837
7838 case ARG_STATE: {
7839 if (isempty(optarg))
7840 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
7841 "--state= requires arguments.");
7842
7843 for (p = optarg;;) {
7844 _cleanup_free_ char *s = NULL;
7845
7846 r = extract_first_word(&p, &s, ",", 0);
7847 if (r < 0)
7848 return log_error_errno(r, "Failed to parse state: %s", optarg);
7849 if (r == 0)
7850 break;
7851
7852 if (streq(s, "help")) {
7853 help_states();
7854 return 0;
7855 }
7856
7857 if (strv_push(&arg_states, s) < 0)
7858 return log_oom();
7859
7860 s = NULL;
7861 }
7862 break;
7863 }
7864
7865 case 'r':
7866 if (geteuid() != 0)
7867 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
7868 "--recursive requires root privileges.");
7869
7870 arg_recursive = true;
7871 break;
7872
7873 case ARG_PRESET_MODE:
7874 if (streq(optarg, "help")) {
7875 DUMP_STRING_TABLE(unit_file_preset_mode, UnitFilePresetMode, _UNIT_FILE_PRESET_MAX);
7876 return 0;
7877 }
7878
7879 arg_preset_mode = unit_file_preset_mode_from_string(optarg);
7880 if (arg_preset_mode < 0)
7881 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
7882 "Failed to parse preset mode: %s.", optarg);
7883
7884 break;
7885
7886 case ARG_NOW:
7887 arg_now = true;
7888 break;
7889
7890 case ARG_MESSAGE:
7891 if (strv_extend(&arg_wall, optarg) < 0)
7892 return log_oom();
7893 break;
7894
7895 case '?':
7896 return -EINVAL;
7897
7898 default:
7899 assert_not_reached("Unhandled option");
7900 }
7901
7902 if (arg_transport != BUS_TRANSPORT_LOCAL && arg_scope != UNIT_FILE_SYSTEM)
7903 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
7904 "Cannot access user instance remotely.");
7905
7906 if (arg_wait && arg_no_block)
7907 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
7908 "--wait may not be combined with --no-block.");
7909
7910 if (arg_runtime && STRPTR_IN_SET(argv[optind], "disable", "unmask", "preset", "preset-all"))
7911 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
7912 "--runtime cannot be used with %s",
7913 argv[optind]);
7914
7915 return 1;
7916 }
7917
7918 static int halt_parse_argv(int argc, char *argv[]) {
7919 enum {
7920 ARG_HELP = 0x100,
7921 ARG_HALT,
7922 ARG_REBOOT,
7923 ARG_NO_WALL
7924 };
7925
7926 static const struct option options[] = {
7927 { "help", no_argument, NULL, ARG_HELP },
7928 { "halt", no_argument, NULL, ARG_HALT },
7929 { "poweroff", no_argument, NULL, 'p' },
7930 { "reboot", no_argument, NULL, ARG_REBOOT },
7931 { "force", no_argument, NULL, 'f' },
7932 { "wtmp-only", no_argument, NULL, 'w' },
7933 { "no-wtmp", no_argument, NULL, 'd' },
7934 { "no-sync", no_argument, NULL, 'n' },
7935 { "no-wall", no_argument, NULL, ARG_NO_WALL },
7936 {}
7937 };
7938
7939 int c, r, runlevel;
7940
7941 assert(argc >= 0);
7942 assert(argv);
7943
7944 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
7945 if (IN_SET(runlevel, '0', '6'))
7946 arg_force = 2;
7947
7948 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0)
7949 switch (c) {
7950
7951 case ARG_HELP:
7952 return halt_help();
7953
7954 case ARG_HALT:
7955 arg_action = ACTION_HALT;
7956 break;
7957
7958 case 'p':
7959 if (arg_action != ACTION_REBOOT)
7960 arg_action = ACTION_POWEROFF;
7961 break;
7962
7963 case ARG_REBOOT:
7964 arg_action = ACTION_REBOOT;
7965 break;
7966
7967 case 'f':
7968 arg_force = 2;
7969 break;
7970
7971 case 'w':
7972 arg_dry_run = true;
7973 break;
7974
7975 case 'd':
7976 arg_no_wtmp = true;
7977 break;
7978
7979 case 'n':
7980 arg_no_sync = true;
7981 break;
7982
7983 case ARG_NO_WALL:
7984 arg_no_wall = true;
7985 break;
7986
7987 case 'i':
7988 case 'h':
7989 /* Compatibility nops */
7990 break;
7991
7992 case '?':
7993 return -EINVAL;
7994
7995 default:
7996 assert_not_reached("Unhandled option");
7997 }
7998
7999 if (arg_action == ACTION_REBOOT && (argc == optind || argc == optind + 1)) {
8000 r = update_reboot_parameter_and_warn(argc == optind + 1 ? argv[optind] : NULL);
8001 if (r < 0)
8002 return r;
8003 } else if (optind < argc)
8004 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8005 "Too many arguments.");
8006
8007 return 1;
8008 }
8009
8010 static int parse_shutdown_time_spec(const char *t, usec_t *_u) {
8011 assert(t);
8012 assert(_u);
8013
8014 if (streq(t, "now"))
8015 *_u = 0;
8016 else if (!strchr(t, ':')) {
8017 uint64_t u;
8018
8019 if (safe_atou64(t, &u) < 0)
8020 return -EINVAL;
8021
8022 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
8023 } else {
8024 char *e = NULL;
8025 long hour, minute;
8026 struct tm tm = {};
8027 time_t s;
8028 usec_t n;
8029
8030 errno = 0;
8031 hour = strtol(t, &e, 10);
8032 if (errno > 0 || *e != ':' || hour < 0 || hour > 23)
8033 return -EINVAL;
8034
8035 minute = strtol(e+1, &e, 10);
8036 if (errno > 0 || *e != 0 || minute < 0 || minute > 59)
8037 return -EINVAL;
8038
8039 n = now(CLOCK_REALTIME);
8040 s = (time_t) (n / USEC_PER_SEC);
8041
8042 assert_se(localtime_r(&s, &tm));
8043
8044 tm.tm_hour = (int) hour;
8045 tm.tm_min = (int) minute;
8046 tm.tm_sec = 0;
8047
8048 s = mktime(&tm);
8049 assert(s >= 0);
8050
8051 *_u = (usec_t) s * USEC_PER_SEC;
8052
8053 while (*_u <= n)
8054 *_u += USEC_PER_DAY;
8055 }
8056
8057 return 0;
8058 }
8059
8060 static int shutdown_parse_argv(int argc, char *argv[]) {
8061 enum {
8062 ARG_HELP = 0x100,
8063 ARG_NO_WALL
8064 };
8065
8066 static const struct option options[] = {
8067 { "help", no_argument, NULL, ARG_HELP },
8068 { "halt", no_argument, NULL, 'H' },
8069 { "poweroff", no_argument, NULL, 'P' },
8070 { "reboot", no_argument, NULL, 'r' },
8071 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
8072 { "no-wall", no_argument, NULL, ARG_NO_WALL },
8073 {}
8074 };
8075
8076 char **wall = NULL;
8077 int c, r;
8078
8079 assert(argc >= 0);
8080 assert(argv);
8081
8082 while ((c = getopt_long(argc, argv, "HPrhkKat:fFc", options, NULL)) >= 0)
8083 switch (c) {
8084
8085 case ARG_HELP:
8086 return shutdown_help();
8087
8088 case 'H':
8089 arg_action = ACTION_HALT;
8090 break;
8091
8092 case 'P':
8093 arg_action = ACTION_POWEROFF;
8094 break;
8095
8096 case 'r':
8097 if (kexec_loaded())
8098 arg_action = ACTION_KEXEC;
8099 else
8100 arg_action = ACTION_REBOOT;
8101 break;
8102
8103 case 'K':
8104 arg_action = ACTION_KEXEC;
8105 break;
8106
8107 case 'h':
8108 if (arg_action != ACTION_HALT)
8109 arg_action = ACTION_POWEROFF;
8110 break;
8111
8112 case 'k':
8113 arg_dry_run = true;
8114 break;
8115
8116 case ARG_NO_WALL:
8117 arg_no_wall = true;
8118 break;
8119
8120 case 'a':
8121 case 't': /* Note that we also ignore any passed argument to -t, not just the -t itself */
8122 case 'f':
8123 case 'F':
8124 /* Compatibility nops */
8125 break;
8126
8127 case 'c':
8128 arg_action = ACTION_CANCEL_SHUTDOWN;
8129 break;
8130
8131 case '?':
8132 return -EINVAL;
8133
8134 default:
8135 assert_not_reached("Unhandled option");
8136 }
8137
8138 if (argc > optind && arg_action != ACTION_CANCEL_SHUTDOWN) {
8139 r = parse_shutdown_time_spec(argv[optind], &arg_when);
8140 if (r < 0) {
8141 log_error("Failed to parse time specification: %s", argv[optind]);
8142 return r;
8143 }
8144 } else
8145 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
8146
8147 if (argc > optind && arg_action == ACTION_CANCEL_SHUTDOWN)
8148 /* No time argument for shutdown cancel */
8149 wall = argv + optind;
8150 else if (argc > optind + 1)
8151 /* We skip the time argument */
8152 wall = argv + optind + 1;
8153
8154 if (wall) {
8155 arg_wall = strv_copy(wall);
8156 if (!arg_wall)
8157 return log_oom();
8158 }
8159
8160 optind = argc;
8161
8162 return 1;
8163 }
8164
8165 static int telinit_parse_argv(int argc, char *argv[]) {
8166 enum {
8167 ARG_HELP = 0x100,
8168 ARG_NO_WALL
8169 };
8170
8171 static const struct option options[] = {
8172 { "help", no_argument, NULL, ARG_HELP },
8173 { "no-wall", no_argument, NULL, ARG_NO_WALL },
8174 {}
8175 };
8176
8177 static const struct {
8178 char from;
8179 enum action to;
8180 } table[] = {
8181 { '0', ACTION_POWEROFF },
8182 { '6', ACTION_REBOOT },
8183 { '1', ACTION_RESCUE },
8184 { '2', ACTION_RUNLEVEL2 },
8185 { '3', ACTION_RUNLEVEL3 },
8186 { '4', ACTION_RUNLEVEL4 },
8187 { '5', ACTION_RUNLEVEL5 },
8188 { 's', ACTION_RESCUE },
8189 { 'S', ACTION_RESCUE },
8190 { 'q', ACTION_RELOAD },
8191 { 'Q', ACTION_RELOAD },
8192 { 'u', ACTION_REEXEC },
8193 { 'U', ACTION_REEXEC }
8194 };
8195
8196 unsigned i;
8197 int c;
8198
8199 assert(argc >= 0);
8200 assert(argv);
8201
8202 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0)
8203 switch (c) {
8204
8205 case ARG_HELP:
8206 return telinit_help();
8207
8208 case ARG_NO_WALL:
8209 arg_no_wall = true;
8210 break;
8211
8212 case '?':
8213 return -EINVAL;
8214
8215 default:
8216 assert_not_reached("Unhandled option");
8217 }
8218
8219 if (optind >= argc)
8220 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8221 "%s: required argument missing.",
8222 program_invocation_short_name);
8223
8224 if (optind + 1 < argc)
8225 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8226 "Too many arguments.");
8227
8228 if (strlen(argv[optind]) != 1)
8229 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8230 "Expected single character argument.");
8231
8232 for (i = 0; i < ELEMENTSOF(table); i++)
8233 if (table[i].from == argv[optind][0])
8234 break;
8235
8236 if (i >= ELEMENTSOF(table))
8237 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8238 "Unknown command '%s'.", argv[optind]);
8239
8240 arg_action = table[i].to;
8241
8242 optind++;
8243
8244 return 1;
8245 }
8246
8247 static int runlevel_parse_argv(int argc, char *argv[]) {
8248 enum {
8249 ARG_HELP = 0x100,
8250 };
8251
8252 static const struct option options[] = {
8253 { "help", no_argument, NULL, ARG_HELP },
8254 {}
8255 };
8256
8257 int c;
8258
8259 assert(argc >= 0);
8260 assert(argv);
8261
8262 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0)
8263 switch (c) {
8264
8265 case ARG_HELP:
8266 return runlevel_help();
8267
8268 case '?':
8269 return -EINVAL;
8270
8271 default:
8272 assert_not_reached("Unhandled option");
8273 }
8274
8275 if (optind < argc)
8276 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8277 "Too many arguments.");
8278
8279 return 1;
8280 }
8281
8282 static int parse_argv(int argc, char *argv[]) {
8283 assert(argc >= 0);
8284 assert(argv);
8285
8286 if (program_invocation_short_name) {
8287
8288 if (strstr(program_invocation_short_name, "halt")) {
8289 arg_action = ACTION_HALT;
8290 return halt_parse_argv(argc, argv);
8291
8292 } else if (strstr(program_invocation_short_name, "poweroff")) {
8293 arg_action = ACTION_POWEROFF;
8294 return halt_parse_argv(argc, argv);
8295
8296 } else if (strstr(program_invocation_short_name, "reboot")) {
8297 if (kexec_loaded())
8298 arg_action = ACTION_KEXEC;
8299 else
8300 arg_action = ACTION_REBOOT;
8301 return halt_parse_argv(argc, argv);
8302
8303 } else if (strstr(program_invocation_short_name, "shutdown")) {
8304 arg_action = ACTION_POWEROFF;
8305 return shutdown_parse_argv(argc, argv);
8306
8307 } else if (strstr(program_invocation_short_name, "init")) {
8308
8309 /* Matches invocations as "init" as well as "telinit", which are synonymous when run as PID !=
8310 * 1 on SysV.
8311 *
8312 * On SysV "telinit" was the official command to communicate with PID 1, but "init" would
8313 * redirect itself to "telinit" if called with PID != 1. We follow the same logic here still,
8314 * though we add one level of indirection, as we implement "telinit" in "systemctl". Hence, for
8315 * us if you invoke "init" you get "systemd", but it will execve() "systemctl" immediately with
8316 * argv[] unmodified if PID is != 1. If you invoke "telinit" you directly get "systemctl". In
8317 * both cases we shall do the same thing, which is why we do strstr(p_i_s_n, "init") here, as a
8318 * quick way to match both.
8319 *
8320 * Also see redirect_telinit() in src/core/main.c. */
8321
8322 if (sd_booted() > 0) {
8323 arg_action = _ACTION_INVALID;
8324 return telinit_parse_argv(argc, argv);
8325 } else {
8326 /* Hmm, so some other init system is running, we need to forward this request to
8327 * it. For now we simply guess that it is Upstart. */
8328
8329 execv(TELINIT, argv);
8330
8331 return log_error_errno(SYNTHETIC_ERRNO(EIO),
8332 "Couldn't find an alternative telinit implementation to spawn.");
8333 }
8334
8335 } else if (strstr(program_invocation_short_name, "runlevel")) {
8336 arg_action = ACTION_RUNLEVEL;
8337 return runlevel_parse_argv(argc, argv);
8338 }
8339 }
8340
8341 arg_action = ACTION_SYSTEMCTL;
8342 return systemctl_parse_argv(argc, argv);
8343 }
8344
8345 #if HAVE_SYSV_COMPAT
8346 _pure_ static int action_to_runlevel(void) {
8347 static const char table[_ACTION_MAX] = {
8348 [ACTION_HALT] = '0',
8349 [ACTION_POWEROFF] = '0',
8350 [ACTION_REBOOT] = '6',
8351 [ACTION_RUNLEVEL2] = '2',
8352 [ACTION_RUNLEVEL3] = '3',
8353 [ACTION_RUNLEVEL4] = '4',
8354 [ACTION_RUNLEVEL5] = '5',
8355 [ACTION_RESCUE] = '1'
8356 };
8357
8358 assert(arg_action >= 0 && arg_action < _ACTION_MAX);
8359
8360 return table[arg_action];
8361 }
8362 #endif
8363
8364 static int talk_initctl(void) {
8365 #if HAVE_SYSV_COMPAT
8366 struct init_request request = {
8367 .magic = INIT_MAGIC,
8368 .sleeptime = 0,
8369 .cmd = INIT_CMD_RUNLVL
8370 };
8371
8372 _cleanup_close_ int fd = -1;
8373 char rl;
8374 int r;
8375 const char *p;
8376
8377 rl = action_to_runlevel();
8378 if (!rl)
8379 return 0;
8380
8381 request.runlevel = rl;
8382
8383 FOREACH_STRING(p, "/run/initctl", "/dev/initctl") {
8384 fd = open(p, O_WRONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
8385 if (fd >= 0 || errno != ENOENT)
8386 break;
8387 }
8388 if (fd < 0) {
8389 if (errno == ENOENT)
8390 return 0;
8391
8392 return log_error_errno(errno, "Failed to open initctl fifo: %m");
8393 }
8394
8395 r = loop_write(fd, &request, sizeof(request), false);
8396 if (r < 0)
8397 return log_error_errno(r, "Failed to write to %s: %m", p);
8398
8399 return 1;
8400 #else
8401 return 0;
8402 #endif
8403 }
8404
8405 static int systemctl_main(int argc, char *argv[]) {
8406 static const Verb verbs[] = {
8407 { "list-units", VERB_ANY, VERB_ANY, VERB_DEFAULT|VERB_ONLINE_ONLY, list_units },
8408 { "list-unit-files", VERB_ANY, VERB_ANY, 0, list_unit_files },
8409 { "list-sockets", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, list_sockets },
8410 { "list-timers", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, list_timers },
8411 { "list-jobs", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, list_jobs },
8412 { "list-machines", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY|VERB_MUST_BE_ROOT, list_machines },
8413 { "clear-jobs", VERB_ANY, 1, VERB_ONLINE_ONLY, trivial_method },
8414 { "cancel", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, cancel_job },
8415 { "start", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8416 { "stop", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8417 { "condstop", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with ALTLinux */
8418 { "reload", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8419 { "restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8420 { "try-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8421 { "reload-or-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8422 { "reload-or-try-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatbility with old systemctl <= 228 */
8423 { "try-reload-or-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8424 { "force-reload", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with SysV */
8425 { "condreload", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with ALTLinux */
8426 { "condrestart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with RH */
8427 { "isolate", 2, 2, VERB_ONLINE_ONLY, start_unit },
8428 { "kill", 2, VERB_ANY, VERB_ONLINE_ONLY, kill_unit },
8429 { "is-active", 2, VERB_ANY, VERB_ONLINE_ONLY, check_unit_active },
8430 { "check", 2, VERB_ANY, VERB_ONLINE_ONLY, check_unit_active }, /* deprecated alias of is-active */
8431 { "is-failed", 2, VERB_ANY, VERB_ONLINE_ONLY, check_unit_failed },
8432 { "show", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, show },
8433 { "cat", 2, VERB_ANY, VERB_ONLINE_ONLY, cat },
8434 { "status", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, show },
8435 { "help", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, show },
8436 { "daemon-reload", VERB_ANY, 1, VERB_ONLINE_ONLY, daemon_reload },
8437 { "daemon-reexec", VERB_ANY, 1, VERB_ONLINE_ONLY, daemon_reload },
8438 { "show-environment", VERB_ANY, 1, VERB_ONLINE_ONLY, show_environment },
8439 { "set-environment", 2, VERB_ANY, VERB_ONLINE_ONLY, set_environment },
8440 { "unset-environment", 2, VERB_ANY, VERB_ONLINE_ONLY, set_environment },
8441 { "import-environment", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, import_environment },
8442 { "halt", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8443 { "poweroff", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8444 { "reboot", VERB_ANY, 2, VERB_ONLINE_ONLY, start_system_special },
8445 { "kexec", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8446 { "suspend", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8447 { "hibernate", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8448 { "hybrid-sleep", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8449 { "suspend-then-hibernate",VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8450 { "default", VERB_ANY, 1, VERB_ONLINE_ONLY, start_special },
8451 { "rescue", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8452 { "emergency", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8453 { "exit", VERB_ANY, 2, VERB_ONLINE_ONLY, start_special },
8454 { "reset-failed", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, reset_failed },
8455 { "enable", 2, VERB_ANY, 0, enable_unit },
8456 { "disable", 2, VERB_ANY, 0, enable_unit },
8457 { "is-enabled", 2, VERB_ANY, 0, unit_is_enabled },
8458 { "reenable", 2, VERB_ANY, 0, enable_unit },
8459 { "preset", 2, VERB_ANY, 0, enable_unit },
8460 { "preset-all", VERB_ANY, 1, 0, preset_all },
8461 { "mask", 2, VERB_ANY, 0, enable_unit },
8462 { "unmask", 2, VERB_ANY, 0, enable_unit },
8463 { "link", 2, VERB_ANY, 0, enable_unit },
8464 { "revert", 2, VERB_ANY, 0, enable_unit },
8465 { "switch-root", 2, VERB_ANY, VERB_ONLINE_ONLY, switch_root },
8466 { "list-dependencies", VERB_ANY, 2, VERB_ONLINE_ONLY, list_dependencies },
8467 { "set-default", 2, 2, 0, set_default },
8468 { "get-default", VERB_ANY, 1, 0, get_default },
8469 { "set-property", 3, VERB_ANY, VERB_ONLINE_ONLY, set_property },
8470 { "is-system-running", VERB_ANY, 1, 0, is_system_running },
8471 { "add-wants", 3, VERB_ANY, 0, add_dependency },
8472 { "add-requires", 3, VERB_ANY, 0, add_dependency },
8473 { "edit", 2, VERB_ANY, VERB_ONLINE_ONLY, edit },
8474 {}
8475 };
8476
8477 return dispatch_verb(argc, argv, verbs, NULL);
8478 }
8479
8480 static int reload_with_fallback(void) {
8481 /* First, try systemd via D-Bus. */
8482 if (daemon_reload(0, NULL, NULL) >= 0)
8483 return 0;
8484
8485 /* Nothing else worked, so let's try signals */
8486 assert(IN_SET(arg_action, ACTION_RELOAD, ACTION_REEXEC));
8487
8488 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0)
8489 return log_error_errno(errno, "kill() failed: %m");
8490
8491 return 0;
8492 }
8493
8494 static int start_with_fallback(void) {
8495 /* First, try systemd via D-Bus. */
8496 if (start_unit(0, NULL, NULL) >= 0)
8497 return 0;
8498
8499 /* Nothing else worked, so let's try /dev/initctl */
8500 if (talk_initctl() > 0)
8501 return 0;
8502
8503 return log_error_errno(SYNTHETIC_ERRNO(EIO),
8504 "Failed to talk to init daemon.");
8505 }
8506
8507 static int halt_now(enum action a) {
8508 /* The kernel will automatically flush ATA disks and suchlike on reboot(), but the file systems need to be
8509 * synced explicitly in advance. */
8510 if (!arg_no_sync && !arg_dry_run)
8511 (void) sync();
8512
8513 /* Make sure C-A-D is handled by the kernel from this point on... */
8514 if (!arg_dry_run)
8515 (void) reboot(RB_ENABLE_CAD);
8516
8517 switch (a) {
8518
8519 case ACTION_HALT:
8520 if (!arg_quiet)
8521 log_info("Halting.");
8522 if (arg_dry_run)
8523 return 0;
8524 (void) reboot(RB_HALT_SYSTEM);
8525 return -errno;
8526
8527 case ACTION_POWEROFF:
8528 if (!arg_quiet)
8529 log_info("Powering off.");
8530 if (arg_dry_run)
8531 return 0;
8532 (void) reboot(RB_POWER_OFF);
8533 return -errno;
8534
8535 case ACTION_KEXEC:
8536 case ACTION_REBOOT:
8537 return reboot_with_parameter(REBOOT_FALLBACK |
8538 (arg_quiet ? 0 : REBOOT_LOG) |
8539 (arg_dry_run ? REBOOT_DRY_RUN : 0));
8540
8541 default:
8542 assert_not_reached("Unknown action.");
8543 }
8544 }
8545
8546 static int logind_schedule_shutdown(void) {
8547
8548 #if ENABLE_LOGIND
8549 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
8550 char date[FORMAT_TIMESTAMP_MAX];
8551 const char *action;
8552 sd_bus *bus;
8553 int r;
8554
8555 r = acquire_bus(BUS_FULL, &bus);
8556 if (r < 0)
8557 return r;
8558
8559 switch (arg_action) {
8560 case ACTION_HALT:
8561 action = "halt";
8562 break;
8563 case ACTION_POWEROFF:
8564 action = "poweroff";
8565 break;
8566 case ACTION_KEXEC:
8567 action = "kexec";
8568 break;
8569 case ACTION_EXIT:
8570 action = "exit";
8571 break;
8572 case ACTION_REBOOT:
8573 default:
8574 action = "reboot";
8575 break;
8576 }
8577
8578 if (arg_dry_run)
8579 action = strjoina("dry-", action);
8580
8581 (void) logind_set_wall_message();
8582
8583 r = sd_bus_call_method(
8584 bus,
8585 "org.freedesktop.login1",
8586 "/org/freedesktop/login1",
8587 "org.freedesktop.login1.Manager",
8588 "ScheduleShutdown",
8589 &error,
8590 NULL,
8591 "st",
8592 action,
8593 arg_when);
8594 if (r < 0)
8595 return log_warning_errno(r, "Failed to call ScheduleShutdown in logind, proceeding with immediate shutdown: %s", bus_error_message(&error, r));
8596
8597 if (!arg_quiet)
8598 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.", format_timestamp(date, sizeof(date), arg_when));
8599 return 0;
8600 #else
8601 log_error("Cannot schedule shutdown without logind support, proceeding with immediate shutdown.");
8602 return -ENOSYS;
8603 #endif
8604 }
8605
8606 static int halt_main(void) {
8607 int r;
8608
8609 r = logind_check_inhibitors(arg_action);
8610 if (r < 0)
8611 return r;
8612
8613 /* Delayed shutdown requested, and was successful */
8614 if (arg_when > 0 && logind_schedule_shutdown() == 0)
8615 return 0;
8616 /* no delay, or logind failed or is not at all available */
8617
8618 if (geteuid() != 0) {
8619 if (arg_dry_run || arg_force > 0) {
8620 (void) must_be_root();
8621 return -EPERM;
8622 }
8623
8624 /* Try logind if we are a normal user and no special
8625 * mode applies. Maybe polkit allows us to shutdown
8626 * the machine. */
8627 if (IN_SET(arg_action, ACTION_POWEROFF, ACTION_REBOOT, ACTION_HALT)) {
8628 r = logind_reboot(arg_action);
8629 if (r >= 0)
8630 return r;
8631 if (IN_SET(r, -EOPNOTSUPP, -EINPROGRESS))
8632 /* requested operation is not
8633 * supported on the local system or
8634 * already in progress */
8635 return r;
8636 /* on all other errors, try low-level operation */
8637 }
8638 }
8639
8640 /* In order to minimize the difference between operation with and
8641 * without logind, we explicitly enable non-blocking mode for this,
8642 * as logind's shutdown operations are always non-blocking. */
8643 arg_no_block = true;
8644
8645 if (!arg_dry_run && !arg_force)
8646 return start_with_fallback();
8647
8648 assert(geteuid() == 0);
8649
8650 if (!arg_no_wtmp) {
8651 if (sd_booted() > 0)
8652 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
8653 else {
8654 r = utmp_put_shutdown();
8655 if (r < 0)
8656 log_warning_errno(r, "Failed to write utmp record: %m");
8657 }
8658 }
8659
8660 if (arg_dry_run)
8661 return 0;
8662
8663 r = halt_now(arg_action);
8664 return log_error_errno(r, "Failed to reboot: %m");
8665 }
8666
8667 static int runlevel_main(void) {
8668 int r, runlevel, previous;
8669
8670 r = utmp_get_runlevel(&runlevel, &previous);
8671 if (r < 0) {
8672 puts("unknown");
8673 return r;
8674 }
8675
8676 printf("%c %c\n",
8677 previous <= 0 ? 'N' : previous,
8678 runlevel <= 0 ? 'N' : runlevel);
8679
8680 return 0;
8681 }
8682
8683 static int logind_cancel_shutdown(void) {
8684 #if ENABLE_LOGIND
8685 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
8686 sd_bus *bus;
8687 int r;
8688
8689 r = acquire_bus(BUS_FULL, &bus);
8690 if (r < 0)
8691 return r;
8692
8693 (void) logind_set_wall_message();
8694
8695 r = sd_bus_call_method(
8696 bus,
8697 "org.freedesktop.login1",
8698 "/org/freedesktop/login1",
8699 "org.freedesktop.login1.Manager",
8700 "CancelScheduledShutdown",
8701 &error,
8702 NULL, NULL);
8703 if (r < 0)
8704 return log_warning_errno(r, "Failed to talk to logind, shutdown hasn't been cancelled: %s", bus_error_message(&error, r));
8705
8706 return 0;
8707 #else
8708 log_error("Not compiled with logind support, cannot cancel scheduled shutdowns.");
8709 return -ENOSYS;
8710 #endif
8711 }
8712
8713 static int run(int argc, char*argv[]) {
8714 int r;
8715
8716 argv_cmdline = argv[0];
8717
8718 setlocale(LC_ALL, "");
8719 log_parse_environment();
8720 log_open();
8721
8722 /* The journal merging logic potentially needs a lot of fds. */
8723 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE);
8724
8725 sigbus_install();
8726
8727 /* Explicitly not on_tty() to avoid setting cached value.
8728 * This becomes relevant for piping output which might be
8729 * ellipsized. */
8730 original_stdout_is_tty = isatty(STDOUT_FILENO);
8731
8732 r = parse_argv(argc, argv);
8733 if (r <= 0)
8734 goto finish;
8735
8736 if (arg_action != ACTION_SYSTEMCTL && running_in_chroot() > 0) {
8737 if (!arg_quiet)
8738 log_info("Running in chroot, ignoring request.");
8739 r = 0;
8740 goto finish;
8741 }
8742
8743 /* systemctl_main() will print an error message for the bus
8744 * connection, but only if it needs to */
8745
8746 switch (arg_action) {
8747
8748 case ACTION_SYSTEMCTL:
8749 r = systemctl_main(argc, argv);
8750 break;
8751
8752 /* Legacy command aliases set arg_action. They provide some fallbacks,
8753 * e.g. to tell sysvinit to reboot after you have installed systemd
8754 * binaries. */
8755
8756 case ACTION_HALT:
8757 case ACTION_POWEROFF:
8758 case ACTION_REBOOT:
8759 case ACTION_KEXEC:
8760 r = halt_main();
8761 break;
8762
8763 case ACTION_RUNLEVEL2:
8764 case ACTION_RUNLEVEL3:
8765 case ACTION_RUNLEVEL4:
8766 case ACTION_RUNLEVEL5:
8767 case ACTION_RESCUE:
8768 r = start_with_fallback();
8769 break;
8770
8771 case ACTION_RELOAD:
8772 case ACTION_REEXEC:
8773 r = reload_with_fallback();
8774 break;
8775
8776 case ACTION_CANCEL_SHUTDOWN:
8777 r = logind_cancel_shutdown();
8778 break;
8779
8780 case ACTION_RUNLEVEL:
8781 r = runlevel_main();
8782 break;
8783
8784 case ACTION_EXIT:
8785 case ACTION_SUSPEND:
8786 case ACTION_HIBERNATE:
8787 case ACTION_HYBRID_SLEEP:
8788 case ACTION_SUSPEND_THEN_HIBERNATE:
8789 case ACTION_EMERGENCY:
8790 case ACTION_DEFAULT:
8791 /* systemctl verbs with no equivalent in the legacy commands.
8792 * These cannot appear in arg_action. Fall through. */
8793
8794 case _ACTION_INVALID:
8795 default:
8796 assert_not_reached("Unknown action");
8797 }
8798
8799 finish:
8800 release_busses();
8801
8802 strv_free(arg_types);
8803 strv_free(arg_states);
8804 strv_free(arg_properties);
8805
8806 strv_free(arg_wall);
8807 free(arg_root);
8808 free(arg_esp_path);
8809
8810 /* Note that we return r here, not 0, so that we can implement the LSB-like return codes */
8811 return r;
8812 }
8813
8814 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);