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