]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/systemctl/systemctl.c
bus-util: print a friendly message when PID1 is not systemd
[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_file(const char *filename, bool newline) {
5318 _cleanup_close_ int fd;
5319
5320 fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOCTTY);
5321 if (fd < 0)
5322 return -errno;
5323
5324 printf("%s%s# %s%s\n",
5325 newline ? "\n" : "",
5326 ansi_highlight_blue(),
5327 filename,
5328 ansi_normal());
5329 fflush(stdout);
5330
5331 return copy_bytes(fd, STDOUT_FILENO, (uint64_t) -1, 0);
5332 }
5333
5334 static int cat(int argc, char *argv[], void *userdata) {
5335 _cleanup_(lookup_paths_free) LookupPaths lp = {};
5336 _cleanup_strv_free_ char **names = NULL;
5337 char **name;
5338 sd_bus *bus;
5339 bool first = true;
5340 int r;
5341
5342 if (arg_transport != BUS_TRANSPORT_LOCAL) {
5343 log_error("Cannot remotely cat units.");
5344 return -EINVAL;
5345 }
5346
5347 r = lookup_paths_init(&lp, arg_scope, 0, arg_root);
5348 if (r < 0)
5349 return log_error_errno(r, "Failed to determine unit paths: %m");
5350
5351 r = acquire_bus(BUS_MANAGER, &bus);
5352 if (r < 0)
5353 return r;
5354
5355 r = expand_names(bus, strv_skip(argv, 1), NULL, &names);
5356 if (r < 0)
5357 return log_error_errno(r, "Failed to expand names: %m");
5358
5359 (void) pager_open(arg_no_pager, false);
5360
5361 STRV_FOREACH(name, names) {
5362 _cleanup_free_ char *fragment_path = NULL;
5363 _cleanup_strv_free_ char **dropin_paths = NULL;
5364 char **path;
5365
5366 r = unit_find_paths(bus, *name, &lp, &fragment_path, &dropin_paths);
5367 if (r < 0)
5368 return r;
5369 else if (r == 0)
5370 return -ENOENT;
5371
5372 if (first)
5373 first = false;
5374 else
5375 puts("");
5376
5377 if (need_daemon_reload(bus, *name) > 0) /* ignore errors (<0), this is informational output */
5378 fprintf(stderr,
5379 "%s# Warning: %s changed on disk, the version systemd has loaded is outdated.\n"
5380 "%s# This output shows the current version of the unit's original fragment and drop-in files.\n"
5381 "%s# If fragments or drop-ins were added or removed, they are not properly reflected in this output.\n"
5382 "%s# Run 'systemctl%s daemon-reload' to reload units.%s\n",
5383 ansi_highlight_red(),
5384 *name,
5385 ansi_highlight_red(),
5386 ansi_highlight_red(),
5387 ansi_highlight_red(),
5388 arg_scope == UNIT_FILE_SYSTEM ? "" : " --user",
5389 ansi_normal());
5390
5391 if (fragment_path) {
5392 r = cat_file(fragment_path, false);
5393 if (r < 0)
5394 return log_warning_errno(r, "Failed to cat %s: %m", fragment_path);
5395 }
5396
5397 STRV_FOREACH(path, dropin_paths) {
5398 r = cat_file(*path, path == dropin_paths);
5399 if (r < 0)
5400 return log_warning_errno(r, "Failed to cat %s: %m", *path);
5401 }
5402 }
5403
5404 return 0;
5405 }
5406
5407 static int set_property(int argc, char *argv[], void *userdata) {
5408 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
5409 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5410 _cleanup_free_ char *n = NULL;
5411 UnitType t;
5412 sd_bus *bus;
5413 int r;
5414
5415 r = acquire_bus(BUS_MANAGER, &bus);
5416 if (r < 0)
5417 return r;
5418
5419 polkit_agent_open_maybe();
5420
5421 r = sd_bus_message_new_method_call(
5422 bus,
5423 &m,
5424 "org.freedesktop.systemd1",
5425 "/org/freedesktop/systemd1",
5426 "org.freedesktop.systemd1.Manager",
5427 "SetUnitProperties");
5428 if (r < 0)
5429 return bus_log_create_error(r);
5430
5431 r = unit_name_mangle(argv[1], arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, &n);
5432 if (r < 0)
5433 return log_error_errno(r, "Failed to mangle unit name: %m");
5434
5435 t = unit_name_to_type(n);
5436 if (t < 0) {
5437 log_error("Invalid unit type: %s", n);
5438 return -EINVAL;
5439 }
5440
5441 r = sd_bus_message_append(m, "sb", n, arg_runtime);
5442 if (r < 0)
5443 return bus_log_create_error(r);
5444
5445 r = sd_bus_message_open_container(m, SD_BUS_TYPE_ARRAY, "(sv)");
5446 if (r < 0)
5447 return bus_log_create_error(r);
5448
5449 r = bus_append_unit_property_assignment_many(m, t, strv_skip(argv, 2));
5450 if (r < 0)
5451 return r;
5452
5453 r = sd_bus_message_close_container(m);
5454 if (r < 0)
5455 return bus_log_create_error(r);
5456
5457 r = sd_bus_call(bus, m, 0, &error, NULL);
5458 if (r < 0)
5459 return log_error_errno(r, "Failed to set unit properties on %s: %s", n, bus_error_message(&error, r));
5460
5461 return 0;
5462 }
5463
5464 static int daemon_reload(int argc, char *argv[], void *userdata) {
5465 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5466 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
5467 const char *method;
5468 sd_bus *bus;
5469 int r;
5470
5471 r = acquire_bus(BUS_MANAGER, &bus);
5472 if (r < 0)
5473 return r;
5474
5475 polkit_agent_open_maybe();
5476
5477 switch (arg_action) {
5478
5479 case ACTION_RELOAD:
5480 method = "Reload";
5481 break;
5482
5483 case ACTION_REEXEC:
5484 method = "Reexecute";
5485 break;
5486
5487 case ACTION_SYSTEMCTL:
5488 method = streq(argv[0], "daemon-reexec") ? "Reexecute" :
5489 /* "daemon-reload" */ "Reload";
5490 break;
5491
5492 default:
5493 assert_not_reached("Unexpected action");
5494 }
5495
5496 r = sd_bus_message_new_method_call(
5497 bus,
5498 &m,
5499 "org.freedesktop.systemd1",
5500 "/org/freedesktop/systemd1",
5501 "org.freedesktop.systemd1.Manager",
5502 method);
5503 if (r < 0)
5504 return bus_log_create_error(r);
5505
5506 /* Note we use an extra-long timeout here. This is because a reload or reexec means generators are rerun which
5507 * are timed out after DEFAULT_TIMEOUT_USEC. Let's use twice that time here, so that the generators can have
5508 * their timeout, and for everything else there's the same time budget in place. */
5509
5510 r = sd_bus_call(bus, m, DEFAULT_TIMEOUT_USEC * 2, &error, NULL);
5511
5512 /* On reexecution, we expect a disconnect, not a reply */
5513 if (IN_SET(r, -ETIMEDOUT, -ECONNRESET) && streq(method, "Reexecute"))
5514 r = 0;
5515
5516 if (r < 0 && arg_action == ACTION_SYSTEMCTL)
5517 return log_error_errno(r, "Failed to reload daemon: %s", bus_error_message(&error, r));
5518
5519 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
5520 * old ways of doing things, hence don't log any error in that case here. */
5521
5522 return r < 0 ? r : 0;
5523 }
5524
5525 static int trivial_method(int argc, char *argv[], void *userdata) {
5526 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5527 const char *method;
5528 sd_bus *bus;
5529 int r;
5530
5531 if (arg_dry_run)
5532 return 0;
5533
5534 r = acquire_bus(BUS_MANAGER, &bus);
5535 if (r < 0)
5536 return r;
5537
5538 polkit_agent_open_maybe();
5539
5540 method =
5541 streq(argv[0], "clear-jobs") ||
5542 streq(argv[0], "cancel") ? "ClearJobs" :
5543 streq(argv[0], "reset-failed") ? "ResetFailed" :
5544 streq(argv[0], "halt") ? "Halt" :
5545 streq(argv[0], "reboot") ? "Reboot" :
5546 streq(argv[0], "kexec") ? "KExec" :
5547 streq(argv[0], "exit") ? "Exit" :
5548 /* poweroff */ "PowerOff";
5549
5550 r = sd_bus_call_method(
5551 bus,
5552 "org.freedesktop.systemd1",
5553 "/org/freedesktop/systemd1",
5554 "org.freedesktop.systemd1.Manager",
5555 method,
5556 &error,
5557 NULL,
5558 NULL);
5559 if (r < 0 && arg_action == ACTION_SYSTEMCTL)
5560 return log_error_errno(r, "Failed to execute operation: %s", bus_error_message(&error, r));
5561
5562 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
5563 * old ways of doing things, hence don't log any error in that case here. */
5564
5565 return r < 0 ? r : 0;
5566 }
5567
5568 static int reset_failed(int argc, char *argv[], void *userdata) {
5569 _cleanup_strv_free_ char **names = NULL;
5570 sd_bus *bus;
5571 char **name;
5572 int r, q;
5573
5574 if (argc <= 1)
5575 return trivial_method(argc, argv, userdata);
5576
5577 r = acquire_bus(BUS_MANAGER, &bus);
5578 if (r < 0)
5579 return r;
5580
5581 polkit_agent_open_maybe();
5582
5583 r = expand_names(bus, strv_skip(argv, 1), NULL, &names);
5584 if (r < 0)
5585 return log_error_errno(r, "Failed to expand names: %m");
5586
5587 STRV_FOREACH(name, names) {
5588 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5589
5590 q = sd_bus_call_method(
5591 bus,
5592 "org.freedesktop.systemd1",
5593 "/org/freedesktop/systemd1",
5594 "org.freedesktop.systemd1.Manager",
5595 "ResetFailedUnit",
5596 &error,
5597 NULL,
5598 "s", *name);
5599 if (q < 0) {
5600 log_error_errno(q, "Failed to reset failed state of unit %s: %s", *name, bus_error_message(&error, q));
5601 if (r == 0)
5602 r = q;
5603 }
5604 }
5605
5606 return r;
5607 }
5608
5609 static int print_variable(const char *s) {
5610 const char *sep;
5611 _cleanup_free_ char *esc = NULL;
5612
5613 sep = strchr(s, '=');
5614 if (!sep) {
5615 log_error("Invalid environment block");
5616 return -EUCLEAN;
5617 }
5618
5619 esc = shell_maybe_quote(sep + 1, ESCAPE_POSIX);
5620 if (!esc)
5621 return log_oom();
5622
5623 printf("%.*s=%s\n", (int)(sep-s), s, esc);
5624 return 0;
5625 }
5626
5627 static int show_environment(int argc, char *argv[], void *userdata) {
5628 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5629 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
5630 const char *text;
5631 sd_bus *bus;
5632 int r;
5633
5634 r = acquire_bus(BUS_MANAGER, &bus);
5635 if (r < 0)
5636 return r;
5637
5638 (void) pager_open(arg_no_pager, false);
5639
5640 r = sd_bus_get_property(
5641 bus,
5642 "org.freedesktop.systemd1",
5643 "/org/freedesktop/systemd1",
5644 "org.freedesktop.systemd1.Manager",
5645 "Environment",
5646 &error,
5647 &reply,
5648 "as");
5649 if (r < 0)
5650 return log_error_errno(r, "Failed to get environment: %s", bus_error_message(&error, r));
5651
5652 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "s");
5653 if (r < 0)
5654 return bus_log_parse_error(r);
5655
5656 while ((r = sd_bus_message_read_basic(reply, SD_BUS_TYPE_STRING, &text)) > 0) {
5657 r = print_variable(text);
5658 if (r < 0)
5659 return r;
5660 }
5661 if (r < 0)
5662 return bus_log_parse_error(r);
5663
5664 r = sd_bus_message_exit_container(reply);
5665 if (r < 0)
5666 return bus_log_parse_error(r);
5667
5668 return 0;
5669 }
5670
5671 static int switch_root(int argc, char *argv[], void *userdata) {
5672 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5673 _cleanup_free_ char *cmdline_init = NULL;
5674 const char *root, *init;
5675 sd_bus *bus;
5676 int r;
5677
5678 if (arg_transport != BUS_TRANSPORT_LOCAL) {
5679 log_error("Cannot switch root remotely.");
5680 return -EINVAL;
5681 }
5682
5683 if (argc < 2 || argc > 3) {
5684 log_error("Wrong number of arguments.");
5685 return -EINVAL;
5686 }
5687
5688 root = argv[1];
5689
5690 if (argc >= 3)
5691 init = argv[2];
5692 else {
5693 r = parse_env_file("/proc/cmdline", WHITESPACE,
5694 "init", &cmdline_init,
5695 NULL);
5696 if (r < 0)
5697 log_debug_errno(r, "Failed to parse /proc/cmdline: %m");
5698
5699 init = cmdline_init;
5700 }
5701
5702 init = empty_to_null(init);
5703 if (init) {
5704 const char *root_systemd_path = NULL, *root_init_path = NULL;
5705
5706 root_systemd_path = strjoina(root, "/" SYSTEMD_BINARY_PATH);
5707 root_init_path = strjoina(root, "/", init);
5708
5709 /* If the passed init is actually the same as the
5710 * systemd binary, then let's suppress it. */
5711 if (files_same(root_init_path, root_systemd_path, 0) > 0)
5712 init = NULL;
5713 }
5714
5715 /* Instruct PID1 to exclude us from its killing spree applied during
5716 * the transition. Otherwise we would exit with a failure status even
5717 * though the switch to the new root has succeed. */
5718 argv_cmdline[0] = '@';
5719
5720 r = acquire_bus(BUS_MANAGER, &bus);
5721 if (r < 0)
5722 return r;
5723
5724 /* If we are slow to exit after the root switch, the new systemd instance
5725 * will send us a signal to terminate. Just ignore it and exit normally.
5726 * This way the unit does not end up as failed.
5727 */
5728 r = ignore_signals(SIGTERM, -1);
5729 if (r < 0)
5730 log_warning_errno(r, "Failed to change disposition of SIGTERM to ignore: %m");
5731
5732 log_debug("Switching root - root: %s; init: %s", root, strna(init));
5733
5734 r = sd_bus_call_method(
5735 bus,
5736 "org.freedesktop.systemd1",
5737 "/org/freedesktop/systemd1",
5738 "org.freedesktop.systemd1.Manager",
5739 "SwitchRoot",
5740 &error,
5741 NULL,
5742 "ss", root, init);
5743 if (r < 0) {
5744 (void) default_signals(SIGTERM, -1);
5745
5746 return log_error_errno(r, "Failed to switch root: %s", bus_error_message(&error, r));
5747 }
5748
5749 return 0;
5750 }
5751
5752 static int set_environment(int argc, char *argv[], void *userdata) {
5753 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5754 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
5755 const char *method;
5756 sd_bus *bus;
5757 int r;
5758
5759 assert(argc > 1);
5760 assert(argv);
5761
5762 r = acquire_bus(BUS_MANAGER, &bus);
5763 if (r < 0)
5764 return r;
5765
5766 polkit_agent_open_maybe();
5767
5768 method = streq(argv[0], "set-environment")
5769 ? "SetEnvironment"
5770 : "UnsetEnvironment";
5771
5772 r = sd_bus_message_new_method_call(
5773 bus,
5774 &m,
5775 "org.freedesktop.systemd1",
5776 "/org/freedesktop/systemd1",
5777 "org.freedesktop.systemd1.Manager",
5778 method);
5779 if (r < 0)
5780 return bus_log_create_error(r);
5781
5782 r = sd_bus_message_append_strv(m, strv_skip(argv, 1));
5783 if (r < 0)
5784 return bus_log_create_error(r);
5785
5786 r = sd_bus_call(bus, m, 0, &error, NULL);
5787 if (r < 0)
5788 return log_error_errno(r, "Failed to set environment: %s", bus_error_message(&error, r));
5789
5790 return 0;
5791 }
5792
5793 static int import_environment(int argc, char *argv[], void *userdata) {
5794 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5795 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
5796 sd_bus *bus;
5797 int r;
5798
5799 r = acquire_bus(BUS_MANAGER, &bus);
5800 if (r < 0)
5801 return r;
5802
5803 polkit_agent_open_maybe();
5804
5805 r = sd_bus_message_new_method_call(
5806 bus,
5807 &m,
5808 "org.freedesktop.systemd1",
5809 "/org/freedesktop/systemd1",
5810 "org.freedesktop.systemd1.Manager",
5811 "SetEnvironment");
5812 if (r < 0)
5813 return bus_log_create_error(r);
5814
5815 if (argc < 2)
5816 r = sd_bus_message_append_strv(m, environ);
5817 else {
5818 char **a, **b;
5819
5820 r = sd_bus_message_open_container(m, 'a', "s");
5821 if (r < 0)
5822 return bus_log_create_error(r);
5823
5824 STRV_FOREACH(a, strv_skip(argv, 1)) {
5825
5826 if (!env_name_is_valid(*a)) {
5827 log_error("Not a valid environment variable name: %s", *a);
5828 return -EINVAL;
5829 }
5830
5831 STRV_FOREACH(b, environ) {
5832 const char *eq;
5833
5834 eq = startswith(*b, *a);
5835 if (eq && *eq == '=') {
5836
5837 r = sd_bus_message_append(m, "s", *b);
5838 if (r < 0)
5839 return bus_log_create_error(r);
5840
5841 break;
5842 }
5843 }
5844 }
5845
5846 r = sd_bus_message_close_container(m);
5847 }
5848 if (r < 0)
5849 return bus_log_create_error(r);
5850
5851 r = sd_bus_call(bus, m, 0, &error, NULL);
5852 if (r < 0)
5853 return log_error_errno(r, "Failed to import environment: %s", bus_error_message(&error, r));
5854
5855 return 0;
5856 }
5857
5858 static int enable_sysv_units(const char *verb, char **args) {
5859 int r = 0;
5860
5861 #if HAVE_SYSV_COMPAT
5862 _cleanup_(lookup_paths_free) LookupPaths paths = {};
5863 unsigned f = 0;
5864
5865 /* Processes all SysV units, and reshuffles the array so that afterwards only the native units remain */
5866
5867 if (arg_scope != UNIT_FILE_SYSTEM)
5868 return 0;
5869
5870 if (getenv_bool("SYSTEMCTL_SKIP_SYSV") > 0)
5871 return 0;
5872
5873 if (!STR_IN_SET(verb,
5874 "enable",
5875 "disable",
5876 "is-enabled"))
5877 return 0;
5878
5879 r = lookup_paths_init(&paths, arg_scope, LOOKUP_PATHS_EXCLUDE_GENERATED, arg_root);
5880 if (r < 0)
5881 return r;
5882
5883 r = 0;
5884 while (args[f]) {
5885
5886 const char *argv[] = {
5887 ROOTLIBEXECDIR "/systemd-sysv-install",
5888 NULL,
5889 NULL,
5890 NULL,
5891 NULL,
5892 };
5893
5894 _cleanup_free_ char *p = NULL, *q = NULL, *l = NULL;
5895 bool found_native = false, found_sysv;
5896 const char *name;
5897 unsigned c = 1;
5898 pid_t pid;
5899 int j;
5900
5901 name = args[f++];
5902
5903 if (!endswith(name, ".service"))
5904 continue;
5905
5906 if (path_is_absolute(name))
5907 continue;
5908
5909 j = unit_file_exists(arg_scope, &paths, name);
5910 if (j < 0 && !IN_SET(j, -ELOOP, -ERFKILL, -EADDRNOTAVAIL))
5911 return log_error_errno(j, "Failed to lookup unit file state: %m");
5912 found_native = j != 0;
5913
5914 /* If we have both a native unit and a SysV script, enable/disable them both (below); for is-enabled,
5915 * prefer the native unit */
5916 if (found_native && streq(verb, "is-enabled"))
5917 continue;
5918
5919 p = path_join(arg_root, SYSTEM_SYSVINIT_PATH, name);
5920 if (!p)
5921 return log_oom();
5922
5923 p[strlen(p) - STRLEN(".service")] = 0;
5924 found_sysv = access(p, F_OK) >= 0;
5925 if (!found_sysv)
5926 continue;
5927
5928 if (!arg_quiet) {
5929 if (found_native)
5930 log_info("Synchronizing state of %s with SysV service script with %s.", name, argv[0]);
5931 else
5932 log_info("%s is not a native service, redirecting to systemd-sysv-install.", name);
5933 }
5934
5935 if (!isempty(arg_root))
5936 argv[c++] = q = strappend("--root=", arg_root);
5937
5938 argv[c++] = verb;
5939 argv[c++] = basename(p);
5940 argv[c] = NULL;
5941
5942 l = strv_join((char**)argv, " ");
5943 if (!l)
5944 return log_oom();
5945
5946 if (!arg_quiet)
5947 log_info("Executing: %s", l);
5948
5949 j = safe_fork("(sysv-install)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_LOG, &pid);
5950 if (j < 0)
5951 return j;
5952 if (j == 0) {
5953 /* Child */
5954 execv(argv[0], (char**) argv);
5955 log_error_errno(errno, "Failed to execute %s: %m", argv[0]);
5956 _exit(EXIT_FAILURE);
5957 }
5958
5959 j = wait_for_terminate_and_check("sysv-install", pid, WAIT_LOG_ABNORMAL);
5960 if (j < 0)
5961 return j;
5962 if (streq(verb, "is-enabled")) {
5963 if (j == EXIT_SUCCESS) {
5964 if (!arg_quiet)
5965 puts("enabled");
5966 r = 1;
5967 } else {
5968 if (!arg_quiet)
5969 puts("disabled");
5970 }
5971
5972 } else if (j != EXIT_SUCCESS)
5973 return -EBADE; /* We don't warn here, under the assumption the script already showed an explanation */
5974
5975 if (found_native)
5976 continue;
5977
5978 /* Remove this entry, so that we don't try enabling it as native unit */
5979 assert(f > 0);
5980 f--;
5981 assert(args[f] == name);
5982 strv_remove(args, name);
5983 }
5984
5985 #endif
5986 return r;
5987 }
5988
5989 static int mangle_names(char **original_names, char ***mangled_names) {
5990 char **i, **l, **name;
5991 int r;
5992
5993 l = i = new(char*, strv_length(original_names) + 1);
5994 if (!l)
5995 return log_oom();
5996
5997 STRV_FOREACH(name, original_names) {
5998
5999 /* When enabling units qualified path names are OK,
6000 * too, hence allow them explicitly. */
6001
6002 if (is_path(*name)) {
6003 *i = strdup(*name);
6004 if (!*i) {
6005 strv_free(l);
6006 return log_oom();
6007 }
6008 } else {
6009 r = unit_name_mangle(*name, arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, i);
6010 if (r < 0) {
6011 *i = NULL;
6012 strv_free(l);
6013 return log_error_errno(r, "Failed to mangle unit name: %m");
6014 }
6015 }
6016
6017 i++;
6018 }
6019
6020 *i = NULL;
6021 *mangled_names = l;
6022
6023 return 0;
6024 }
6025
6026 static int normalize_filenames(char **names) {
6027 char **u;
6028 int r;
6029
6030 STRV_FOREACH(u, names)
6031 if (!path_is_absolute(*u)) {
6032 char* normalized_path;
6033
6034 if (!isempty(arg_root)) {
6035 log_error("Non-absolute paths are not allowed when --root is used: %s", *u);
6036 return -EINVAL;
6037 }
6038
6039 if (!strchr(*u,'/')) {
6040 log_error("Link argument does contain at least one directory separator: %s", *u);
6041 return -EINVAL;
6042 }
6043
6044 r = path_make_absolute_cwd(*u, &normalized_path);
6045 if (r < 0)
6046 return r;
6047
6048 free_and_replace(*u, normalized_path);
6049 }
6050
6051 return 0;
6052 }
6053
6054 static int normalize_names(char **names, bool warn_if_path) {
6055 char **u;
6056 bool was_path = false;
6057
6058 STRV_FOREACH(u, names) {
6059 int r;
6060
6061 if (!is_path(*u))
6062 continue;
6063
6064 r = free_and_strdup(u, basename(*u));
6065 if (r < 0)
6066 return log_error_errno(r, "Failed to normalize unit file path: %m");
6067
6068 was_path = true;
6069 }
6070
6071 if (warn_if_path && was_path)
6072 log_warning("Warning: Can't execute disable on the unit file path. Proceeding with the unit name.");
6073
6074 return 0;
6075 }
6076
6077 static int unit_exists(LookupPaths *lp, const char *unit) {
6078 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6079 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
6080 _cleanup_free_ char *path = NULL;
6081 static const struct bus_properties_map property_map[] = {
6082 { "LoadState", "s", NULL, offsetof(UnitStatusInfo, load_state) },
6083 { "ActiveState", "s", NULL, offsetof(UnitStatusInfo, active_state)},
6084 {},
6085 };
6086 UnitStatusInfo info = {};
6087 sd_bus *bus;
6088 int r;
6089
6090 if (unit_name_is_valid(unit, UNIT_NAME_TEMPLATE))
6091 return unit_find_template_path(unit, lp, NULL, NULL);
6092
6093 path = unit_dbus_path_from_name(unit);
6094 if (!path)
6095 return log_oom();
6096
6097 r = acquire_bus(BUS_MANAGER, &bus);
6098 if (r < 0)
6099 return r;
6100
6101 r = bus_map_all_properties(bus, "org.freedesktop.systemd1", path, property_map, 0, &error, &m, &info);
6102 if (r < 0)
6103 return log_error_errno(r, "Failed to get properties: %s", bus_error_message(&error, r));
6104
6105 return !streq_ptr(info.load_state, "not-found") || !streq_ptr(info.active_state, "inactive");
6106 }
6107
6108 static int enable_unit(int argc, char *argv[], void *userdata) {
6109 _cleanup_strv_free_ char **names = NULL;
6110 const char *verb = argv[0];
6111 UnitFileChange *changes = NULL;
6112 size_t n_changes = 0;
6113 int carries_install_info = -1;
6114 bool ignore_carries_install_info = arg_quiet;
6115 int r;
6116
6117 if (!argv[1])
6118 return 0;
6119
6120 r = mangle_names(strv_skip(argv, 1), &names);
6121 if (r < 0)
6122 return r;
6123
6124 r = enable_sysv_units(verb, names);
6125 if (r < 0)
6126 return r;
6127
6128 /* If the operation was fully executed by the SysV compat, let's finish early */
6129 if (strv_isempty(names)) {
6130 if (arg_no_reload || install_client_side())
6131 return 0;
6132 return daemon_reload(argc, argv, userdata);
6133 }
6134
6135 if (streq(verb, "disable")) {
6136 r = normalize_names(names, true);
6137 if (r < 0)
6138 return r;
6139 }
6140
6141 if (streq(verb, "link")) {
6142 r = normalize_filenames(names);
6143 if (r < 0)
6144 return r;
6145 }
6146
6147 if (install_client_side()) {
6148 UnitFileFlags flags;
6149
6150 flags = args_to_flags();
6151 if (streq(verb, "enable")) {
6152 r = unit_file_enable(arg_scope, flags, arg_root, names, &changes, &n_changes);
6153 carries_install_info = r;
6154 } else if (streq(verb, "disable"))
6155 r = unit_file_disable(arg_scope, flags, arg_root, names, &changes, &n_changes);
6156 else if (streq(verb, "reenable")) {
6157 r = unit_file_reenable(arg_scope, flags, arg_root, names, &changes, &n_changes);
6158 carries_install_info = r;
6159 } else if (streq(verb, "link"))
6160 r = unit_file_link(arg_scope, flags, arg_root, names, &changes, &n_changes);
6161 else if (streq(verb, "preset")) {
6162 r = unit_file_preset(arg_scope, flags, arg_root, names, arg_preset_mode, &changes, &n_changes);
6163 } else if (streq(verb, "mask"))
6164 r = unit_file_mask(arg_scope, flags, arg_root, names, &changes, &n_changes);
6165 else if (streq(verb, "unmask"))
6166 r = unit_file_unmask(arg_scope, flags, arg_root, names, &changes, &n_changes);
6167 else if (streq(verb, "revert"))
6168 r = unit_file_revert(arg_scope, arg_root, names, &changes, &n_changes);
6169 else
6170 assert_not_reached("Unknown verb");
6171
6172 unit_file_dump_changes(r, verb, changes, n_changes, arg_quiet);
6173 if (r < 0)
6174 goto finish;
6175 r = 0;
6176 } else {
6177 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL, *m = NULL;
6178 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6179 bool expect_carries_install_info = false;
6180 bool send_runtime = true, send_force = true, send_preset_mode = false;
6181 const char *method;
6182 sd_bus *bus;
6183
6184 if (STR_IN_SET(verb, "mask", "unmask")) {
6185 char **name;
6186 _cleanup_(lookup_paths_free) LookupPaths lp = {};
6187
6188 r = lookup_paths_init(&lp, arg_scope, 0, arg_root);
6189 if (r < 0)
6190 return r;
6191
6192 STRV_FOREACH(name, names) {
6193 r = unit_exists(&lp, *name);
6194 if (r < 0)
6195 return r;
6196 if (r == 0)
6197 log_notice("Unit %s does not exist, proceeding anyway.", *names);
6198 }
6199 }
6200
6201 r = acquire_bus(BUS_MANAGER, &bus);
6202 if (r < 0)
6203 return r;
6204
6205 polkit_agent_open_maybe();
6206
6207 if (streq(verb, "enable")) {
6208 method = "EnableUnitFiles";
6209 expect_carries_install_info = true;
6210 } else if (streq(verb, "disable")) {
6211 method = "DisableUnitFiles";
6212 send_force = false;
6213 } else if (streq(verb, "reenable")) {
6214 method = "ReenableUnitFiles";
6215 expect_carries_install_info = true;
6216 } else if (streq(verb, "link"))
6217 method = "LinkUnitFiles";
6218 else if (streq(verb, "preset")) {
6219
6220 if (arg_preset_mode != UNIT_FILE_PRESET_FULL) {
6221 method = "PresetUnitFilesWithMode";
6222 send_preset_mode = true;
6223 } else
6224 method = "PresetUnitFiles";
6225
6226 expect_carries_install_info = true;
6227 ignore_carries_install_info = true;
6228 } else if (streq(verb, "mask"))
6229 method = "MaskUnitFiles";
6230 else if (streq(verb, "unmask")) {
6231 method = "UnmaskUnitFiles";
6232 send_force = false;
6233 } else if (streq(verb, "revert")) {
6234 method = "RevertUnitFiles";
6235 send_runtime = send_force = false;
6236 } else
6237 assert_not_reached("Unknown verb");
6238
6239 r = sd_bus_message_new_method_call(
6240 bus,
6241 &m,
6242 "org.freedesktop.systemd1",
6243 "/org/freedesktop/systemd1",
6244 "org.freedesktop.systemd1.Manager",
6245 method);
6246 if (r < 0)
6247 return bus_log_create_error(r);
6248
6249 r = sd_bus_message_append_strv(m, names);
6250 if (r < 0)
6251 return bus_log_create_error(r);
6252
6253 if (send_preset_mode) {
6254 r = sd_bus_message_append(m, "s", unit_file_preset_mode_to_string(arg_preset_mode));
6255 if (r < 0)
6256 return bus_log_create_error(r);
6257 }
6258
6259 if (send_runtime) {
6260 r = sd_bus_message_append(m, "b", arg_runtime);
6261 if (r < 0)
6262 return bus_log_create_error(r);
6263 }
6264
6265 if (send_force) {
6266 r = sd_bus_message_append(m, "b", arg_force);
6267 if (r < 0)
6268 return bus_log_create_error(r);
6269 }
6270
6271 r = sd_bus_call(bus, m, 0, &error, &reply);
6272 if (r < 0)
6273 return log_error_errno(r, "Failed to %s unit: %s", verb, bus_error_message(&error, r));
6274
6275 if (expect_carries_install_info) {
6276 r = sd_bus_message_read(reply, "b", &carries_install_info);
6277 if (r < 0)
6278 return bus_log_parse_error(r);
6279 }
6280
6281 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
6282 if (r < 0)
6283 goto finish;
6284
6285 /* Try to reload if enabled */
6286 if (!arg_no_reload)
6287 r = daemon_reload(argc, argv, userdata);
6288 else
6289 r = 0;
6290 }
6291
6292 if (carries_install_info == 0 && !ignore_carries_install_info)
6293 log_warning("The unit files have no installation config (WantedBy, RequiredBy, Also, Alias\n"
6294 "settings in the [Install] section, and DefaultInstance for template units).\n"
6295 "This means they are not meant to be enabled using systemctl.\n"
6296 "Possible reasons for having this kind of units are:\n"
6297 "1) A unit may be statically enabled by being symlinked from another unit's\n"
6298 " .wants/ or .requires/ directory.\n"
6299 "2) A unit's purpose may be to act as a helper for some other unit which has\n"
6300 " a requirement dependency on it.\n"
6301 "3) A unit may be started when needed via activation (socket, path, timer,\n"
6302 " D-Bus, udev, scripted systemctl call, ...).\n"
6303 "4) In case of template units, the unit is meant to be enabled with some\n"
6304 " instance name specified.");
6305
6306 if (arg_now && STR_IN_SET(argv[0], "enable", "disable", "mask")) {
6307 sd_bus *bus;
6308 size_t len, i;
6309
6310 r = acquire_bus(BUS_MANAGER, &bus);
6311 if (r < 0)
6312 goto finish;
6313
6314 len = strv_length(names);
6315 {
6316 char *new_args[len + 2];
6317
6318 new_args[0] = (char*) (streq(argv[0], "enable") ? "start" : "stop");
6319 for (i = 0; i < len; i++)
6320 new_args[i + 1] = basename(names[i]);
6321 new_args[i + 1] = NULL;
6322
6323 r = start_unit(len + 1, new_args, userdata);
6324 }
6325 }
6326
6327 finish:
6328 unit_file_changes_free(changes, n_changes);
6329
6330 return r;
6331 }
6332
6333 static int add_dependency(int argc, char *argv[], void *userdata) {
6334 _cleanup_strv_free_ char **names = NULL;
6335 _cleanup_free_ char *target = NULL;
6336 const char *verb = argv[0];
6337 UnitFileChange *changes = NULL;
6338 size_t n_changes = 0;
6339 UnitDependency dep;
6340 int r = 0;
6341
6342 if (!argv[1])
6343 return 0;
6344
6345 r = unit_name_mangle_with_suffix(argv[1], arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, ".target", &target);
6346 if (r < 0)
6347 return log_error_errno(r, "Failed to mangle unit name: %m");
6348
6349 r = mangle_names(strv_skip(argv, 2), &names);
6350 if (r < 0)
6351 return r;
6352
6353 if (streq(verb, "add-wants"))
6354 dep = UNIT_WANTS;
6355 else if (streq(verb, "add-requires"))
6356 dep = UNIT_REQUIRES;
6357 else
6358 assert_not_reached("Unknown verb");
6359
6360 if (install_client_side()) {
6361 r = unit_file_add_dependency(arg_scope, args_to_flags(), arg_root, names, target, dep, &changes, &n_changes);
6362 unit_file_dump_changes(r, "add dependency on", changes, n_changes, arg_quiet);
6363
6364 if (r > 0)
6365 r = 0;
6366 } else {
6367 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL, *m = NULL;
6368 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6369 sd_bus *bus;
6370
6371 r = acquire_bus(BUS_MANAGER, &bus);
6372 if (r < 0)
6373 return r;
6374
6375 polkit_agent_open_maybe();
6376
6377 r = sd_bus_message_new_method_call(
6378 bus,
6379 &m,
6380 "org.freedesktop.systemd1",
6381 "/org/freedesktop/systemd1",
6382 "org.freedesktop.systemd1.Manager",
6383 "AddDependencyUnitFiles");
6384 if (r < 0)
6385 return bus_log_create_error(r);
6386
6387 r = sd_bus_message_append_strv(m, names);
6388 if (r < 0)
6389 return bus_log_create_error(r);
6390
6391 r = sd_bus_message_append(m, "ssbb", target, unit_dependency_to_string(dep), arg_runtime, arg_force);
6392 if (r < 0)
6393 return bus_log_create_error(r);
6394
6395 r = sd_bus_call(bus, m, 0, &error, &reply);
6396 if (r < 0)
6397 return log_error_errno(r, "Failed to add dependency: %s", bus_error_message(&error, r));
6398
6399 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
6400 if (r < 0)
6401 goto finish;
6402
6403 if (arg_no_reload) {
6404 r = 0;
6405 goto finish;
6406 }
6407
6408 r = daemon_reload(argc, argv, userdata);
6409 }
6410
6411 finish:
6412 unit_file_changes_free(changes, n_changes);
6413
6414 return r;
6415 }
6416
6417 static int preset_all(int argc, char *argv[], void *userdata) {
6418 UnitFileChange *changes = NULL;
6419 size_t n_changes = 0;
6420 int r;
6421
6422 if (install_client_side()) {
6423 r = unit_file_preset_all(arg_scope, args_to_flags(), arg_root, arg_preset_mode, &changes, &n_changes);
6424 unit_file_dump_changes(r, "preset", changes, n_changes, arg_quiet);
6425
6426 if (r > 0)
6427 r = 0;
6428 } else {
6429 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6430 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
6431 sd_bus *bus;
6432
6433 r = acquire_bus(BUS_MANAGER, &bus);
6434 if (r < 0)
6435 return r;
6436
6437 polkit_agent_open_maybe();
6438
6439 r = sd_bus_call_method(
6440 bus,
6441 "org.freedesktop.systemd1",
6442 "/org/freedesktop/systemd1",
6443 "org.freedesktop.systemd1.Manager",
6444 "PresetAllUnitFiles",
6445 &error,
6446 &reply,
6447 "sbb",
6448 unit_file_preset_mode_to_string(arg_preset_mode),
6449 arg_runtime,
6450 arg_force);
6451 if (r < 0)
6452 return log_error_errno(r, "Failed to preset all units: %s", bus_error_message(&error, r));
6453
6454 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
6455 if (r < 0)
6456 goto finish;
6457
6458 if (arg_no_reload) {
6459 r = 0;
6460 goto finish;
6461 }
6462
6463 r = daemon_reload(argc, argv, userdata);
6464 }
6465
6466 finish:
6467 unit_file_changes_free(changes, n_changes);
6468
6469 return r;
6470 }
6471
6472 static int show_installation_targets_client_side(const char *name) {
6473 UnitFileChange *changes = NULL;
6474 size_t n_changes = 0, i;
6475 UnitFileFlags flags;
6476 char **p;
6477 int r;
6478
6479 p = STRV_MAKE(name);
6480 flags = UNIT_FILE_DRY_RUN |
6481 (arg_runtime ? UNIT_FILE_RUNTIME : 0);
6482
6483 r = unit_file_disable(UNIT_FILE_SYSTEM, flags, NULL, p, &changes, &n_changes);
6484 if (r < 0)
6485 return log_error_errno(r, "Failed to get file links for %s: %m", name);
6486
6487 for (i = 0; i < n_changes; i++)
6488 if (changes[i].type == UNIT_FILE_UNLINK)
6489 printf(" %s\n", changes[i].path);
6490
6491 return 0;
6492 }
6493
6494 static int show_installation_targets(sd_bus *bus, const char *name) {
6495 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
6496 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6497 const char *link;
6498 int r;
6499
6500 r = sd_bus_call_method(
6501 bus,
6502 "org.freedesktop.systemd1",
6503 "/org/freedesktop/systemd1",
6504 "org.freedesktop.systemd1.Manager",
6505 "GetUnitFileLinks",
6506 &error,
6507 &reply,
6508 "sb", name, arg_runtime);
6509 if (r < 0)
6510 return log_error_errno(r, "Failed to get unit file links for %s: %s", name, bus_error_message(&error, r));
6511
6512 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "s");
6513 if (r < 0)
6514 return bus_log_parse_error(r);
6515
6516 while ((r = sd_bus_message_read(reply, "s", &link)) > 0)
6517 printf(" %s\n", link);
6518
6519 if (r < 0)
6520 return bus_log_parse_error(r);
6521
6522 r = sd_bus_message_exit_container(reply);
6523 if (r < 0)
6524 return bus_log_parse_error(r);
6525
6526 return 0;
6527 }
6528
6529 static int unit_is_enabled(int argc, char *argv[], void *userdata) {
6530
6531 _cleanup_strv_free_ char **names = NULL;
6532 bool enabled;
6533 char **name;
6534 int r;
6535
6536 r = mangle_names(strv_skip(argv, 1), &names);
6537 if (r < 0)
6538 return r;
6539
6540 r = enable_sysv_units(argv[0], names);
6541 if (r < 0)
6542 return r;
6543
6544 enabled = r > 0;
6545
6546 if (install_client_side()) {
6547 STRV_FOREACH(name, names) {
6548 UnitFileState state;
6549
6550 r = unit_file_get_state(arg_scope, arg_root, *name, &state);
6551 if (r < 0)
6552 return log_error_errno(r, "Failed to get unit file state for %s: %m", *name);
6553
6554 if (IN_SET(state,
6555 UNIT_FILE_ENABLED,
6556 UNIT_FILE_ENABLED_RUNTIME,
6557 UNIT_FILE_STATIC,
6558 UNIT_FILE_INDIRECT,
6559 UNIT_FILE_GENERATED))
6560 enabled = true;
6561
6562 if (!arg_quiet) {
6563 puts(unit_file_state_to_string(state));
6564 if (arg_full) {
6565 r = show_installation_targets_client_side(*name);
6566 if (r < 0)
6567 return r;
6568 }
6569 }
6570 }
6571
6572 r = 0;
6573 } else {
6574 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6575 sd_bus *bus;
6576
6577 r = acquire_bus(BUS_MANAGER, &bus);
6578 if (r < 0)
6579 return r;
6580
6581 STRV_FOREACH(name, names) {
6582 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
6583 const char *s;
6584
6585 r = sd_bus_call_method(
6586 bus,
6587 "org.freedesktop.systemd1",
6588 "/org/freedesktop/systemd1",
6589 "org.freedesktop.systemd1.Manager",
6590 "GetUnitFileState",
6591 &error,
6592 &reply,
6593 "s", *name);
6594 if (r < 0)
6595 return log_error_errno(r, "Failed to get unit file state for %s: %s", *name, bus_error_message(&error, r));
6596
6597 r = sd_bus_message_read(reply, "s", &s);
6598 if (r < 0)
6599 return bus_log_parse_error(r);
6600
6601 if (STR_IN_SET(s, "enabled", "enabled-runtime", "static", "indirect", "generated"))
6602 enabled = true;
6603
6604 if (!arg_quiet) {
6605 puts(s);
6606 if (arg_full) {
6607 r = show_installation_targets(bus, *name);
6608 if (r < 0)
6609 return r;
6610 }
6611 }
6612 }
6613 }
6614
6615 return enabled ? EXIT_SUCCESS : EXIT_FAILURE;
6616 }
6617
6618 static int is_system_running(int argc, char *argv[], void *userdata) {
6619 _cleanup_free_ char *state = NULL;
6620 sd_bus *bus;
6621 int r;
6622
6623 if (running_in_chroot() > 0 || (arg_transport == BUS_TRANSPORT_LOCAL && !sd_booted())) {
6624 if (!arg_quiet)
6625 puts("offline");
6626 return EXIT_FAILURE;
6627 }
6628
6629 r = acquire_bus(BUS_MANAGER, &bus);
6630 if (r < 0)
6631 return r;
6632
6633 r = sd_bus_get_property_string(
6634 bus,
6635 "org.freedesktop.systemd1",
6636 "/org/freedesktop/systemd1",
6637 "org.freedesktop.systemd1.Manager",
6638 "SystemState",
6639 NULL,
6640 &state);
6641 if (r < 0) {
6642 if (!arg_quiet)
6643 puts("unknown");
6644 return 0;
6645 }
6646
6647 if (!arg_quiet)
6648 puts(state);
6649
6650 return streq(state, "running") ? EXIT_SUCCESS : EXIT_FAILURE;
6651 }
6652
6653 static int create_edit_temp_file(const char *new_path, const char *original_path, char **ret_tmp_fn) {
6654 _cleanup_free_ char *t = NULL;
6655 int r;
6656
6657 assert(new_path);
6658 assert(original_path);
6659 assert(ret_tmp_fn);
6660
6661 r = tempfn_random(new_path, NULL, &t);
6662 if (r < 0)
6663 return log_error_errno(r, "Failed to determine temporary filename for \"%s\": %m", new_path);
6664
6665 r = mkdir_parents(new_path, 0755);
6666 if (r < 0)
6667 return log_error_errno(r, "Failed to create directories for \"%s\": %m", new_path);
6668
6669 r = copy_file(original_path, t, 0, 0644, 0, COPY_REFLINK);
6670 if (r == -ENOENT) {
6671
6672 r = touch(t);
6673 if (r < 0)
6674 return log_error_errno(r, "Failed to create temporary file \"%s\": %m", t);
6675
6676 } else if (r < 0)
6677 return log_error_errno(r, "Failed to create temporary file for \"%s\": %m", new_path);
6678
6679 *ret_tmp_fn = TAKE_PTR(t);
6680
6681 return 0;
6682 }
6683
6684 static int get_file_to_edit(
6685 const LookupPaths *paths,
6686 const char *name,
6687 char **ret_path) {
6688
6689 _cleanup_free_ char *path = NULL, *run = NULL;
6690
6691 assert(name);
6692 assert(ret_path);
6693
6694 path = strjoin(paths->persistent_config, "/", name);
6695 if (!path)
6696 return log_oom();
6697
6698 if (arg_runtime) {
6699 run = strjoin(paths->runtime_config, "/", name);
6700 if (!run)
6701 return log_oom();
6702 }
6703
6704 if (arg_runtime) {
6705 if (access(path, F_OK) >= 0) {
6706 log_error("Refusing to create \"%s\" because it would be overridden by \"%s\" anyway.", run, path);
6707 return -EEXIST;
6708 }
6709
6710 *ret_path = TAKE_PTR(run);
6711 } else
6712 *ret_path = TAKE_PTR(path);
6713
6714 return 0;
6715 }
6716
6717 static int unit_file_create_new(
6718 const LookupPaths *paths,
6719 const char *unit_name,
6720 const char *suffix,
6721 char **ret_new_path,
6722 char **ret_tmp_path) {
6723
6724 char *tmp_new_path, *tmp_tmp_path, *ending;
6725 int r;
6726
6727 assert(unit_name);
6728 assert(ret_new_path);
6729 assert(ret_tmp_path);
6730
6731 ending = strjoina(unit_name, suffix);
6732 r = get_file_to_edit(paths, ending, &tmp_new_path);
6733 if (r < 0)
6734 return r;
6735
6736 r = create_edit_temp_file(tmp_new_path, tmp_new_path, &tmp_tmp_path);
6737 if (r < 0) {
6738 free(tmp_new_path);
6739 return r;
6740 }
6741
6742 *ret_new_path = tmp_new_path;
6743 *ret_tmp_path = tmp_tmp_path;
6744
6745 return 0;
6746 }
6747
6748 static int unit_file_create_copy(
6749 const LookupPaths *paths,
6750 const char *unit_name,
6751 const char *fragment_path,
6752 char **ret_new_path,
6753 char **ret_tmp_path) {
6754
6755 char *tmp_new_path, *tmp_tmp_path;
6756 int r;
6757
6758 assert(fragment_path);
6759 assert(unit_name);
6760 assert(ret_new_path);
6761 assert(ret_tmp_path);
6762
6763 r = get_file_to_edit(paths, unit_name, &tmp_new_path);
6764 if (r < 0)
6765 return r;
6766
6767 if (!path_equal(fragment_path, tmp_new_path) && access(tmp_new_path, F_OK) == 0) {
6768 char response;
6769
6770 r = ask_char(&response, "yn", "\"%s\" already exists. Overwrite with \"%s\"? [(y)es, (n)o] ", tmp_new_path, fragment_path);
6771 if (r < 0) {
6772 free(tmp_new_path);
6773 return r;
6774 }
6775 if (response != 'y') {
6776 log_warning("%s ignored", unit_name);
6777 free(tmp_new_path);
6778 return -EKEYREJECTED;
6779 }
6780 }
6781
6782 r = create_edit_temp_file(tmp_new_path, fragment_path, &tmp_tmp_path);
6783 if (r < 0) {
6784 free(tmp_new_path);
6785 return r;
6786 }
6787
6788 *ret_new_path = tmp_new_path;
6789 *ret_tmp_path = tmp_tmp_path;
6790
6791 return 0;
6792 }
6793
6794 static int run_editor(char **paths) {
6795 int r;
6796
6797 assert(paths);
6798
6799 r = safe_fork("(editor)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_LOG|FORK_WAIT, NULL);
6800 if (r < 0)
6801 return r;
6802 if (r == 0) {
6803 const char **args;
6804 char *editor, **editor_args = NULL;
6805 char **tmp_path, **original_path, *p;
6806 size_t n_editor_args = 0, i = 1;
6807 size_t argc;
6808
6809 argc = strv_length(paths)/2 + 1;
6810
6811 /* SYSTEMD_EDITOR takes precedence over EDITOR which takes precedence over VISUAL
6812 * If neither SYSTEMD_EDITOR nor EDITOR nor VISUAL are present,
6813 * we try to execute well known editors
6814 */
6815 editor = getenv("SYSTEMD_EDITOR");
6816 if (!editor)
6817 editor = getenv("EDITOR");
6818 if (!editor)
6819 editor = getenv("VISUAL");
6820
6821 if (!isempty(editor)) {
6822 editor_args = strv_split(editor, WHITESPACE);
6823 if (!editor_args) {
6824 (void) log_oom();
6825 _exit(EXIT_FAILURE);
6826 }
6827 n_editor_args = strv_length(editor_args);
6828 argc += n_editor_args - 1;
6829 }
6830 args = newa(const char*, argc + 1);
6831
6832 if (n_editor_args > 0) {
6833 args[0] = editor_args[0];
6834 for (; i < n_editor_args; i++)
6835 args[i] = editor_args[i];
6836 }
6837
6838 STRV_FOREACH_PAIR(original_path, tmp_path, paths) {
6839 args[i] = *tmp_path;
6840 i++;
6841 }
6842 args[i] = NULL;
6843
6844 if (n_editor_args > 0)
6845 execvp(args[0], (char* const*) args);
6846
6847 FOREACH_STRING(p, "editor", "nano", "vim", "vi") {
6848 args[0] = p;
6849 execvp(p, (char* const*) args);
6850 /* We do not fail if the editor doesn't exist
6851 * because we want to try each one of them before
6852 * failing.
6853 */
6854 if (errno != ENOENT) {
6855 log_error_errno(errno, "Failed to execute %s: %m", editor);
6856 _exit(EXIT_FAILURE);
6857 }
6858 }
6859
6860 log_error("Cannot edit unit(s), no editor available. Please set either $SYSTEMD_EDITOR, $EDITOR or $VISUAL.");
6861 _exit(EXIT_FAILURE);
6862 }
6863
6864 return 0;
6865 }
6866
6867 static int find_paths_to_edit(sd_bus *bus, char **names, char ***paths) {
6868 _cleanup_(lookup_paths_free) LookupPaths lp = {};
6869 char **name;
6870 int r;
6871
6872 assert(names);
6873 assert(paths);
6874
6875 r = lookup_paths_init(&lp, arg_scope, 0, arg_root);
6876 if (r < 0)
6877 return r;
6878
6879 STRV_FOREACH(name, names) {
6880 _cleanup_free_ char *path = NULL, *new_path = NULL, *tmp_path = NULL, *tmp_name = NULL;
6881 const char *unit_name;
6882
6883 r = unit_find_paths(bus, *name, &lp, &path, NULL);
6884 if (r < 0)
6885 return r;
6886
6887 if (r == 0) {
6888 assert(!path);
6889
6890 if (!arg_force) {
6891 log_error("Run 'systemctl edit%s --force %s' to create a new unit.",
6892 arg_scope == UNIT_FILE_GLOBAL ? " --global" :
6893 arg_scope == UNIT_FILE_USER ? " --user" : "",
6894 *name);
6895 return -ENOENT;
6896 }
6897
6898 /* Create a new unit from scratch */
6899 unit_name = *name;
6900 r = unit_file_create_new(&lp, unit_name,
6901 arg_full ? NULL : ".d/override.conf",
6902 &new_path, &tmp_path);
6903 } else {
6904 assert(path);
6905
6906 unit_name = basename(path);
6907 /* We follow unit aliases, but we need to propagate the instance */
6908 if (unit_name_is_valid(*name, UNIT_NAME_INSTANCE) &&
6909 unit_name_is_valid(unit_name, UNIT_NAME_TEMPLATE)) {
6910 _cleanup_free_ char *instance = NULL;
6911
6912 r = unit_name_to_instance(*name, &instance);
6913 if (r < 0)
6914 return r;
6915
6916 r = unit_name_replace_instance(unit_name, instance, &tmp_name);
6917 if (r < 0)
6918 return r;
6919
6920 unit_name = tmp_name;
6921 }
6922
6923 if (arg_full)
6924 r = unit_file_create_copy(&lp, unit_name, path, &new_path, &tmp_path);
6925 else
6926 r = unit_file_create_new(&lp, unit_name, ".d/override.conf", &new_path, &tmp_path);
6927 }
6928 if (r < 0)
6929 return r;
6930
6931 r = strv_push_pair(paths, new_path, tmp_path);
6932 if (r < 0)
6933 return log_oom();
6934 new_path = tmp_path = NULL;
6935 }
6936
6937 return 0;
6938 }
6939
6940 static int edit(int argc, char *argv[], void *userdata) {
6941 _cleanup_strv_free_ char **names = NULL;
6942 _cleanup_strv_free_ char **paths = NULL;
6943 char **original, **tmp;
6944 sd_bus *bus;
6945 int r;
6946
6947 if (!on_tty()) {
6948 log_error("Cannot edit units if not on a tty.");
6949 return -EINVAL;
6950 }
6951
6952 if (arg_transport != BUS_TRANSPORT_LOCAL) {
6953 log_error("Cannot edit units remotely.");
6954 return -EINVAL;
6955 }
6956
6957 r = acquire_bus(BUS_MANAGER, &bus);
6958 if (r < 0)
6959 return r;
6960
6961 r = expand_names(bus, strv_skip(argv, 1), NULL, &names);
6962 if (r < 0)
6963 return log_error_errno(r, "Failed to expand names: %m");
6964
6965 STRV_FOREACH(tmp, names) {
6966 r = unit_is_masked(bus, *tmp);
6967 if (r < 0)
6968 return r;
6969
6970 if (r > 0) {
6971 log_error("Cannot edit %s: unit is masked.", *tmp);
6972 return -EINVAL;
6973 }
6974 }
6975
6976 r = find_paths_to_edit(bus, names, &paths);
6977 if (r < 0)
6978 return r;
6979
6980 if (strv_isempty(paths))
6981 return -ENOENT;
6982
6983 r = run_editor(paths);
6984 if (r < 0)
6985 goto end;
6986
6987 STRV_FOREACH_PAIR(original, tmp, paths) {
6988 /* If the temporary file is empty we ignore it.
6989 * This allows the user to cancel the modification.
6990 */
6991 if (null_or_empty_path(*tmp)) {
6992 log_warning("Editing \"%s\" canceled: temporary file is empty.", *original);
6993 continue;
6994 }
6995
6996 r = rename(*tmp, *original);
6997 if (r < 0) {
6998 r = log_error_errno(errno, "Failed to rename \"%s\" to \"%s\": %m", *tmp, *original);
6999 goto end;
7000 }
7001 }
7002
7003 r = 0;
7004
7005 if (!arg_no_reload && !install_client_side())
7006 r = daemon_reload(argc, argv, userdata);
7007
7008 end:
7009 STRV_FOREACH_PAIR(original, tmp, paths) {
7010 (void) unlink(*tmp);
7011
7012 /* Removing empty dropin dirs */
7013 if (!arg_full) {
7014 _cleanup_free_ char *dir;
7015
7016 dir = dirname_malloc(*original);
7017 if (!dir)
7018 return log_oom();
7019
7020 /* no need to check if the dir is empty, rmdir
7021 * does nothing if it is not the case.
7022 */
7023 (void) rmdir(dir);
7024 }
7025 }
7026
7027 return r;
7028 }
7029
7030 static void systemctl_help(void) {
7031
7032 (void) pager_open(arg_no_pager, false);
7033
7034 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
7035 "Query or send control commands to the systemd manager.\n\n"
7036 " -h --help Show this help\n"
7037 " --version Show package version\n"
7038 " --system Connect to system manager\n"
7039 " --user Connect to user service manager\n"
7040 " -H --host=[USER@]HOST\n"
7041 " Operate on remote host\n"
7042 " -M --machine=CONTAINER\n"
7043 " Operate on local container\n"
7044 " -t --type=TYPE List units of a particular type\n"
7045 " --state=STATE List units with particular LOAD or SUB or ACTIVE state\n"
7046 " -p --property=NAME Show only properties by this name\n"
7047 " -a --all Show all properties/all units currently in memory,\n"
7048 " including dead/empty ones. To list all units installed on\n"
7049 " the system, use the 'list-unit-files' command instead.\n"
7050 " --failed Same as --state=failed\n"
7051 " -l --full Don't ellipsize unit names on output\n"
7052 " -r --recursive Show unit list of host and local containers\n"
7053 " --reverse Show reverse dependencies with 'list-dependencies'\n"
7054 " --job-mode=MODE Specify how to deal with already queued jobs, when\n"
7055 " queueing a new job\n"
7056 " --show-types When showing sockets, explicitly show their type\n"
7057 " --value When showing properties, only print the value\n"
7058 " -i --ignore-inhibitors\n"
7059 " When shutting down or sleeping, ignore inhibitors\n"
7060 " --kill-who=WHO Who to send signal to\n"
7061 " -s --signal=SIGNAL Which signal to send\n"
7062 " --now Start or stop unit in addition to enabling or disabling it\n"
7063 " --dry-run Only print what would be done\n"
7064 " -q --quiet Suppress output\n"
7065 " --wait For (re)start, wait until service stopped again\n"
7066 " --no-block Do not wait until operation finished\n"
7067 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7068 " --no-reload Don't reload daemon after en-/dis-abling unit files\n"
7069 " --no-legend Do not print a legend (column headers and hints)\n"
7070 " --no-pager Do not pipe output into a pager\n"
7071 " --no-ask-password\n"
7072 " Do not ask for system passwords\n"
7073 " --global Enable/disable/mask unit files globally\n"
7074 " --runtime Enable/disable/mask unit files temporarily until next\n"
7075 " reboot\n"
7076 " -f --force When enabling unit files, override existing symlinks\n"
7077 " When shutting down, execute action immediately\n"
7078 " --preset-mode= Apply only enable, only disable, or all presets\n"
7079 " --root=PATH Enable/disable/mask unit files in the specified root\n"
7080 " directory\n"
7081 " -n --lines=INTEGER Number of journal entries to show\n"
7082 " -o --output=STRING Change journal output mode (short, short-precise,\n"
7083 " short-iso, short-iso-precise, short-full,\n"
7084 " short-monotonic, short-unix,\n"
7085 " verbose, export, json, json-pretty, json-sse, cat)\n"
7086 " --firmware-setup Tell the firmware to show the setup menu on next boot\n"
7087 " --plain Print unit dependencies as a list instead of a tree\n\n"
7088 "Unit Commands:\n"
7089 " list-units [PATTERN...] List units currently in memory\n"
7090 " list-sockets [PATTERN...] List socket units currently in memory,\n"
7091 " ordered by address\n"
7092 " list-timers [PATTERN...] List timer units currently in memory,\n"
7093 " ordered by next elapse\n"
7094 " start UNIT... Start (activate) one or more units\n"
7095 " stop UNIT... Stop (deactivate) one or more units\n"
7096 " reload UNIT... Reload one or more units\n"
7097 " restart UNIT... Start or restart one or more units\n"
7098 " try-restart UNIT... Restart one or more units if active\n"
7099 " reload-or-restart UNIT... Reload one or more units if possible,\n"
7100 " otherwise start or restart\n"
7101 " try-reload-or-restart UNIT... If active, reload one or more units,\n"
7102 " if supported, otherwise restart\n"
7103 " isolate UNIT Start one unit and stop all others\n"
7104 " kill UNIT... Send signal to processes of a unit\n"
7105 " is-active PATTERN... Check whether units are active\n"
7106 " is-failed PATTERN... Check whether units are failed\n"
7107 " status [PATTERN...|PID...] Show runtime status of one or more units\n"
7108 " show [PATTERN...|JOB...] Show properties of one or more\n"
7109 " units/jobs or the manager\n"
7110 " cat PATTERN... Show files and drop-ins of specified units\n"
7111 " set-property UNIT PROPERTY=VALUE... Sets one or more properties of a unit\n"
7112 " help PATTERN...|PID... Show manual for one or more units\n"
7113 " reset-failed [PATTERN...] Reset failed state for all, one, or more\n"
7114 " units\n"
7115 " list-dependencies [UNIT] Recursively show units which are required\n"
7116 " or wanted by this unit or by which this\n"
7117 " unit is required or wanted\n\n"
7118 "Unit File Commands:\n"
7119 " list-unit-files [PATTERN...] List installed unit files\n"
7120 " enable [UNIT...|PATH...] Enable one or more unit files\n"
7121 " disable UNIT... Disable one or more unit files\n"
7122 " reenable UNIT... Reenable one or more unit files\n"
7123 " preset UNIT... Enable/disable one or more unit files\n"
7124 " based on preset configuration\n"
7125 " preset-all Enable/disable all unit files based on\n"
7126 " preset configuration\n"
7127 " is-enabled UNIT... Check whether unit files are enabled\n"
7128 " mask UNIT... Mask one or more units\n"
7129 " unmask UNIT... Unmask one or more units\n"
7130 " link PATH... Link one or more units files into\n"
7131 " the search path\n"
7132 " revert UNIT... Revert one or more unit files to vendor\n"
7133 " version\n"
7134 " add-wants TARGET UNIT... Add 'Wants' dependency for the target\n"
7135 " on specified one or more units\n"
7136 " add-requires TARGET UNIT... Add 'Requires' dependency for the target\n"
7137 " on specified one or more units\n"
7138 " edit UNIT... Edit one or more unit files\n"
7139 " get-default Get the name of the default target\n"
7140 " set-default TARGET Set the default target\n\n"
7141 "Machine Commands:\n"
7142 " list-machines [PATTERN...] List local containers and host\n\n"
7143 "Job Commands:\n"
7144 " list-jobs [PATTERN...] List jobs\n"
7145 " cancel [JOB...] Cancel all, one, or more jobs\n\n"
7146 "Environment Commands:\n"
7147 " show-environment Dump environment\n"
7148 " set-environment VARIABLE=VALUE... Set one or more environment variables\n"
7149 " unset-environment VARIABLE... Unset one or more environment variables\n"
7150 " import-environment [VARIABLE...] Import all or some environment variables\n\n"
7151 "Manager Lifecycle Commands:\n"
7152 " daemon-reload Reload systemd manager configuration\n"
7153 " daemon-reexec Reexecute systemd manager\n\n"
7154 "System Commands:\n"
7155 " is-system-running Check whether system is fully running\n"
7156 " default Enter system default mode\n"
7157 " rescue Enter system rescue mode\n"
7158 " emergency Enter system emergency mode\n"
7159 " halt Shut down and halt the system\n"
7160 " poweroff Shut down and power-off the system\n"
7161 " reboot [ARG] Shut down and reboot the system\n"
7162 " kexec Shut down and reboot the system with kexec\n"
7163 " exit [EXIT_CODE] Request user instance or container exit\n"
7164 " switch-root ROOT [INIT] Change to a different root file system\n"
7165 " suspend Suspend the system\n"
7166 " hibernate Hibernate the system\n"
7167 " hybrid-sleep Hibernate and suspend the system\n"
7168 " suspend-then-hibernate Suspend the system, wake after a period of\n"
7169 " time and put it into hibernate\n",
7170 program_invocation_short_name);
7171 }
7172
7173 static void halt_help(void) {
7174 printf("%s [OPTIONS...]%s\n\n"
7175 "%s the system.\n\n"
7176 " --help Show this help\n"
7177 " --halt Halt the machine\n"
7178 " -p --poweroff Switch off the machine\n"
7179 " --reboot Reboot the machine\n"
7180 " -f --force Force immediate halt/power-off/reboot\n"
7181 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
7182 " -d --no-wtmp Don't write wtmp record\n"
7183 " --no-wall Don't send wall message before halt/power-off/reboot\n",
7184 program_invocation_short_name,
7185 arg_action == ACTION_REBOOT ? " [ARG]" : "",
7186 arg_action == ACTION_REBOOT ? "Reboot" :
7187 arg_action == ACTION_POWEROFF ? "Power off" :
7188 "Halt");
7189 }
7190
7191 static void shutdown_help(void) {
7192 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
7193 "Shut down the system.\n\n"
7194 " --help Show this help\n"
7195 " -H --halt Halt the machine\n"
7196 " -P --poweroff Power-off the machine\n"
7197 " -r --reboot Reboot the machine\n"
7198 " -h Equivalent to --poweroff, overridden by --halt\n"
7199 " -k Don't halt/power-off/reboot, just send warnings\n"
7200 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7201 " -c Cancel a pending shutdown\n",
7202 program_invocation_short_name);
7203 }
7204
7205 static void telinit_help(void) {
7206 printf("%s [OPTIONS...] {COMMAND}\n\n"
7207 "Send control commands to the init daemon.\n\n"
7208 " --help Show this help\n"
7209 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
7210 "Commands:\n"
7211 " 0 Power-off the machine\n"
7212 " 6 Reboot the machine\n"
7213 " 2, 3, 4, 5 Start runlevelX.target unit\n"
7214 " 1, s, S Enter rescue mode\n"
7215 " q, Q Reload init daemon configuration\n"
7216 " u, U Reexecute init daemon\n",
7217 program_invocation_short_name);
7218 }
7219
7220 static void runlevel_help(void) {
7221 printf("%s [OPTIONS...]\n\n"
7222 "Prints the previous and current runlevel of the init system.\n\n"
7223 " --help Show this help\n",
7224 program_invocation_short_name);
7225 }
7226
7227 static void help_types(void) {
7228 int i;
7229
7230 if (!arg_no_legend)
7231 puts("Available unit types:");
7232 for (i = 0; i < _UNIT_TYPE_MAX; i++)
7233 puts(unit_type_to_string(i));
7234 }
7235
7236 static void help_states(void) {
7237 int i;
7238
7239 if (!arg_no_legend)
7240 puts("Available unit load states:");
7241 for (i = 0; i < _UNIT_LOAD_STATE_MAX; i++)
7242 puts(unit_load_state_to_string(i));
7243
7244 if (!arg_no_legend)
7245 puts("\nAvailable unit active states:");
7246 for (i = 0; i < _UNIT_ACTIVE_STATE_MAX; i++)
7247 puts(unit_active_state_to_string(i));
7248
7249 if (!arg_no_legend)
7250 puts("\nAvailable automount unit substates:");
7251 for (i = 0; i < _AUTOMOUNT_STATE_MAX; i++)
7252 puts(automount_state_to_string(i));
7253
7254 if (!arg_no_legend)
7255 puts("\nAvailable device unit substates:");
7256 for (i = 0; i < _DEVICE_STATE_MAX; i++)
7257 puts(device_state_to_string(i));
7258
7259 if (!arg_no_legend)
7260 puts("\nAvailable mount unit substates:");
7261 for (i = 0; i < _MOUNT_STATE_MAX; i++)
7262 puts(mount_state_to_string(i));
7263
7264 if (!arg_no_legend)
7265 puts("\nAvailable path unit substates:");
7266 for (i = 0; i < _PATH_STATE_MAX; i++)
7267 puts(path_state_to_string(i));
7268
7269 if (!arg_no_legend)
7270 puts("\nAvailable scope unit substates:");
7271 for (i = 0; i < _SCOPE_STATE_MAX; i++)
7272 puts(scope_state_to_string(i));
7273
7274 if (!arg_no_legend)
7275 puts("\nAvailable service unit substates:");
7276 for (i = 0; i < _SERVICE_STATE_MAX; i++)
7277 puts(service_state_to_string(i));
7278
7279 if (!arg_no_legend)
7280 puts("\nAvailable slice unit substates:");
7281 for (i = 0; i < _SLICE_STATE_MAX; i++)
7282 puts(slice_state_to_string(i));
7283
7284 if (!arg_no_legend)
7285 puts("\nAvailable socket unit substates:");
7286 for (i = 0; i < _SOCKET_STATE_MAX; i++)
7287 puts(socket_state_to_string(i));
7288
7289 if (!arg_no_legend)
7290 puts("\nAvailable swap unit substates:");
7291 for (i = 0; i < _SWAP_STATE_MAX; i++)
7292 puts(swap_state_to_string(i));
7293
7294 if (!arg_no_legend)
7295 puts("\nAvailable target unit substates:");
7296 for (i = 0; i < _TARGET_STATE_MAX; i++)
7297 puts(target_state_to_string(i));
7298
7299 if (!arg_no_legend)
7300 puts("\nAvailable timer unit substates:");
7301 for (i = 0; i < _TIMER_STATE_MAX; i++)
7302 puts(timer_state_to_string(i));
7303 }
7304
7305 static int systemctl_parse_argv(int argc, char *argv[]) {
7306
7307 enum {
7308 ARG_FAIL = 0x100,
7309 ARG_REVERSE,
7310 ARG_AFTER,
7311 ARG_BEFORE,
7312 ARG_DRY_RUN,
7313 ARG_SHOW_TYPES,
7314 ARG_IRREVERSIBLE,
7315 ARG_IGNORE_DEPENDENCIES,
7316 ARG_VALUE,
7317 ARG_VERSION,
7318 ARG_USER,
7319 ARG_SYSTEM,
7320 ARG_GLOBAL,
7321 ARG_NO_BLOCK,
7322 ARG_NO_LEGEND,
7323 ARG_NO_PAGER,
7324 ARG_NO_WALL,
7325 ARG_ROOT,
7326 ARG_NO_RELOAD,
7327 ARG_KILL_WHO,
7328 ARG_NO_ASK_PASSWORD,
7329 ARG_FAILED,
7330 ARG_RUNTIME,
7331 ARG_PLAIN,
7332 ARG_STATE,
7333 ARG_JOB_MODE,
7334 ARG_PRESET_MODE,
7335 ARG_FIRMWARE_SETUP,
7336 ARG_NOW,
7337 ARG_MESSAGE,
7338 ARG_WAIT,
7339 };
7340
7341 static const struct option options[] = {
7342 { "help", no_argument, NULL, 'h' },
7343 { "version", no_argument, NULL, ARG_VERSION },
7344 { "type", required_argument, NULL, 't' },
7345 { "property", required_argument, NULL, 'p' },
7346 { "all", no_argument, NULL, 'a' },
7347 { "reverse", no_argument, NULL, ARG_REVERSE },
7348 { "after", no_argument, NULL, ARG_AFTER },
7349 { "before", no_argument, NULL, ARG_BEFORE },
7350 { "show-types", no_argument, NULL, ARG_SHOW_TYPES },
7351 { "failed", no_argument, NULL, ARG_FAILED }, /* compatibility only */
7352 { "full", no_argument, NULL, 'l' },
7353 { "job-mode", required_argument, NULL, ARG_JOB_MODE },
7354 { "fail", no_argument, NULL, ARG_FAIL }, /* compatibility only */
7355 { "irreversible", no_argument, NULL, ARG_IRREVERSIBLE }, /* compatibility only */
7356 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES }, /* compatibility only */
7357 { "ignore-inhibitors", no_argument, NULL, 'i' },
7358 { "value", no_argument, NULL, ARG_VALUE },
7359 { "user", no_argument, NULL, ARG_USER },
7360 { "system", no_argument, NULL, ARG_SYSTEM },
7361 { "global", no_argument, NULL, ARG_GLOBAL },
7362 { "wait", no_argument, NULL, ARG_WAIT },
7363 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
7364 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
7365 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
7366 { "no-wall", no_argument, NULL, ARG_NO_WALL },
7367 { "dry-run", no_argument, NULL, ARG_DRY_RUN },
7368 { "quiet", no_argument, NULL, 'q' },
7369 { "root", required_argument, NULL, ARG_ROOT },
7370 { "force", no_argument, NULL, 'f' },
7371 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
7372 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
7373 { "signal", required_argument, NULL, 's' },
7374 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
7375 { "host", required_argument, NULL, 'H' },
7376 { "machine", required_argument, NULL, 'M' },
7377 { "runtime", no_argument, NULL, ARG_RUNTIME },
7378 { "lines", required_argument, NULL, 'n' },
7379 { "output", required_argument, NULL, 'o' },
7380 { "plain", no_argument, NULL, ARG_PLAIN },
7381 { "state", required_argument, NULL, ARG_STATE },
7382 { "recursive", no_argument, NULL, 'r' },
7383 { "preset-mode", required_argument, NULL, ARG_PRESET_MODE },
7384 { "firmware-setup", no_argument, NULL, ARG_FIRMWARE_SETUP },
7385 { "now", no_argument, NULL, ARG_NOW },
7386 { "message", required_argument, NULL, ARG_MESSAGE },
7387 {}
7388 };
7389
7390 const char *p;
7391 int c, r;
7392
7393 assert(argc >= 0);
7394 assert(argv);
7395
7396 /* we default to allowing interactive authorization only in systemctl (not in the legacy commands) */
7397 arg_ask_password = true;
7398
7399 while ((c = getopt_long(argc, argv, "ht:p:alqfs:H:M:n:o:ir", options, NULL)) >= 0)
7400
7401 switch (c) {
7402
7403 case 'h':
7404 systemctl_help();
7405 return 0;
7406
7407 case ARG_VERSION:
7408 return version();
7409
7410 case 't': {
7411 if (isempty(optarg)) {
7412 log_error("--type= requires arguments.");
7413 return -EINVAL;
7414 }
7415
7416 for (p = optarg;;) {
7417 _cleanup_free_ char *type = NULL;
7418
7419 r = extract_first_word(&p, &type, ",", 0);
7420 if (r < 0)
7421 return log_error_errno(r, "Failed to parse type: %s", optarg);
7422 if (r == 0)
7423 break;
7424
7425 if (streq(type, "help")) {
7426 help_types();
7427 return 0;
7428 }
7429
7430 if (unit_type_from_string(type) >= 0) {
7431 if (strv_push(&arg_types, type) < 0)
7432 return log_oom();
7433 type = NULL;
7434 continue;
7435 }
7436
7437 /* It's much nicer to use --state= for
7438 * load states, but let's support this
7439 * in --types= too for compatibility
7440 * with old versions */
7441 if (unit_load_state_from_string(type) >= 0) {
7442 if (strv_push(&arg_states, type) < 0)
7443 return log_oom();
7444 type = NULL;
7445 continue;
7446 }
7447
7448 log_error("Unknown unit type or load state '%s'.", type);
7449 log_info("Use -t help to see a list of allowed values.");
7450 return -EINVAL;
7451 }
7452
7453 break;
7454 }
7455
7456 case 'p': {
7457 /* Make sure that if the empty property list
7458 was specified, we won't show any properties. */
7459 if (isempty(optarg) && !arg_properties) {
7460 arg_properties = new0(char*, 1);
7461 if (!arg_properties)
7462 return log_oom();
7463 } else
7464 for (p = optarg;;) {
7465 _cleanup_free_ char *prop = NULL;
7466
7467 r = extract_first_word(&p, &prop, ",", 0);
7468 if (r < 0)
7469 return log_error_errno(r, "Failed to parse property: %s", optarg);
7470 if (r == 0)
7471 break;
7472
7473 if (strv_push(&arg_properties, prop) < 0)
7474 return log_oom();
7475
7476 prop = NULL;
7477 }
7478
7479 /* If the user asked for a particular
7480 * property, show it to him, even if it is
7481 * empty. */
7482 arg_all = true;
7483
7484 break;
7485 }
7486
7487 case 'a':
7488 arg_all = true;
7489 break;
7490
7491 case ARG_REVERSE:
7492 arg_dependency = DEPENDENCY_REVERSE;
7493 break;
7494
7495 case ARG_AFTER:
7496 arg_dependency = DEPENDENCY_AFTER;
7497 arg_jobs_after = true;
7498 break;
7499
7500 case ARG_BEFORE:
7501 arg_dependency = DEPENDENCY_BEFORE;
7502 arg_jobs_before = true;
7503 break;
7504
7505 case ARG_SHOW_TYPES:
7506 arg_show_types = true;
7507 break;
7508
7509 case ARG_VALUE:
7510 arg_value = true;
7511 break;
7512
7513 case ARG_JOB_MODE:
7514 arg_job_mode = optarg;
7515 break;
7516
7517 case ARG_FAIL:
7518 arg_job_mode = "fail";
7519 break;
7520
7521 case ARG_IRREVERSIBLE:
7522 arg_job_mode = "replace-irreversibly";
7523 break;
7524
7525 case ARG_IGNORE_DEPENDENCIES:
7526 arg_job_mode = "ignore-dependencies";
7527 break;
7528
7529 case ARG_USER:
7530 arg_scope = UNIT_FILE_USER;
7531 break;
7532
7533 case ARG_SYSTEM:
7534 arg_scope = UNIT_FILE_SYSTEM;
7535 break;
7536
7537 case ARG_GLOBAL:
7538 arg_scope = UNIT_FILE_GLOBAL;
7539 break;
7540
7541 case ARG_WAIT:
7542 arg_wait = true;
7543 break;
7544
7545 case ARG_NO_BLOCK:
7546 arg_no_block = true;
7547 break;
7548
7549 case ARG_NO_LEGEND:
7550 arg_no_legend = true;
7551 break;
7552
7553 case ARG_NO_PAGER:
7554 arg_no_pager = true;
7555 break;
7556
7557 case ARG_NO_WALL:
7558 arg_no_wall = true;
7559 break;
7560
7561 case ARG_ROOT:
7562 r = parse_path_argument_and_warn(optarg, false, &arg_root);
7563 if (r < 0)
7564 return r;
7565 break;
7566
7567 case 'l':
7568 arg_full = true;
7569 break;
7570
7571 case ARG_FAILED:
7572 if (strv_extend(&arg_states, "failed") < 0)
7573 return log_oom();
7574
7575 break;
7576
7577 case ARG_DRY_RUN:
7578 arg_dry_run = true;
7579 break;
7580
7581 case 'q':
7582 arg_quiet = true;
7583 break;
7584
7585 case 'f':
7586 arg_force++;
7587 break;
7588
7589 case ARG_NO_RELOAD:
7590 arg_no_reload = true;
7591 break;
7592
7593 case ARG_KILL_WHO:
7594 arg_kill_who = optarg;
7595 break;
7596
7597 case 's':
7598 arg_signal = signal_from_string(optarg);
7599 if (arg_signal < 0) {
7600 log_error("Failed to parse signal string %s.", optarg);
7601 return -EINVAL;
7602 }
7603 break;
7604
7605 case ARG_NO_ASK_PASSWORD:
7606 arg_ask_password = false;
7607 break;
7608
7609 case 'H':
7610 arg_transport = BUS_TRANSPORT_REMOTE;
7611 arg_host = optarg;
7612 break;
7613
7614 case 'M':
7615 arg_transport = BUS_TRANSPORT_MACHINE;
7616 arg_host = optarg;
7617 break;
7618
7619 case ARG_RUNTIME:
7620 arg_runtime = true;
7621 break;
7622
7623 case 'n':
7624 if (safe_atou(optarg, &arg_lines) < 0) {
7625 log_error("Failed to parse lines '%s'", optarg);
7626 return -EINVAL;
7627 }
7628 break;
7629
7630 case 'o':
7631 arg_output = output_mode_from_string(optarg);
7632 if (arg_output < 0) {
7633 log_error("Unknown output '%s'.", optarg);
7634 return -EINVAL;
7635 }
7636 break;
7637
7638 case 'i':
7639 arg_ignore_inhibitors = true;
7640 break;
7641
7642 case ARG_PLAIN:
7643 arg_plain = true;
7644 break;
7645
7646 case ARG_FIRMWARE_SETUP:
7647 arg_firmware_setup = true;
7648 break;
7649
7650 case ARG_STATE: {
7651 if (isempty(optarg)) {
7652 log_error("--state= requires arguments.");
7653 return -EINVAL;
7654 }
7655
7656 for (p = optarg;;) {
7657 _cleanup_free_ char *s = NULL;
7658
7659 r = extract_first_word(&p, &s, ",", 0);
7660 if (r < 0)
7661 return log_error_errno(r, "Failed to parse state: %s", optarg);
7662 if (r == 0)
7663 break;
7664
7665 if (streq(s, "help")) {
7666 help_states();
7667 return 0;
7668 }
7669
7670 if (strv_push(&arg_states, s) < 0)
7671 return log_oom();
7672
7673 s = NULL;
7674 }
7675 break;
7676 }
7677
7678 case 'r':
7679 if (geteuid() != 0) {
7680 log_error("--recursive requires root privileges.");
7681 return -EPERM;
7682 }
7683
7684 arg_recursive = true;
7685 break;
7686
7687 case ARG_PRESET_MODE:
7688
7689 arg_preset_mode = unit_file_preset_mode_from_string(optarg);
7690 if (arg_preset_mode < 0) {
7691 log_error("Failed to parse preset mode: %s.", optarg);
7692 return -EINVAL;
7693 }
7694
7695 break;
7696
7697 case ARG_NOW:
7698 arg_now = true;
7699 break;
7700
7701 case ARG_MESSAGE:
7702 if (strv_extend(&arg_wall, optarg) < 0)
7703 return log_oom();
7704 break;
7705
7706 case '?':
7707 return -EINVAL;
7708
7709 default:
7710 assert_not_reached("Unhandled option");
7711 }
7712
7713 if (arg_transport != BUS_TRANSPORT_LOCAL && arg_scope != UNIT_FILE_SYSTEM) {
7714 log_error("Cannot access user instance remotely.");
7715 return -EINVAL;
7716 }
7717
7718 if (arg_wait && arg_no_block) {
7719 log_error("--wait may not be combined with --no-block.");
7720 return -EINVAL;
7721 }
7722
7723 return 1;
7724 }
7725
7726 static int halt_parse_argv(int argc, char *argv[]) {
7727
7728 enum {
7729 ARG_HELP = 0x100,
7730 ARG_HALT,
7731 ARG_REBOOT,
7732 ARG_NO_WALL
7733 };
7734
7735 static const struct option options[] = {
7736 { "help", no_argument, NULL, ARG_HELP },
7737 { "halt", no_argument, NULL, ARG_HALT },
7738 { "poweroff", no_argument, NULL, 'p' },
7739 { "reboot", no_argument, NULL, ARG_REBOOT },
7740 { "force", no_argument, NULL, 'f' },
7741 { "wtmp-only", no_argument, NULL, 'w' },
7742 { "no-wtmp", no_argument, NULL, 'd' },
7743 { "no-sync", no_argument, NULL, 'n' },
7744 { "no-wall", no_argument, NULL, ARG_NO_WALL },
7745 {}
7746 };
7747
7748 int c, r, runlevel;
7749
7750 assert(argc >= 0);
7751 assert(argv);
7752
7753 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
7754 if (IN_SET(runlevel, '0', '6'))
7755 arg_force = 2;
7756
7757 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0)
7758 switch (c) {
7759
7760 case ARG_HELP:
7761 halt_help();
7762 return 0;
7763
7764 case ARG_HALT:
7765 arg_action = ACTION_HALT;
7766 break;
7767
7768 case 'p':
7769 if (arg_action != ACTION_REBOOT)
7770 arg_action = ACTION_POWEROFF;
7771 break;
7772
7773 case ARG_REBOOT:
7774 arg_action = ACTION_REBOOT;
7775 break;
7776
7777 case 'f':
7778 arg_force = 2;
7779 break;
7780
7781 case 'w':
7782 arg_dry_run = true;
7783 break;
7784
7785 case 'd':
7786 arg_no_wtmp = true;
7787 break;
7788
7789 case 'n':
7790 arg_no_sync = true;
7791 break;
7792
7793 case ARG_NO_WALL:
7794 arg_no_wall = true;
7795 break;
7796
7797 case 'i':
7798 case 'h':
7799 /* Compatibility nops */
7800 break;
7801
7802 case '?':
7803 return -EINVAL;
7804
7805 default:
7806 assert_not_reached("Unhandled option");
7807 }
7808
7809 if (arg_action == ACTION_REBOOT && (argc == optind || argc == optind + 1)) {
7810 r = update_reboot_parameter_and_warn(argc == optind + 1 ? argv[optind] : NULL);
7811 if (r < 0)
7812 return r;
7813 } else if (optind < argc) {
7814 log_error("Too many arguments.");
7815 return -EINVAL;
7816 }
7817
7818 return 1;
7819 }
7820
7821 static int parse_shutdown_time_spec(const char *t, usec_t *_u) {
7822 assert(t);
7823 assert(_u);
7824
7825 if (streq(t, "now"))
7826 *_u = 0;
7827 else if (!strchr(t, ':')) {
7828 uint64_t u;
7829
7830 if (safe_atou64(t, &u) < 0)
7831 return -EINVAL;
7832
7833 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
7834 } else {
7835 char *e = NULL;
7836 long hour, minute;
7837 struct tm tm = {};
7838 time_t s;
7839 usec_t n;
7840
7841 errno = 0;
7842 hour = strtol(t, &e, 10);
7843 if (errno > 0 || *e != ':' || hour < 0 || hour > 23)
7844 return -EINVAL;
7845
7846 minute = strtol(e+1, &e, 10);
7847 if (errno > 0 || *e != 0 || minute < 0 || minute > 59)
7848 return -EINVAL;
7849
7850 n = now(CLOCK_REALTIME);
7851 s = (time_t) (n / USEC_PER_SEC);
7852
7853 assert_se(localtime_r(&s, &tm));
7854
7855 tm.tm_hour = (int) hour;
7856 tm.tm_min = (int) minute;
7857 tm.tm_sec = 0;
7858
7859 assert_se(s = mktime(&tm));
7860
7861 *_u = (usec_t) s * USEC_PER_SEC;
7862
7863 while (*_u <= n)
7864 *_u += USEC_PER_DAY;
7865 }
7866
7867 return 0;
7868 }
7869
7870 static int shutdown_parse_argv(int argc, char *argv[]) {
7871
7872 enum {
7873 ARG_HELP = 0x100,
7874 ARG_NO_WALL
7875 };
7876
7877 static const struct option options[] = {
7878 { "help", no_argument, NULL, ARG_HELP },
7879 { "halt", no_argument, NULL, 'H' },
7880 { "poweroff", no_argument, NULL, 'P' },
7881 { "reboot", no_argument, NULL, 'r' },
7882 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
7883 { "no-wall", no_argument, NULL, ARG_NO_WALL },
7884 {}
7885 };
7886
7887 char **wall = NULL;
7888 int c, r;
7889
7890 assert(argc >= 0);
7891 assert(argv);
7892
7893 while ((c = getopt_long(argc, argv, "HPrhkKat:fFc", options, NULL)) >= 0)
7894 switch (c) {
7895
7896 case ARG_HELP:
7897 shutdown_help();
7898 return 0;
7899
7900 case 'H':
7901 arg_action = ACTION_HALT;
7902 break;
7903
7904 case 'P':
7905 arg_action = ACTION_POWEROFF;
7906 break;
7907
7908 case 'r':
7909 if (kexec_loaded())
7910 arg_action = ACTION_KEXEC;
7911 else
7912 arg_action = ACTION_REBOOT;
7913 break;
7914
7915 case 'K':
7916 arg_action = ACTION_KEXEC;
7917 break;
7918
7919 case 'h':
7920 if (arg_action != ACTION_HALT)
7921 arg_action = ACTION_POWEROFF;
7922 break;
7923
7924 case 'k':
7925 arg_dry_run = true;
7926 break;
7927
7928 case ARG_NO_WALL:
7929 arg_no_wall = true;
7930 break;
7931
7932 case 'a':
7933 case 't': /* Note that we also ignore any passed argument to -t, not just the -t itself */
7934 case 'f':
7935 case 'F':
7936 /* Compatibility nops */
7937 break;
7938
7939 case 'c':
7940 arg_action = ACTION_CANCEL_SHUTDOWN;
7941 break;
7942
7943 case '?':
7944 return -EINVAL;
7945
7946 default:
7947 assert_not_reached("Unhandled option");
7948 }
7949
7950 if (argc > optind && arg_action != ACTION_CANCEL_SHUTDOWN) {
7951 r = parse_shutdown_time_spec(argv[optind], &arg_when);
7952 if (r < 0) {
7953 log_error("Failed to parse time specification: %s", argv[optind]);
7954 return r;
7955 }
7956 } else
7957 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
7958
7959 if (argc > optind && arg_action == ACTION_CANCEL_SHUTDOWN)
7960 /* No time argument for shutdown cancel */
7961 wall = argv + optind;
7962 else if (argc > optind + 1)
7963 /* We skip the time argument */
7964 wall = argv + optind + 1;
7965
7966 if (wall) {
7967 arg_wall = strv_copy(wall);
7968 if (!arg_wall)
7969 return log_oom();
7970 }
7971
7972 optind = argc;
7973
7974 return 1;
7975 }
7976
7977 static int telinit_parse_argv(int argc, char *argv[]) {
7978
7979 enum {
7980 ARG_HELP = 0x100,
7981 ARG_NO_WALL
7982 };
7983
7984 static const struct option options[] = {
7985 { "help", no_argument, NULL, ARG_HELP },
7986 { "no-wall", no_argument, NULL, ARG_NO_WALL },
7987 {}
7988 };
7989
7990 static const struct {
7991 char from;
7992 enum action to;
7993 } table[] = {
7994 { '0', ACTION_POWEROFF },
7995 { '6', ACTION_REBOOT },
7996 { '1', ACTION_RESCUE },
7997 { '2', ACTION_RUNLEVEL2 },
7998 { '3', ACTION_RUNLEVEL3 },
7999 { '4', ACTION_RUNLEVEL4 },
8000 { '5', ACTION_RUNLEVEL5 },
8001 { 's', ACTION_RESCUE },
8002 { 'S', ACTION_RESCUE },
8003 { 'q', ACTION_RELOAD },
8004 { 'Q', ACTION_RELOAD },
8005 { 'u', ACTION_REEXEC },
8006 { 'U', ACTION_REEXEC }
8007 };
8008
8009 unsigned i;
8010 int c;
8011
8012 assert(argc >= 0);
8013 assert(argv);
8014
8015 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0)
8016 switch (c) {
8017
8018 case ARG_HELP:
8019 telinit_help();
8020 return 0;
8021
8022 case ARG_NO_WALL:
8023 arg_no_wall = true;
8024 break;
8025
8026 case '?':
8027 return -EINVAL;
8028
8029 default:
8030 assert_not_reached("Unhandled option");
8031 }
8032
8033 if (optind >= argc) {
8034 log_error("%s: required argument missing.", program_invocation_short_name);
8035 return -EINVAL;
8036 }
8037
8038 if (optind + 1 < argc) {
8039 log_error("Too many arguments.");
8040 return -EINVAL;
8041 }
8042
8043 if (strlen(argv[optind]) != 1) {
8044 log_error("Expected single character argument.");
8045 return -EINVAL;
8046 }
8047
8048 for (i = 0; i < ELEMENTSOF(table); i++)
8049 if (table[i].from == argv[optind][0])
8050 break;
8051
8052 if (i >= ELEMENTSOF(table)) {
8053 log_error("Unknown command '%s'.", argv[optind]);
8054 return -EINVAL;
8055 }
8056
8057 arg_action = table[i].to;
8058
8059 optind++;
8060
8061 return 1;
8062 }
8063
8064 static int runlevel_parse_argv(int argc, char *argv[]) {
8065
8066 enum {
8067 ARG_HELP = 0x100,
8068 };
8069
8070 static const struct option options[] = {
8071 { "help", no_argument, NULL, ARG_HELP },
8072 {}
8073 };
8074
8075 int c;
8076
8077 assert(argc >= 0);
8078 assert(argv);
8079
8080 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0)
8081 switch (c) {
8082
8083 case ARG_HELP:
8084 runlevel_help();
8085 return 0;
8086
8087 case '?':
8088 return -EINVAL;
8089
8090 default:
8091 assert_not_reached("Unhandled option");
8092 }
8093
8094 if (optind < argc) {
8095 log_error("Too many arguments.");
8096 return -EINVAL;
8097 }
8098
8099 return 1;
8100 }
8101
8102 static int parse_argv(int argc, char *argv[]) {
8103 assert(argc >= 0);
8104 assert(argv);
8105
8106 if (program_invocation_short_name) {
8107
8108 if (strstr(program_invocation_short_name, "halt")) {
8109 arg_action = ACTION_HALT;
8110 return halt_parse_argv(argc, argv);
8111
8112 } else if (strstr(program_invocation_short_name, "poweroff")) {
8113 arg_action = ACTION_POWEROFF;
8114 return halt_parse_argv(argc, argv);
8115
8116 } else if (strstr(program_invocation_short_name, "reboot")) {
8117 if (kexec_loaded())
8118 arg_action = ACTION_KEXEC;
8119 else
8120 arg_action = ACTION_REBOOT;
8121 return halt_parse_argv(argc, argv);
8122
8123 } else if (strstr(program_invocation_short_name, "shutdown")) {
8124 arg_action = ACTION_POWEROFF;
8125 return shutdown_parse_argv(argc, argv);
8126
8127 } else if (strstr(program_invocation_short_name, "init")) {
8128
8129 /* Matches invocations as "init" as well as "telinit", which are synonymous when run as PID !=
8130 * 1 on SysV.
8131 *
8132 * On SysV "telinit" was the official command to communicate with PID 1, but "init" would
8133 * redirect itself to "telinit" if called with PID != 1. We follow the same logic here still,
8134 * though we add one level of indirection, as we implement "telinit" in "systemctl". Hence, for
8135 * us if you invoke "init" you get "systemd", but it will execve() "systemctl" immediately with
8136 * argv[] unmodified if PID is != 1. If you invoke "telinit" you directly get "systemctl". In
8137 * both cases we shall do the same thing, which is why we do strstr(p_i_s_n, "init") here, as a
8138 * quick way to match both.
8139 *
8140 * Also see redirect_telinit() in src/core/main.c. */
8141
8142 if (sd_booted() > 0) {
8143 arg_action = _ACTION_INVALID;
8144 return telinit_parse_argv(argc, argv);
8145 } else {
8146 /* Hmm, so some other init system is running, we need to forward this request to
8147 * it. For now we simply guess that it is Upstart. */
8148
8149 execv(TELINIT, argv);
8150
8151 log_error("Couldn't find an alternative telinit implementation to spawn.");
8152 return -EIO;
8153 }
8154
8155 } else if (strstr(program_invocation_short_name, "runlevel")) {
8156 arg_action = ACTION_RUNLEVEL;
8157 return runlevel_parse_argv(argc, argv);
8158 }
8159 }
8160
8161 arg_action = ACTION_SYSTEMCTL;
8162 return systemctl_parse_argv(argc, argv);
8163 }
8164
8165 #if HAVE_SYSV_COMPAT
8166 _pure_ static int action_to_runlevel(void) {
8167
8168 static const char table[_ACTION_MAX] = {
8169 [ACTION_HALT] = '0',
8170 [ACTION_POWEROFF] = '0',
8171 [ACTION_REBOOT] = '6',
8172 [ACTION_RUNLEVEL2] = '2',
8173 [ACTION_RUNLEVEL3] = '3',
8174 [ACTION_RUNLEVEL4] = '4',
8175 [ACTION_RUNLEVEL5] = '5',
8176 [ACTION_RESCUE] = '1'
8177 };
8178
8179 assert(arg_action >= 0 && arg_action < _ACTION_MAX);
8180
8181 return table[arg_action];
8182 }
8183 #endif
8184
8185 static int talk_initctl(void) {
8186 #if HAVE_SYSV_COMPAT
8187 struct init_request request = {
8188 .magic = INIT_MAGIC,
8189 .sleeptime = 0,
8190 .cmd = INIT_CMD_RUNLVL
8191 };
8192
8193 _cleanup_close_ int fd = -1;
8194 char rl;
8195 int r;
8196 const char *p;
8197
8198 rl = action_to_runlevel();
8199 if (!rl)
8200 return 0;
8201
8202 request.runlevel = rl;
8203
8204 FOREACH_STRING(p, "/run/initctl", "/dev/initctl") {
8205 fd = open(p, O_WRONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
8206 if (fd >= 0 || errno != ENOENT)
8207 break;
8208 }
8209 if (fd < 0) {
8210 if (errno == ENOENT)
8211 return 0;
8212
8213 return log_error_errno(errno, "Failed to open initctl fifo: %m");
8214 }
8215
8216 r = loop_write(fd, &request, sizeof(request), false);
8217 if (r < 0)
8218 return log_error_errno(r, "Failed to write to %s: %m", p);
8219
8220 return 1;
8221 #else
8222 return 0;
8223 #endif
8224 }
8225
8226 static int systemctl_main(int argc, char *argv[]) {
8227
8228 static const Verb verbs[] = {
8229 { "list-units", VERB_ANY, VERB_ANY, VERB_DEFAULT|VERB_ONLINE_ONLY, list_units },
8230 { "list-unit-files", VERB_ANY, VERB_ANY, 0, list_unit_files },
8231 { "list-sockets", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, list_sockets },
8232 { "list-timers", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, list_timers },
8233 { "list-jobs", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, list_jobs },
8234 { "list-machines", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY|VERB_MUST_BE_ROOT, list_machines },
8235 { "clear-jobs", VERB_ANY, 1, VERB_ONLINE_ONLY, trivial_method },
8236 { "cancel", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, cancel_job },
8237 { "start", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8238 { "stop", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8239 { "condstop", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with ALTLinux */
8240 { "reload", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8241 { "restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8242 { "try-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8243 { "reload-or-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8244 { "reload-or-try-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatbility with old systemctl <= 228 */
8245 { "try-reload-or-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8246 { "force-reload", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with SysV */
8247 { "condreload", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with ALTLinux */
8248 { "condrestart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with RH */
8249 { "isolate", 2, 2, VERB_ONLINE_ONLY, start_unit },
8250 { "kill", 2, VERB_ANY, VERB_ONLINE_ONLY, kill_unit },
8251 { "is-active", 2, VERB_ANY, VERB_ONLINE_ONLY, check_unit_active },
8252 { "check", 2, VERB_ANY, VERB_ONLINE_ONLY, check_unit_active }, /* deprecated alias of is-active */
8253 { "is-failed", 2, VERB_ANY, VERB_ONLINE_ONLY, check_unit_failed },
8254 { "show", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, show },
8255 { "cat", 2, VERB_ANY, VERB_ONLINE_ONLY, cat },
8256 { "status", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, show },
8257 { "help", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, show },
8258 { "daemon-reload", VERB_ANY, 1, VERB_ONLINE_ONLY, daemon_reload },
8259 { "daemon-reexec", VERB_ANY, 1, VERB_ONLINE_ONLY, daemon_reload },
8260 { "show-environment", VERB_ANY, 1, VERB_ONLINE_ONLY, show_environment },
8261 { "set-environment", 2, VERB_ANY, VERB_ONLINE_ONLY, set_environment },
8262 { "unset-environment", 2, VERB_ANY, VERB_ONLINE_ONLY, set_environment },
8263 { "import-environment", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, import_environment },
8264 { "halt", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8265 { "poweroff", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8266 { "reboot", VERB_ANY, 2, VERB_ONLINE_ONLY, start_system_special },
8267 { "kexec", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8268 { "suspend", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8269 { "hibernate", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8270 { "hybrid-sleep", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8271 { "suspend-then-hibernate",VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8272 { "default", VERB_ANY, 1, VERB_ONLINE_ONLY, start_special },
8273 { "rescue", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8274 { "emergency", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8275 { "exit", VERB_ANY, 2, VERB_ONLINE_ONLY, start_special },
8276 { "reset-failed", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, reset_failed },
8277 { "enable", 2, VERB_ANY, 0, enable_unit },
8278 { "disable", 2, VERB_ANY, 0, enable_unit },
8279 { "is-enabled", 2, VERB_ANY, 0, unit_is_enabled },
8280 { "reenable", 2, VERB_ANY, 0, enable_unit },
8281 { "preset", 2, VERB_ANY, 0, enable_unit },
8282 { "preset-all", VERB_ANY, 1, 0, preset_all },
8283 { "mask", 2, VERB_ANY, 0, enable_unit },
8284 { "unmask", 2, VERB_ANY, 0, enable_unit },
8285 { "link", 2, VERB_ANY, 0, enable_unit },
8286 { "revert", 2, VERB_ANY, 0, enable_unit },
8287 { "switch-root", 2, VERB_ANY, VERB_ONLINE_ONLY, switch_root },
8288 { "list-dependencies", VERB_ANY, 2, VERB_ONLINE_ONLY, list_dependencies },
8289 { "set-default", 2, 2, 0, set_default },
8290 { "get-default", VERB_ANY, 1, 0, get_default },
8291 { "set-property", 3, VERB_ANY, VERB_ONLINE_ONLY, set_property },
8292 { "is-system-running", VERB_ANY, 1, 0, is_system_running },
8293 { "add-wants", 3, VERB_ANY, 0, add_dependency },
8294 { "add-requires", 3, VERB_ANY, 0, add_dependency },
8295 { "edit", 2, VERB_ANY, VERB_ONLINE_ONLY, edit },
8296 {}
8297 };
8298
8299 return dispatch_verb(argc, argv, verbs, NULL);
8300 }
8301
8302 static int reload_with_fallback(void) {
8303
8304 /* First, try systemd via D-Bus. */
8305 if (daemon_reload(0, NULL, NULL) >= 0)
8306 return 0;
8307
8308 /* Nothing else worked, so let's try signals */
8309 assert(IN_SET(arg_action, ACTION_RELOAD, ACTION_REEXEC));
8310
8311 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0)
8312 return log_error_errno(errno, "kill() failed: %m");
8313
8314 return 0;
8315 }
8316
8317 static int start_with_fallback(void) {
8318
8319 /* First, try systemd via D-Bus. */
8320 if (start_unit(0, NULL, NULL) >= 0)
8321 return 0;
8322
8323 /* Nothing else worked, so let's try /dev/initctl */
8324 if (talk_initctl() > 0)
8325 return 0;
8326
8327 log_error("Failed to talk to init daemon.");
8328 return -EIO;
8329 }
8330
8331 static int halt_now(enum action a) {
8332
8333 /* The kernel will automatically flush ATA disks and suchlike on reboot(), but the file systems need to be
8334 * synce'd explicitly in advance. */
8335 if (!arg_no_sync && !arg_dry_run)
8336 (void) sync();
8337
8338 /* Make sure C-A-D is handled by the kernel from this point on... */
8339 if (!arg_dry_run)
8340 (void) reboot(RB_ENABLE_CAD);
8341
8342 switch (a) {
8343
8344 case ACTION_HALT:
8345 if (!arg_quiet)
8346 log_info("Halting.");
8347 if (arg_dry_run)
8348 return 0;
8349 (void) reboot(RB_HALT_SYSTEM);
8350 return -errno;
8351
8352 case ACTION_POWEROFF:
8353 if (!arg_quiet)
8354 log_info("Powering off.");
8355 if (arg_dry_run)
8356 return 0;
8357 (void) reboot(RB_POWER_OFF);
8358 return -errno;
8359
8360 case ACTION_KEXEC:
8361 case ACTION_REBOOT:
8362 return reboot_with_parameter(REBOOT_FALLBACK |
8363 (arg_quiet ? 0 : REBOOT_LOG) |
8364 (arg_dry_run ? REBOOT_DRY_RUN : 0));
8365
8366 default:
8367 assert_not_reached("Unknown action.");
8368 }
8369 }
8370
8371 static int logind_schedule_shutdown(void) {
8372
8373 #if ENABLE_LOGIND
8374 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
8375 char date[FORMAT_TIMESTAMP_MAX];
8376 const char *action;
8377 sd_bus *bus;
8378 int r;
8379
8380 r = acquire_bus(BUS_FULL, &bus);
8381 if (r < 0)
8382 return r;
8383
8384 switch (arg_action) {
8385 case ACTION_HALT:
8386 action = "halt";
8387 break;
8388 case ACTION_POWEROFF:
8389 action = "poweroff";
8390 break;
8391 case ACTION_KEXEC:
8392 action = "kexec";
8393 break;
8394 case ACTION_EXIT:
8395 action = "exit";
8396 break;
8397 case ACTION_REBOOT:
8398 default:
8399 action = "reboot";
8400 break;
8401 }
8402
8403 if (arg_dry_run)
8404 action = strjoina("dry-", action);
8405
8406 (void) logind_set_wall_message();
8407
8408 r = sd_bus_call_method(
8409 bus,
8410 "org.freedesktop.login1",
8411 "/org/freedesktop/login1",
8412 "org.freedesktop.login1.Manager",
8413 "ScheduleShutdown",
8414 &error,
8415 NULL,
8416 "st",
8417 action,
8418 arg_when);
8419 if (r < 0)
8420 return log_warning_errno(r, "Failed to call ScheduleShutdown in logind, proceeding with immediate shutdown: %s", bus_error_message(&error, r));
8421
8422 if (!arg_quiet)
8423 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.", format_timestamp(date, sizeof(date), arg_when));
8424 return 0;
8425 #else
8426 log_error("Cannot schedule shutdown without logind support, proceeding with immediate shutdown.");
8427 return -ENOSYS;
8428 #endif
8429 }
8430
8431 static int halt_main(void) {
8432 int r;
8433
8434 r = logind_check_inhibitors(arg_action);
8435 if (r < 0)
8436 return r;
8437
8438 if (arg_when > 0)
8439 return logind_schedule_shutdown();
8440
8441 if (geteuid() != 0) {
8442 if (arg_dry_run || arg_force > 0) {
8443 (void) must_be_root();
8444 return -EPERM;
8445 }
8446
8447 /* Try logind if we are a normal user and no special
8448 * mode applies. Maybe PolicyKit allows us to shutdown
8449 * the machine. */
8450 if (IN_SET(arg_action, ACTION_POWEROFF, ACTION_REBOOT, ACTION_HALT)) {
8451 r = logind_reboot(arg_action);
8452 if (r >= 0)
8453 return r;
8454 if (IN_SET(r, -EOPNOTSUPP, -EINPROGRESS))
8455 /* requested operation is not
8456 * supported on the local system or
8457 * already in progress */
8458 return r;
8459 /* on all other errors, try low-level operation */
8460 }
8461 }
8462
8463 /* In order to minimize the difference between operation with and
8464 * without logind, we explicitly enable non-blocking mode for this,
8465 * as logind's shutdown operations are always non-blocking. */
8466 arg_no_block = true;
8467
8468 if (!arg_dry_run && !arg_force)
8469 return start_with_fallback();
8470
8471 assert(geteuid() == 0);
8472
8473 if (!arg_no_wtmp) {
8474 if (sd_booted() > 0)
8475 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
8476 else {
8477 r = utmp_put_shutdown();
8478 if (r < 0)
8479 log_warning_errno(r, "Failed to write utmp record: %m");
8480 }
8481 }
8482
8483 if (arg_dry_run)
8484 return 0;
8485
8486 r = halt_now(arg_action);
8487 return log_error_errno(r, "Failed to reboot: %m");
8488 }
8489
8490 static int runlevel_main(void) {
8491 int r, runlevel, previous;
8492
8493 r = utmp_get_runlevel(&runlevel, &previous);
8494 if (r < 0) {
8495 puts("unknown");
8496 return r;
8497 }
8498
8499 printf("%c %c\n",
8500 previous <= 0 ? 'N' : previous,
8501 runlevel <= 0 ? 'N' : runlevel);
8502
8503 return 0;
8504 }
8505
8506 static int logind_cancel_shutdown(void) {
8507 #if ENABLE_LOGIND
8508 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
8509 sd_bus *bus;
8510 int r;
8511
8512 r = acquire_bus(BUS_FULL, &bus);
8513 if (r < 0)
8514 return r;
8515
8516 (void) logind_set_wall_message();
8517
8518 r = sd_bus_call_method(
8519 bus,
8520 "org.freedesktop.login1",
8521 "/org/freedesktop/login1",
8522 "org.freedesktop.login1.Manager",
8523 "CancelScheduledShutdown",
8524 &error,
8525 NULL, NULL);
8526 if (r < 0)
8527 return log_warning_errno(r, "Failed to talk to logind, shutdown hasn't been cancelled: %s", bus_error_message(&error, r));
8528
8529 return 0;
8530 #else
8531 log_error("Not compiled with logind support, cannot cancel scheduled shutdowns.");
8532 return -ENOSYS;
8533 #endif
8534 }
8535
8536 int main(int argc, char*argv[]) {
8537 int r;
8538
8539 argv_cmdline = argv[0];
8540
8541 setlocale(LC_ALL, "");
8542 log_parse_environment();
8543 log_open();
8544 sigbus_install();
8545
8546 /* Explicitly not on_tty() to avoid setting cached value.
8547 * This becomes relevant for piping output which might be
8548 * ellipsized. */
8549 original_stdout_is_tty = isatty(STDOUT_FILENO);
8550
8551 r = parse_argv(argc, argv);
8552 if (r <= 0)
8553 goto finish;
8554
8555 if (arg_action != ACTION_SYSTEMCTL && running_in_chroot() > 0) {
8556
8557 if (!arg_quiet)
8558 log_info("Running in chroot, ignoring request.");
8559 r = 0;
8560 goto finish;
8561 }
8562
8563 /* systemctl_main() will print an error message for the bus
8564 * connection, but only if it needs to */
8565
8566 switch (arg_action) {
8567
8568 case ACTION_SYSTEMCTL:
8569 r = systemctl_main(argc, argv);
8570 break;
8571
8572 /* Legacy command aliases set arg_action. They provide some fallbacks,
8573 * e.g. to tell sysvinit to reboot after you have installed systemd
8574 * binaries. */
8575
8576 case ACTION_HALT:
8577 case ACTION_POWEROFF:
8578 case ACTION_REBOOT:
8579 case ACTION_KEXEC:
8580 r = halt_main();
8581 break;
8582
8583 case ACTION_RUNLEVEL2:
8584 case ACTION_RUNLEVEL3:
8585 case ACTION_RUNLEVEL4:
8586 case ACTION_RUNLEVEL5:
8587 case ACTION_RESCUE:
8588 r = start_with_fallback();
8589 break;
8590
8591 case ACTION_RELOAD:
8592 case ACTION_REEXEC:
8593 r = reload_with_fallback();
8594 break;
8595
8596 case ACTION_CANCEL_SHUTDOWN:
8597 r = logind_cancel_shutdown();
8598 break;
8599
8600 case ACTION_RUNLEVEL:
8601 r = runlevel_main();
8602 break;
8603
8604 case ACTION_EXIT:
8605 case ACTION_SUSPEND:
8606 case ACTION_HIBERNATE:
8607 case ACTION_HYBRID_SLEEP:
8608 case ACTION_SUSPEND_THEN_HIBERNATE:
8609 case ACTION_EMERGENCY:
8610 case ACTION_DEFAULT:
8611 /* systemctl verbs with no equivalent in the legacy commands.
8612 * These cannot appear in arg_action. Fall through. */
8613
8614 case _ACTION_INVALID:
8615 default:
8616 assert_not_reached("Unknown action");
8617 }
8618
8619 finish:
8620 release_busses();
8621
8622 pager_close();
8623 ask_password_agent_close();
8624 polkit_agent_close();
8625
8626 strv_free(arg_types);
8627 strv_free(arg_states);
8628 strv_free(arg_properties);
8629
8630 strv_free(arg_wall);
8631 free(arg_root);
8632 free(arg_esp_path);
8633
8634 /* Note that we return r here, not EXIT_SUCCESS, so that we can implement the LSB-like return codes */
8635 return r < 0 ? EXIT_FAILURE : r;
8636 }