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