chiark / gitweb /
20bc3bdf1c93eaf4cdebf34c6d0e941c42e05c76
[elogind.git] / src / systemctl / systemctl.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7   Copyright 2013 Marc-Antoine Perennou
8
9   systemd is free software; you can redistribute it and/or modify it
10   under the terms of the GNU Lesser General Public License as published by
11   the Free Software Foundation; either version 2.1 of the License, or
12   (at your option) any later version.
13
14   systemd is distributed in the hope that it will be useful, but
15   WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17   Lesser General Public License for more details.
18
19   You should have received a copy of the GNU Lesser General Public License
20   along with systemd; If not, see <http://www.gnu.org/licenses/>.
21 ***/
22
23 #include <sys/reboot.h>
24 #include <linux/reboot.h>
25 #include <sys/syscall.h>
26 #include <stdio.h>
27 #include <getopt.h>
28 #include <locale.h>
29 #include <stdbool.h>
30 #include <string.h>
31 #include <errno.h>
32 #include <sys/ioctl.h>
33 #include <termios.h>
34 #include <unistd.h>
35 #include <fcntl.h>
36 #include <sys/socket.h>
37 #include <sys/stat.h>
38 #include <stddef.h>
39 #include <sys/prctl.h>
40 #include <fnmatch.h>
41
42 #include "sd-daemon.h"
43 #include "sd-shutdown.h"
44 #include "sd-login.h"
45 #include "sd-bus.h"
46 #include "log.h"
47 #include "util.h"
48 #include "macro.h"
49 #include "set.h"
50 #include "utmp-wtmp.h"
51 #include "special.h"
52 #include "initreq.h"
53 #include "path-util.h"
54 #include "strv.h"
55 #include "cgroup-show.h"
56 #include "cgroup-util.h"
57 #include "list.h"
58 #include "path-lookup.h"
59 #include "conf-parser.h"
60 #include "exit-status.h"
61 #include "build.h"
62 #include "unit-name.h"
63 #include "pager.h"
64 #include "spawn-ask-password-agent.h"
65 #include "spawn-polkit-agent.h"
66 #include "install.h"
67 #include "logs-show.h"
68 #include "socket-util.h"
69 #include "fileio.h"
70 #include "copy.h"
71 #include "env-util.h"
72 #include "bus-util.h"
73 #include "bus-message.h"
74 #include "bus-error.h"
75 #include "bus-common-errors.h"
76 #include "mkdir.h"
77
78 static char **arg_types = NULL;
79 static char **arg_states = NULL;
80 static char **arg_properties = NULL;
81 static bool arg_all = false;
82 static enum dependency {
83         DEPENDENCY_FORWARD,
84         DEPENDENCY_REVERSE,
85         DEPENDENCY_AFTER,
86         DEPENDENCY_BEFORE,
87         _DEPENDENCY_MAX
88 } arg_dependency = DEPENDENCY_FORWARD;
89 static const char *arg_job_mode = "replace";
90 static UnitFileScope arg_scope = UNIT_FILE_SYSTEM;
91 static bool arg_no_block = false;
92 static bool arg_no_legend = false;
93 static bool arg_no_pager = false;
94 static bool arg_no_wtmp = false;
95 static bool arg_no_wall = false;
96 static bool arg_no_reload = false;
97 static bool arg_show_types = false;
98 static bool arg_ignore_inhibitors = false;
99 static bool arg_dry = false;
100 static bool arg_quiet = false;
101 static bool arg_full = false;
102 static bool arg_recursive = false;
103 static int arg_force = 0;
104 static bool arg_ask_password = true;
105 static bool arg_runtime = false;
106 static UnitFilePresetMode arg_preset_mode = UNIT_FILE_PRESET_FULL;
107 static char **arg_wall = NULL;
108 static const char *arg_kill_who = NULL;
109 static int arg_signal = SIGTERM;
110 static const char *arg_root = NULL;
111 static usec_t arg_when = 0;
112 static enum action {
113         _ACTION_INVALID,
114         ACTION_SYSTEMCTL,
115         ACTION_HALT,
116         ACTION_POWEROFF,
117         ACTION_REBOOT,
118         ACTION_KEXEC,
119         ACTION_EXIT,
120         ACTION_SUSPEND,
121         ACTION_HIBERNATE,
122         ACTION_HYBRID_SLEEP,
123         ACTION_RUNLEVEL2,
124         ACTION_RUNLEVEL3,
125         ACTION_RUNLEVEL4,
126         ACTION_RUNLEVEL5,
127         ACTION_RESCUE,
128         ACTION_EMERGENCY,
129         ACTION_DEFAULT,
130         ACTION_RELOAD,
131         ACTION_REEXEC,
132         ACTION_RUNLEVEL,
133         ACTION_CANCEL_SHUTDOWN,
134         _ACTION_MAX
135 } arg_action = ACTION_SYSTEMCTL;
136 static BusTransport arg_transport = BUS_TRANSPORT_LOCAL;
137 static char *arg_host = NULL;
138 static unsigned arg_lines = 10;
139 static OutputMode arg_output = OUTPUT_SHORT;
140 static bool arg_plain = false;
141
142 static bool original_stdout_is_tty;
143
144 static int daemon_reload(sd_bus *bus, char **args);
145 static int halt_now(enum action a);
146 static int check_one_unit(sd_bus *bus, const char *name, const char *good_states, bool quiet);
147
148 static char** strv_skip_first(char **strv) {
149         if (strv_length(strv) > 0)
150                 return strv + 1;
151         return NULL;
152 }
153
154 static void pager_open_if_enabled(void) {
155
156         if (arg_no_pager)
157                 return;
158
159         pager_open(false);
160 }
161
162 static void ask_password_agent_open_if_enabled(void) {
163
164         /* Open the password agent as a child process if necessary */
165
166         if (!arg_ask_password)
167                 return;
168
169         if (arg_scope != UNIT_FILE_SYSTEM)
170                 return;
171
172         if (arg_transport != BUS_TRANSPORT_LOCAL)
173                 return;
174
175         ask_password_agent_open();
176 }
177
178 #ifdef HAVE_LOGIND
179 static void polkit_agent_open_if_enabled(void) {
180
181         /* Open the polkit agent as a child process if necessary */
182
183         if (!arg_ask_password)
184                 return;
185
186         if (arg_scope != UNIT_FILE_SYSTEM)
187                 return;
188
189         if (arg_transport != BUS_TRANSPORT_LOCAL)
190                 return;
191
192         polkit_agent_open();
193 }
194 #endif
195
196 static int translate_bus_error_to_exit_status(int r, const sd_bus_error *error) {
197         assert(error);
198
199         if (!sd_bus_error_is_set(error))
200                 return r;
201
202         if (sd_bus_error_has_name(error, SD_BUS_ERROR_ACCESS_DENIED) ||
203             sd_bus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
204             sd_bus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
205             sd_bus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
206                 return EXIT_NOPERMISSION;
207
208         if (sd_bus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
209                 return EXIT_NOTINSTALLED;
210
211         if (sd_bus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
212             sd_bus_error_has_name(error, SD_BUS_ERROR_NOT_SUPPORTED))
213                 return EXIT_NOTIMPLEMENTED;
214
215         if (sd_bus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
216                 return EXIT_NOTCONFIGURED;
217
218         if (r != 0)
219                 return r;
220
221         return EXIT_FAILURE;
222 }
223
224 static void warn_wall(enum action a) {
225         static const char *table[_ACTION_MAX] = {
226                 [ACTION_HALT]            = "The system is going down for system halt NOW!",
227                 [ACTION_REBOOT]          = "The system is going down for reboot NOW!",
228                 [ACTION_POWEROFF]        = "The system is going down for power-off NOW!",
229                 [ACTION_KEXEC]           = "The system is going down for kexec reboot NOW!",
230                 [ACTION_RESCUE]          = "The system is going down to rescue mode NOW!",
231                 [ACTION_EMERGENCY]       = "The system is going down to emergency mode NOW!",
232                 [ACTION_CANCEL_SHUTDOWN] = "The system shutdown has been cancelled NOW!"
233         };
234
235         if (arg_no_wall)
236                 return;
237
238         if (arg_wall) {
239                 _cleanup_free_ char *p;
240
241                 p = strv_join(arg_wall, " ");
242                 if (!p) {
243                         log_oom();
244                         return;
245                 }
246
247                 if (*p) {
248                         utmp_wall(p, NULL, NULL);
249                         return;
250                 }
251         }
252
253         if (!table[a])
254                 return;
255
256         utmp_wall(table[a], NULL, NULL);
257 }
258
259 static bool avoid_bus(void) {
260
261         if (running_in_chroot() > 0)
262                 return true;
263
264         if (sd_booted() <= 0)
265                 return true;
266
267         if (!isempty(arg_root))
268                 return true;
269
270         if (arg_scope == UNIT_FILE_GLOBAL)
271                 return true;
272
273         return false;
274 }
275
276 static int compare_unit_info(const void *a, const void *b) {
277         const UnitInfo *u = a, *v = b;
278         const char *d1, *d2;
279         int r;
280
281         /* First, order by machine */
282         if (!u->machine && v->machine)
283                 return -1;
284         if (u->machine && !v->machine)
285                 return 1;
286         if (u->machine && v->machine) {
287                 r = strcasecmp(u->machine, v->machine);
288                 if (r != 0)
289                         return r;
290         }
291
292         /* Second, order by unit type */
293         d1 = strrchr(u->id, '.');
294         d2 = strrchr(v->id, '.');
295         if (d1 && d2) {
296                 r = strcasecmp(d1, d2);
297                 if (r != 0)
298                         return r;
299         }
300
301         /* Third, order by name */
302         return strcasecmp(u->id, v->id);
303 }
304
305 static bool output_show_unit(const UnitInfo *u, char **patterns) {
306         if (!strv_isempty(patterns)) {
307                 char **pattern;
308
309                 STRV_FOREACH(pattern, patterns)
310                         if (fnmatch(*pattern, u->id, FNM_NOESCAPE) == 0)
311                                 goto next;
312                 return false;
313         }
314
315 next:
316         if (arg_types) {
317                 const char *dot;
318
319                 dot = strrchr(u->id, '.');
320                 if (!dot)
321                         return false;
322
323                 if (!strv_find(arg_types, dot+1))
324                         return false;
325         }
326
327         if (arg_all)
328                 return true;
329
330         if (u->job_id > 0)
331                 return true;
332
333         if (streq(u->active_state, "inactive") || u->following[0])
334                 return false;
335
336         return true;
337 }
338
339 static int output_units_list(const UnitInfo *unit_infos, unsigned c) {
340         unsigned circle_len = 0, id_len, max_id_len, load_len, active_len, sub_len, job_len, desc_len;
341         const UnitInfo *u;
342         unsigned n_shown = 0;
343         int job_count = 0;
344
345         max_id_len = strlen("UNIT");
346         load_len = strlen("LOAD");
347         active_len = strlen("ACTIVE");
348         sub_len = strlen("SUB");
349         job_len = strlen("JOB");
350         desc_len = 0;
351
352         for (u = unit_infos; u < unit_infos + c; u++) {
353                 max_id_len = MAX(max_id_len, strlen(u->id) + (u->machine ? strlen(u->machine)+1 : 0));
354                 load_len = MAX(load_len, strlen(u->load_state));
355                 active_len = MAX(active_len, strlen(u->active_state));
356                 sub_len = MAX(sub_len, strlen(u->sub_state));
357
358                 if (u->job_id != 0) {
359                         job_len = MAX(job_len, strlen(u->job_type));
360                         job_count++;
361                 }
362
363                 if (!arg_no_legend &&
364                     (streq(u->active_state, "failed") ||
365                      STR_IN_SET(u->load_state, "error", "not-found", "masked")))
366                         circle_len = 2;
367         }
368
369         if (!arg_full && original_stdout_is_tty) {
370                 unsigned basic_len;
371
372                 id_len = MIN(max_id_len, 25u);
373                 basic_len = circle_len + 5 + id_len + 5 + active_len + sub_len;
374
375                 if (job_count)
376                         basic_len += job_len + 1;
377
378                 if (basic_len < (unsigned) columns()) {
379                         unsigned extra_len, incr;
380                         extra_len = columns() - basic_len;
381
382                         /* Either UNIT already got 25, or is fully satisfied.
383                          * Grant up to 25 to DESC now. */
384                         incr = MIN(extra_len, 25u);
385                         desc_len += incr;
386                         extra_len -= incr;
387
388                         /* split the remaining space between UNIT and DESC,
389                          * but do not give UNIT more than it needs. */
390                         if (extra_len > 0) {
391                                 incr = MIN(extra_len / 2, max_id_len - id_len);
392                                 id_len += incr;
393                                 desc_len += extra_len - incr;
394                         }
395                 }
396         } else
397                 id_len = max_id_len;
398
399         for (u = unit_infos; u < unit_infos + c; u++) {
400                 _cleanup_free_ char *e = NULL, *j = NULL;
401                 const char *on_loaded = "", *off_loaded = "";
402                 const char *on_active = "", *off_active = "";
403                 const char *on_circle = "", *off_circle = "";
404                 const char *id;
405                 bool circle = false;
406
407                 if (!n_shown && !arg_no_legend) {
408
409                         if (circle_len > 0)
410                                 fputs("  ", stdout);
411
412                         printf("%-*s %-*s %-*s %-*s ",
413                                id_len, "UNIT",
414                                load_len, "LOAD",
415                                active_len, "ACTIVE",
416                                sub_len, "SUB");
417
418                         if (job_count)
419                                 printf("%-*s ", job_len, "JOB");
420
421                         if (!arg_full && arg_no_pager)
422                                 printf("%.*s\n", desc_len, "DESCRIPTION");
423                         else
424                                 printf("%s\n", "DESCRIPTION");
425                 }
426
427                 n_shown++;
428
429                 if (STR_IN_SET(u->load_state, "error", "not-found", "masked")) {
430                         on_loaded = ansi_highlight_red();
431                         on_circle = ansi_highlight_yellow();
432                         off_loaded = off_circle = ansi_highlight_off();
433                         circle = true;
434                 }
435
436                 if (streq(u->active_state, "failed")) {
437                         on_circle = on_active = ansi_highlight_red();
438                         off_circle = off_active = ansi_highlight_off();
439                         circle = true;
440                 }
441
442                 if (u->machine) {
443                         j = strjoin(u->machine, ":", u->id, NULL);
444                         if (!j)
445                                 return log_oom();
446
447                         id = j;
448                 } else
449                         id = u->id;
450
451                 if (arg_full) {
452                         e = ellipsize(id, id_len, 33);
453                         if (!e)
454                                 return log_oom();
455
456                         id = e;
457                 }
458
459                 if (circle_len > 0)
460                         printf("%s%s%s ", on_circle, circle ? draw_special_char(DRAW_BLACK_CIRCLE) : " ", off_circle);
461
462                 printf("%s%-*s%s %s%-*s%s %s%-*s %-*s%s %-*s",
463                        on_active, id_len, id, off_active,
464                        on_loaded, load_len, u->load_state, off_loaded,
465                        on_active, active_len, u->active_state,
466                        sub_len, u->sub_state, off_active,
467                        job_count ? job_len + 1 : 0, u->job_id ? u->job_type : "");
468
469                 if (desc_len > 0)
470                         printf("%.*s\n", desc_len, u->description);
471                 else
472                         printf("%s\n", u->description);
473         }
474
475         if (!arg_no_legend) {
476                 const char *on, *off;
477
478                 if (n_shown) {
479                         puts("\n"
480                              "LOAD   = Reflects whether the unit definition was properly loaded.\n"
481                              "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
482                              "SUB    = The low-level unit activation state, values depend on unit type.");
483                         puts(job_count ? "JOB    = Pending job for the unit.\n" : "");
484                         on = ansi_highlight();
485                         off = ansi_highlight_off();
486                 } else {
487                         on = ansi_highlight_red();
488                         off = ansi_highlight_off();
489                 }
490
491                 if (arg_all)
492                         printf("%s%u loaded units listed.%s\n"
493                                "To show all installed unit files use 'systemctl list-unit-files'.\n",
494                                on, n_shown, off);
495                 else
496                         printf("%s%u loaded units listed.%s Pass --all to see loaded but inactive units, too.\n"
497                                "To show all installed unit files use 'systemctl list-unit-files'.\n",
498                                on, n_shown, off);
499         }
500
501         return 0;
502 }
503
504 static int get_unit_list(
505                 sd_bus *bus,
506                 const char *machine,
507                 char **patterns,
508                 UnitInfo **unit_infos,
509                 int c,
510                 sd_bus_message **_reply) {
511
512         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
513         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
514         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
515         size_t size = c;
516         int r;
517         UnitInfo u;
518
519         assert(bus);
520         assert(unit_infos);
521         assert(_reply);
522
523         r = sd_bus_message_new_method_call(
524                         bus,
525                         &m,
526                         "org.freedesktop.systemd1",
527                         "/org/freedesktop/systemd1",
528                         "org.freedesktop.systemd1.Manager",
529                         "ListUnitsFiltered");
530
531         if (r < 0)
532                 return bus_log_create_error(r);
533
534         r = sd_bus_message_append_strv(m, arg_states);
535         if (r < 0)
536                 return bus_log_create_error(r);
537
538         r = sd_bus_call(bus, m, 0, &error, &reply);
539         if (r < 0) {
540                 log_error("Failed to list units: %s", bus_error_message(&error, r));
541                 return r;
542         }
543
544         r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssssouso)");
545         if (r < 0)
546                 return bus_log_parse_error(r);
547
548         while ((r = bus_parse_unit_info(reply, &u)) > 0) {
549                 u.machine = machine;
550
551                 if (!output_show_unit(&u, patterns))
552                         continue;
553
554                 if (!GREEDY_REALLOC(*unit_infos, size, c+1))
555                         return log_oom();
556
557                 (*unit_infos)[c++] = u;
558         }
559         if (r < 0)
560                 return bus_log_parse_error(r);
561
562         r = sd_bus_message_exit_container(reply);
563         if (r < 0)
564                 return bus_log_parse_error(r);
565
566         *_reply = reply;
567         reply = NULL;
568
569         return c;
570 }
571
572 static void message_set_freep(Set **set) {
573         sd_bus_message *m;
574
575         while ((m = set_steal_first(*set)))
576                 sd_bus_message_unref(m);
577
578         set_free(*set);
579 }
580
581 static int get_unit_list_recursive(
582                 sd_bus *bus,
583                 char **patterns,
584                 UnitInfo **_unit_infos,
585                 Set **_replies,
586                 char ***_machines) {
587
588         _cleanup_free_ UnitInfo *unit_infos = NULL;
589         _cleanup_(message_set_freep) Set *replies;
590         sd_bus_message *reply;
591         int c, r;
592
593         assert(bus);
594         assert(_replies);
595         assert(_unit_infos);
596         assert(_machines);
597
598         replies = set_new(NULL);
599         if (!replies)
600                 return log_oom();
601
602         c = get_unit_list(bus, NULL, patterns, &unit_infos, 0, &reply);
603         if (c < 0)
604                 return c;
605
606         r = set_put(replies, reply);
607         if (r < 0) {
608                 sd_bus_message_unref(reply);
609                 return r;
610         }
611
612         if (arg_recursive) {
613                 _cleanup_strv_free_ char **machines = NULL;
614                 char **i;
615
616                 r = sd_get_machine_names(&machines);
617                 if (r < 0)
618                         return r;
619
620                 STRV_FOREACH(i, machines) {
621                         _cleanup_bus_close_unref_ sd_bus *container = NULL;
622                         int k;
623
624                         r = sd_bus_open_system_container(&container, *i);
625                         if (r < 0) {
626                                 log_error_errno(r, "Failed to connect to container %s: %m", *i);
627                                 continue;
628                         }
629
630                         k = get_unit_list(container, *i, patterns, &unit_infos, c, &reply);
631                         if (k < 0)
632                                 return k;
633
634                         c = k;
635
636                         r = set_put(replies, reply);
637                         if (r < 0) {
638                                 sd_bus_message_unref(reply);
639                                 return r;
640                         }
641                 }
642
643                 *_machines = machines;
644                 machines = NULL;
645         } else
646                 *_machines = NULL;
647
648         *_unit_infos = unit_infos;
649         unit_infos = NULL;
650
651         *_replies = replies;
652         replies = NULL;
653
654         return c;
655 }
656
657 static int list_units(sd_bus *bus, char **args) {
658         _cleanup_free_ UnitInfo *unit_infos = NULL;
659         _cleanup_(message_set_freep) Set *replies = NULL;
660         _cleanup_strv_free_ char **machines = NULL;
661         int r;
662
663         pager_open_if_enabled();
664
665         r = get_unit_list_recursive(bus, strv_skip_first(args), &unit_infos, &replies, &machines);
666         if (r < 0)
667                 return r;
668
669         qsort_safe(unit_infos, r, sizeof(UnitInfo), compare_unit_info);
670         return output_units_list(unit_infos, r);
671 }
672
673 static int get_triggered_units(
674                 sd_bus *bus,
675                 const char* path,
676                 char*** ret) {
677
678         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
679         int r;
680
681         r = sd_bus_get_property_strv(
682                         bus,
683                         "org.freedesktop.systemd1",
684                         path,
685                         "org.freedesktop.systemd1.Unit",
686                         "Triggers",
687                         &error,
688                         ret);
689
690         if (r < 0)
691                 log_error("Failed to determine triggers: %s", bus_error_message(&error, r));
692
693         return 0;
694 }
695
696 static int get_listening(
697                 sd_bus *bus,
698                 const char* unit_path,
699                 char*** listening) {
700
701         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
702         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
703         const char *type, *path;
704         int r, n = 0;
705
706         r = sd_bus_get_property(
707                         bus,
708                         "org.freedesktop.systemd1",
709                         unit_path,
710                         "org.freedesktop.systemd1.Socket",
711                         "Listen",
712                         &error,
713                         &reply,
714                         "a(ss)");
715         if (r < 0) {
716                 log_error("Failed to get list of listening sockets: %s", bus_error_message(&error, r));
717                 return r;
718         }
719
720         r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ss)");
721         if (r < 0)
722                 return bus_log_parse_error(r);
723
724         while ((r = sd_bus_message_read(reply, "(ss)", &type, &path)) > 0) {
725
726                 r = strv_extend(listening, type);
727                 if (r < 0)
728                         return log_oom();
729
730                 r = strv_extend(listening, path);
731                 if (r < 0)
732                         return log_oom();
733
734                 n++;
735         }
736         if (r < 0)
737                 return bus_log_parse_error(r);
738
739         r = sd_bus_message_exit_container(reply);
740         if (r < 0)
741                 return bus_log_parse_error(r);
742
743         return n;
744 }
745
746 struct socket_info {
747         const char *machine;
748         const char* id;
749
750         char* type;
751         char* path;
752
753         /* Note: triggered is a list here, although it almost certainly
754          * will always be one unit. Nevertheless, dbus API allows for multiple
755          * values, so let's follow that. */
756         char** triggered;
757
758         /* The strv above is shared. free is set only in the first one. */
759         bool own_triggered;
760 };
761
762 static int socket_info_compare(const struct socket_info *a, const struct socket_info *b) {
763         int o;
764
765         assert(a);
766         assert(b);
767
768         if (!a->machine && b->machine)
769                 return -1;
770         if (a->machine && !b->machine)
771                 return 1;
772         if (a->machine && b->machine) {
773                 o = strcasecmp(a->machine, b->machine);
774                 if (o != 0)
775                         return o;
776         }
777
778         o = strcmp(a->path, b->path);
779         if (o == 0)
780                 o = strcmp(a->type, b->type);
781
782         return o;
783 }
784
785 static int output_sockets_list(struct socket_info *socket_infos, unsigned cs) {
786         struct socket_info *s;
787         unsigned pathlen = strlen("LISTEN"),
788                 typelen = strlen("TYPE") * arg_show_types,
789                 socklen = strlen("UNIT"),
790                 servlen = strlen("ACTIVATES");
791         const char *on, *off;
792
793         for (s = socket_infos; s < socket_infos + cs; s++) {
794                 unsigned tmp = 0;
795                 char **a;
796
797                 socklen = MAX(socklen, strlen(s->id));
798                 if (arg_show_types)
799                         typelen = MAX(typelen, strlen(s->type));
800                 pathlen = MAX(pathlen, strlen(s->path) + (s->machine ? strlen(s->machine)+1 : 0));
801
802                 STRV_FOREACH(a, s->triggered)
803                         tmp += strlen(*a) + 2*(a != s->triggered);
804                 servlen = MAX(servlen, tmp);
805         }
806
807         if (cs) {
808                 if (!arg_no_legend)
809                         printf("%-*s %-*.*s%-*s %s\n",
810                                pathlen, "LISTEN",
811                                typelen + arg_show_types, typelen + arg_show_types, "TYPE ",
812                                socklen, "UNIT",
813                                "ACTIVATES");
814
815                 for (s = socket_infos; s < socket_infos + cs; s++) {
816                         _cleanup_free_ char *j = NULL;
817                         const char *path;
818                         char **a;
819
820                         if (s->machine) {
821                                 j = strjoin(s->machine, ":", s->path, NULL);
822                                 if (!j)
823                                         return log_oom();
824                                 path = j;
825                         } else
826                                 path = s->path;
827
828                         if (arg_show_types)
829                                 printf("%-*s %-*s %-*s",
830                                        pathlen, path, typelen, s->type, socklen, s->id);
831                         else
832                                 printf("%-*s %-*s",
833                                        pathlen, path, socklen, s->id);
834                         STRV_FOREACH(a, s->triggered)
835                                 printf("%s %s",
836                                        a == s->triggered ? "" : ",", *a);
837                         printf("\n");
838                 }
839
840                 on = ansi_highlight();
841                 off = ansi_highlight_off();
842                 if (!arg_no_legend)
843                         printf("\n");
844         } else {
845                 on = ansi_highlight_red();
846                 off = ansi_highlight_off();
847         }
848
849         if (!arg_no_legend) {
850                 printf("%s%u sockets listed.%s\n", on, cs, off);
851                 if (!arg_all)
852                         printf("Pass --all to see loaded but inactive sockets, too.\n");
853         }
854
855         return 0;
856 }
857
858 static int list_sockets(sd_bus *bus, char **args) {
859         _cleanup_(message_set_freep) Set *replies = NULL;
860         _cleanup_strv_free_ char **machines = NULL;
861         _cleanup_free_ UnitInfo *unit_infos = NULL;
862         _cleanup_free_ struct socket_info *socket_infos = NULL;
863         const UnitInfo *u;
864         struct socket_info *s;
865         unsigned cs = 0;
866         size_t size = 0;
867         int r = 0, n;
868
869         pager_open_if_enabled();
870
871         n = get_unit_list_recursive(bus, strv_skip_first(args), &unit_infos, &replies, &machines);
872         if (n < 0)
873                 return n;
874
875         for (u = unit_infos; u < unit_infos + n; u++) {
876                 _cleanup_strv_free_ char **listening = NULL, **triggered = NULL;
877                 int i, c;
878
879                 if (!endswith(u->id, ".socket"))
880                         continue;
881
882                 r = get_triggered_units(bus, u->unit_path, &triggered);
883                 if (r < 0)
884                         goto cleanup;
885
886                 c = get_listening(bus, u->unit_path, &listening);
887                 if (c < 0) {
888                         r = c;
889                         goto cleanup;
890                 }
891
892                 if (!GREEDY_REALLOC(socket_infos, size, cs + c)) {
893                         r = log_oom();
894                         goto cleanup;
895                 }
896
897                 for (i = 0; i < c; i++)
898                         socket_infos[cs + i] = (struct socket_info) {
899                                 .machine = u->machine,
900                                 .id = u->id,
901                                 .type = listening[i*2],
902                                 .path = listening[i*2 + 1],
903                                 .triggered = triggered,
904                                 .own_triggered = i==0,
905                         };
906
907                 /* from this point on we will cleanup those socket_infos */
908                 cs += c;
909                 free(listening);
910                 listening = triggered = NULL; /* avoid cleanup */
911         }
912
913         qsort_safe(socket_infos, cs, sizeof(struct socket_info),
914                    (__compar_fn_t) socket_info_compare);
915
916         output_sockets_list(socket_infos, cs);
917
918  cleanup:
919         assert(cs == 0 || socket_infos);
920         for (s = socket_infos; s < socket_infos + cs; s++) {
921                 free(s->type);
922                 free(s->path);
923                 if (s->own_triggered)
924                         strv_free(s->triggered);
925         }
926
927         return r;
928 }
929
930 static int get_next_elapse(
931                 sd_bus *bus,
932                 const char *path,
933                 dual_timestamp *next) {
934
935         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
936         dual_timestamp t;
937         int r;
938
939         assert(bus);
940         assert(path);
941         assert(next);
942
943         r = sd_bus_get_property_trivial(
944                         bus,
945                         "org.freedesktop.systemd1",
946                         path,
947                         "org.freedesktop.systemd1.Timer",
948                         "NextElapseUSecMonotonic",
949                         &error,
950                         't',
951                         &t.monotonic);
952         if (r < 0) {
953                 log_error("Failed to get next elapsation time: %s", bus_error_message(&error, r));
954                 return r;
955         }
956
957         r = sd_bus_get_property_trivial(
958                         bus,
959                         "org.freedesktop.systemd1",
960                         path,
961                         "org.freedesktop.systemd1.Timer",
962                         "NextElapseUSecRealtime",
963                         &error,
964                         't',
965                         &t.realtime);
966         if (r < 0) {
967                 log_error("Failed to get next elapsation time: %s", bus_error_message(&error, r));
968                 return r;
969         }
970
971         *next = t;
972         return 0;
973 }
974
975 static int get_last_trigger(
976                 sd_bus *bus,
977                 const char *path,
978                 usec_t *last) {
979
980         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
981         int r;
982
983         assert(bus);
984         assert(path);
985         assert(last);
986
987         r = sd_bus_get_property_trivial(
988                         bus,
989                         "org.freedesktop.systemd1",
990                         path,
991                         "org.freedesktop.systemd1.Timer",
992                         "LastTriggerUSec",
993                         &error,
994                         't',
995                         last);
996         if (r < 0) {
997                 log_error("Failed to get last trigger time: %s", bus_error_message(&error, r));
998                 return r;
999         }
1000
1001         return 0;
1002 }
1003
1004 struct timer_info {
1005         const char* machine;
1006         const char* id;
1007         usec_t next_elapse;
1008         usec_t last_trigger;
1009         char** triggered;
1010 };
1011
1012 static int timer_info_compare(const struct timer_info *a, const struct timer_info *b) {
1013         int o;
1014
1015         assert(a);
1016         assert(b);
1017
1018         if (!a->machine && b->machine)
1019                 return -1;
1020         if (a->machine && !b->machine)
1021                 return 1;
1022         if (a->machine && b->machine) {
1023                 o = strcasecmp(a->machine, b->machine);
1024                 if (o != 0)
1025                         return o;
1026         }
1027
1028         if (a->next_elapse < b->next_elapse)
1029                 return -1;
1030         if (a->next_elapse > b->next_elapse)
1031                 return 1;
1032
1033         return strcmp(a->id, b->id);
1034 }
1035
1036 static int output_timers_list(struct timer_info *timer_infos, unsigned n) {
1037         struct timer_info *t;
1038         unsigned
1039                 nextlen = strlen("NEXT"),
1040                 leftlen = strlen("LEFT"),
1041                 lastlen = strlen("LAST"),
1042                 passedlen = strlen("PASSED"),
1043                 unitlen = strlen("UNIT"),
1044                 activatelen = strlen("ACTIVATES");
1045
1046         const char *on, *off;
1047
1048         assert(timer_infos || n == 0);
1049
1050         for (t = timer_infos; t < timer_infos + n; t++) {
1051                 unsigned ul = 0;
1052                 char **a;
1053
1054                 if (t->next_elapse > 0) {
1055                         char tstamp[FORMAT_TIMESTAMP_MAX] = "", trel[FORMAT_TIMESTAMP_RELATIVE_MAX] = "";
1056
1057                         format_timestamp(tstamp, sizeof(tstamp), t->next_elapse);
1058                         nextlen = MAX(nextlen, strlen(tstamp) + 1);
1059
1060                         format_timestamp_relative(trel, sizeof(trel), t->next_elapse);
1061                         leftlen = MAX(leftlen, strlen(trel));
1062                 }
1063
1064                 if (t->last_trigger > 0) {
1065                         char tstamp[FORMAT_TIMESTAMP_MAX] = "", trel[FORMAT_TIMESTAMP_RELATIVE_MAX] = "";
1066
1067                         format_timestamp(tstamp, sizeof(tstamp), t->last_trigger);
1068                         lastlen = MAX(lastlen, strlen(tstamp) + 1);
1069
1070                         format_timestamp_relative(trel, sizeof(trel), t->last_trigger);
1071                         passedlen = MAX(passedlen, strlen(trel));
1072                 }
1073
1074                 unitlen = MAX(unitlen, strlen(t->id) + (t->machine ? strlen(t->machine)+1 : 0));
1075
1076                 STRV_FOREACH(a, t->triggered)
1077                         ul += strlen(*a) + 2*(a != t->triggered);
1078
1079                 activatelen = MAX(activatelen, ul);
1080         }
1081
1082         if (n > 0) {
1083                 if (!arg_no_legend)
1084                         printf("%-*s %-*s %-*s %-*s %-*s %s\n",
1085                                nextlen,   "NEXT",
1086                                leftlen,   "LEFT",
1087                                lastlen,   "LAST",
1088                                passedlen, "PASSED",
1089                                unitlen,   "UNIT",
1090                                           "ACTIVATES");
1091
1092                 for (t = timer_infos; t < timer_infos + n; t++) {
1093                         _cleanup_free_ char *j = NULL;
1094                         const char *unit;
1095                         char tstamp1[FORMAT_TIMESTAMP_MAX] = "n/a", trel1[FORMAT_TIMESTAMP_RELATIVE_MAX] = "n/a";
1096                         char tstamp2[FORMAT_TIMESTAMP_MAX] = "n/a", trel2[FORMAT_TIMESTAMP_RELATIVE_MAX] = "n/a";
1097                         char **a;
1098
1099                         format_timestamp(tstamp1, sizeof(tstamp1), t->next_elapse);
1100                         format_timestamp_relative(trel1, sizeof(trel1), t->next_elapse);
1101
1102                         format_timestamp(tstamp2, sizeof(tstamp2), t->last_trigger);
1103                         format_timestamp_relative(trel2, sizeof(trel2), t->last_trigger);
1104
1105                         if (t->machine) {
1106                                 j = strjoin(t->machine, ":", t->id, NULL);
1107                                 if (!j)
1108                                         return log_oom();
1109                                 unit = j;
1110                         } else
1111                                 unit = t->id;
1112
1113                         printf("%-*s %-*s %-*s %-*s %-*s",
1114                                nextlen, tstamp1, leftlen, trel1, lastlen, tstamp2, passedlen, trel2, unitlen, unit);
1115
1116                         STRV_FOREACH(a, t->triggered)
1117                                 printf("%s %s",
1118                                        a == t->triggered ? "" : ",", *a);
1119                         printf("\n");
1120                 }
1121
1122                 on = ansi_highlight();
1123                 off = ansi_highlight_off();
1124                 if (!arg_no_legend)
1125                         printf("\n");
1126         } else {
1127                 on = ansi_highlight_red();
1128                 off = ansi_highlight_off();
1129         }
1130
1131         if (!arg_no_legend) {
1132                 printf("%s%u timers listed.%s\n", on, n, off);
1133                 if (!arg_all)
1134                         printf("Pass --all to see loaded but inactive timers, too.\n");
1135         }
1136
1137         return 0;
1138 }
1139
1140 static usec_t calc_next_elapse(dual_timestamp *nw, dual_timestamp *next) {
1141         usec_t next_elapse;
1142
1143         assert(nw);
1144         assert(next);
1145
1146         if (next->monotonic != USEC_INFINITY && next->monotonic > 0) {
1147                 usec_t converted;
1148
1149                 if (next->monotonic > nw->monotonic)
1150                         converted = nw->realtime + (next->monotonic - nw->monotonic);
1151                 else
1152                         converted = nw->realtime - (nw->monotonic - next->monotonic);
1153
1154                 if (next->realtime != USEC_INFINITY && next->realtime > 0)
1155                         next_elapse = MIN(converted, next->realtime);
1156                 else
1157                         next_elapse = converted;
1158
1159         } else
1160                 next_elapse = next->realtime;
1161
1162         return next_elapse;
1163 }
1164
1165 static int list_timers(sd_bus *bus, char **args) {
1166         _cleanup_(message_set_freep) Set *replies = NULL;
1167         _cleanup_strv_free_ char **machines = NULL;
1168         _cleanup_free_ struct timer_info *timer_infos = NULL;
1169         _cleanup_free_ UnitInfo *unit_infos = NULL;
1170         struct timer_info *t;
1171         const UnitInfo *u;
1172         size_t size = 0;
1173         int n, c = 0;
1174         dual_timestamp nw;
1175         int r = 0;
1176
1177         pager_open_if_enabled();
1178
1179         n = get_unit_list_recursive(bus, strv_skip_first(args), &unit_infos, &replies, &machines);
1180         if (n < 0)
1181                 return n;
1182
1183         dual_timestamp_get(&nw);
1184
1185         for (u = unit_infos; u < unit_infos + n; u++) {
1186                 _cleanup_strv_free_ char **triggered = NULL;
1187                 dual_timestamp next = {};
1188                 usec_t m, last = 0;
1189
1190                 if (!endswith(u->id, ".timer"))
1191                         continue;
1192
1193                 r = get_triggered_units(bus, u->unit_path, &triggered);
1194                 if (r < 0)
1195                         goto cleanup;
1196
1197                 r = get_next_elapse(bus, u->unit_path, &next);
1198                 if (r < 0)
1199                         goto cleanup;
1200
1201                 get_last_trigger(bus, u->unit_path, &last);
1202
1203                 if (!GREEDY_REALLOC(timer_infos, size, c+1)) {
1204                         r = log_oom();
1205                         goto cleanup;
1206                 }
1207
1208                 m = calc_next_elapse(&nw, &next);
1209
1210                 timer_infos[c++] = (struct timer_info) {
1211                         .machine = u->machine,
1212                         .id = u->id,
1213                         .next_elapse = m,
1214                         .last_trigger = last,
1215                         .triggered = triggered,
1216                 };
1217
1218                 triggered = NULL; /* avoid cleanup */
1219         }
1220
1221         qsort_safe(timer_infos, c, sizeof(struct timer_info),
1222                    (__compar_fn_t) timer_info_compare);
1223
1224         output_timers_list(timer_infos, c);
1225
1226  cleanup:
1227         for (t = timer_infos; t < timer_infos + c; t++)
1228                 strv_free(t->triggered);
1229
1230         return r;
1231 }
1232
1233 static int compare_unit_file_list(const void *a, const void *b) {
1234         const char *d1, *d2;
1235         const UnitFileList *u = a, *v = b;
1236
1237         d1 = strrchr(u->path, '.');
1238         d2 = strrchr(v->path, '.');
1239
1240         if (d1 && d2) {
1241                 int r;
1242
1243                 r = strcasecmp(d1, d2);
1244                 if (r != 0)
1245                         return r;
1246         }
1247
1248         return strcasecmp(basename(u->path), basename(v->path));
1249 }
1250
1251 static bool output_show_unit_file(const UnitFileList *u, char **patterns) {
1252         if (!strv_isempty(patterns)) {
1253                 char **pattern;
1254
1255                 STRV_FOREACH(pattern, patterns)
1256                         if (fnmatch(*pattern, basename(u->path), FNM_NOESCAPE) == 0)
1257                                 goto next;
1258                 return false;
1259         }
1260
1261 next:
1262         if (!strv_isempty(arg_types)) {
1263                 const char *dot;
1264
1265                 dot = strrchr(u->path, '.');
1266                 if (!dot)
1267                         return false;
1268
1269                 if (!strv_find(arg_types, dot+1))
1270                         return false;
1271         }
1272
1273         if (!strv_isempty(arg_states)) {
1274                 if (!strv_find(arg_states, unit_file_state_to_string(u->state)))
1275                         return false;
1276         }
1277
1278         return true;
1279 }
1280
1281 static void output_unit_file_list(const UnitFileList *units, unsigned c) {
1282         unsigned max_id_len, id_cols, state_cols;
1283         const UnitFileList *u;
1284
1285         max_id_len = strlen("UNIT FILE");
1286         state_cols = strlen("STATE");
1287
1288         for (u = units; u < units + c; u++) {
1289                 max_id_len = MAX(max_id_len, strlen(basename(u->path)));
1290                 state_cols = MAX(state_cols, strlen(unit_file_state_to_string(u->state)));
1291         }
1292
1293         if (!arg_full) {
1294                 unsigned basic_cols;
1295
1296                 id_cols = MIN(max_id_len, 25u);
1297                 basic_cols = 1 + id_cols + state_cols;
1298                 if (basic_cols < (unsigned) columns())
1299                         id_cols += MIN(columns() - basic_cols, max_id_len - id_cols);
1300         } else
1301                 id_cols = max_id_len;
1302
1303         if (!arg_no_legend)
1304                 printf("%-*s %-*s\n",
1305                        id_cols, "UNIT FILE",
1306                        state_cols, "STATE");
1307
1308         for (u = units; u < units + c; u++) {
1309                 _cleanup_free_ char *e = NULL;
1310                 const char *on, *off;
1311                 const char *id;
1312
1313                 if (u->state == UNIT_FILE_MASKED ||
1314                     u->state == UNIT_FILE_MASKED_RUNTIME ||
1315                     u->state == UNIT_FILE_DISABLED ||
1316                     u->state == UNIT_FILE_INVALID) {
1317                         on  = ansi_highlight_red();
1318                         off = ansi_highlight_off();
1319                 } else if (u->state == UNIT_FILE_ENABLED) {
1320                         on  = ansi_highlight_green();
1321                         off = ansi_highlight_off();
1322                 } else
1323                         on = off = "";
1324
1325                 id = basename(u->path);
1326
1327                 e = arg_full ? NULL : ellipsize(id, id_cols, 33);
1328
1329                 printf("%-*s %s%-*s%s\n",
1330                        id_cols, e ? e : id,
1331                        on, state_cols, unit_file_state_to_string(u->state), off);
1332         }
1333
1334         if (!arg_no_legend)
1335                 printf("\n%u unit files listed.\n", c);
1336 }
1337
1338 static int list_unit_files(sd_bus *bus, char **args) {
1339         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
1340         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1341         _cleanup_free_ UnitFileList *units = NULL;
1342         UnitFileList *unit;
1343         size_t size = 0;
1344         unsigned c = 0;
1345         const char *state;
1346         char *path;
1347         int r;
1348
1349         pager_open_if_enabled();
1350
1351         if (avoid_bus()) {
1352                 Hashmap *h;
1353                 UnitFileList *u;
1354                 Iterator i;
1355                 unsigned n_units;
1356
1357                 h = hashmap_new(&string_hash_ops);
1358                 if (!h)
1359                         return log_oom();
1360
1361                 r = unit_file_get_list(arg_scope, arg_root, h);
1362                 if (r < 0) {
1363                         unit_file_list_free(h);
1364                         log_error_errno(r, "Failed to get unit file list: %m");
1365                         return r;
1366                 }
1367
1368                 n_units = hashmap_size(h);
1369
1370                 units = new(UnitFileList, n_units);
1371                 if (!units && n_units > 0) {
1372                         unit_file_list_free(h);
1373                         return log_oom();
1374                 }
1375
1376                 HASHMAP_FOREACH(u, h, i) {
1377                         if (!output_show_unit_file(u, strv_skip_first(args)))
1378                                 continue;
1379
1380                         units[c++] = *u;
1381                         free(u);
1382                 }
1383
1384                 assert(c <= n_units);
1385                 hashmap_free(h);
1386         } else {
1387                 r = sd_bus_call_method(
1388                                 bus,
1389                                 "org.freedesktop.systemd1",
1390                                 "/org/freedesktop/systemd1",
1391                                 "org.freedesktop.systemd1.Manager",
1392                                 "ListUnitFiles",
1393                                 &error,
1394                                 &reply,
1395                                 NULL);
1396                 if (r < 0) {
1397                         log_error("Failed to list unit files: %s", bus_error_message(&error, r));
1398                         return r;
1399                 }
1400
1401                 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ss)");
1402                 if (r < 0)
1403                         return bus_log_parse_error(r);
1404
1405                 while ((r = sd_bus_message_read(reply, "(ss)", &path, &state)) > 0) {
1406
1407                         if (!GREEDY_REALLOC(units, size, c + 1))
1408                                 return log_oom();
1409
1410                         units[c] = (struct UnitFileList) {
1411                                 path,
1412                                 unit_file_state_from_string(state)
1413                         };
1414
1415                         if (output_show_unit_file(&units[c], strv_skip_first(args)))
1416                                 c ++;
1417
1418                 }
1419                 if (r < 0)
1420                         return bus_log_parse_error(r);
1421
1422                 r = sd_bus_message_exit_container(reply);
1423                 if (r < 0)
1424                         return bus_log_parse_error(r);
1425         }
1426
1427         qsort_safe(units, c, sizeof(UnitFileList), compare_unit_file_list);
1428         output_unit_file_list(units, c);
1429
1430         if (avoid_bus()) {
1431                 for (unit = units; unit < units + c; unit++)
1432                         free(unit->path);
1433         }
1434
1435         return 0;
1436 }
1437
1438 static int list_dependencies_print(const char *name, int level, unsigned int branches, bool last) {
1439         _cleanup_free_ char *n = NULL;
1440         size_t max_len = MAX(columns(),20u);
1441         size_t len = 0;
1442         int i;
1443
1444         if (!arg_plain) {
1445
1446                 for (i = level - 1; i >= 0; i--) {
1447                         len += 2;
1448                         if (len > max_len - 3 && !arg_full) {
1449                                 printf("%s...\n",max_len % 2 ? "" : " ");
1450                                 return 0;
1451                         }
1452                         printf("%s", draw_special_char(branches & (1 << i) ? DRAW_TREE_VERTICAL : DRAW_TREE_SPACE));
1453                 }
1454                 len += 2;
1455
1456                 if (len > max_len - 3 && !arg_full) {
1457                         printf("%s...\n",max_len % 2 ? "" : " ");
1458                         return 0;
1459                 }
1460
1461                 printf("%s", draw_special_char(last ? DRAW_TREE_RIGHT : DRAW_TREE_BRANCH));
1462         }
1463
1464         if (arg_full){
1465                 printf("%s\n", name);
1466                 return 0;
1467         }
1468
1469         n = ellipsize(name, max_len-len, 100);
1470         if (!n)
1471                 return log_oom();
1472
1473         printf("%s\n", n);
1474         return 0;
1475 }
1476
1477 static int list_dependencies_get_dependencies(sd_bus *bus, const char *name, char ***deps) {
1478
1479         static const char *dependencies[_DEPENDENCY_MAX] = {
1480                 [DEPENDENCY_FORWARD] = "Requires\0"
1481                                        "RequiresOverridable\0"
1482                                        "Requisite\0"
1483                                        "RequisiteOverridable\0"
1484                                        "Wants\0"
1485                                        "BindsTo\0",
1486                 [DEPENDENCY_REVERSE] = "RequiredBy\0"
1487                                        "RequiredByOverridable\0"
1488                                        "WantedBy\0"
1489                                        "PartOf\0"
1490                                        "BoundBy\0",
1491                 [DEPENDENCY_AFTER]   = "After\0",
1492                 [DEPENDENCY_BEFORE]  = "Before\0",
1493         };
1494
1495         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1496         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
1497         _cleanup_strv_free_ char **ret = NULL;
1498         _cleanup_free_ char *path = NULL;
1499         int r;
1500
1501         assert(bus);
1502         assert(name);
1503         assert(deps);
1504         assert_cc(ELEMENTSOF(dependencies) == _DEPENDENCY_MAX);
1505
1506         path = unit_dbus_path_from_name(name);
1507         if (!path)
1508                 return log_oom();
1509
1510         r = sd_bus_call_method(
1511                         bus,
1512                         "org.freedesktop.systemd1",
1513                         path,
1514                         "org.freedesktop.DBus.Properties",
1515                         "GetAll",
1516                         &error,
1517                         &reply,
1518                         "s", "org.freedesktop.systemd1.Unit");
1519         if (r < 0) {
1520                 log_error("Failed to get properties of %s: %s", name, bus_error_message(&error, r));
1521                 return r;
1522         }
1523
1524         r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "{sv}");
1525         if (r < 0)
1526                 return bus_log_parse_error(r);
1527
1528         while ((r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
1529                 const char *prop;
1530
1531                 r = sd_bus_message_read(reply, "s", &prop);
1532                 if (r < 0)
1533                         return bus_log_parse_error(r);
1534
1535                 if (!nulstr_contains(dependencies[arg_dependency], prop)) {
1536                         r = sd_bus_message_skip(reply, "v");
1537                         if (r < 0)
1538                                 return bus_log_parse_error(r);
1539                 } else {
1540
1541                         r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_VARIANT, "as");
1542                         if (r < 0)
1543                                 return bus_log_parse_error(r);
1544
1545                         r = bus_message_read_strv_extend(reply, &ret);
1546                         if (r < 0)
1547                                 return bus_log_parse_error(r);
1548
1549                         r = sd_bus_message_exit_container(reply);
1550                         if (r < 0)
1551                                 return bus_log_parse_error(r);
1552                 }
1553
1554                 r = sd_bus_message_exit_container(reply);
1555                 if (r < 0)
1556                         return bus_log_parse_error(r);
1557
1558         }
1559         if (r < 0)
1560                 return bus_log_parse_error(r);
1561
1562         r = sd_bus_message_exit_container(reply);
1563         if (r < 0)
1564                 return bus_log_parse_error(r);
1565
1566         *deps = ret;
1567         ret = NULL;
1568
1569         return 0;
1570 }
1571
1572 static int list_dependencies_compare(const void *_a, const void *_b) {
1573         const char **a = (const char**) _a, **b = (const char**) _b;
1574
1575         if (unit_name_to_type(*a) == UNIT_TARGET && unit_name_to_type(*b) != UNIT_TARGET)
1576                 return 1;
1577         if (unit_name_to_type(*a) != UNIT_TARGET && unit_name_to_type(*b) == UNIT_TARGET)
1578                 return -1;
1579
1580         return strcasecmp(*a, *b);
1581 }
1582
1583 static int list_dependencies_one(
1584                 sd_bus *bus,
1585                 const char *name,
1586                 int level,
1587                 char ***units,
1588                 unsigned int branches) {
1589
1590         _cleanup_strv_free_ char **deps = NULL;
1591         char **c;
1592         int r = 0;
1593
1594         assert(bus);
1595         assert(name);
1596         assert(units);
1597
1598         r = strv_extend(units, name);
1599         if (r < 0)
1600                 return log_oom();
1601
1602         r = list_dependencies_get_dependencies(bus, name, &deps);
1603         if (r < 0)
1604                 return r;
1605
1606         qsort_safe(deps, strv_length(deps), sizeof (char*), list_dependencies_compare);
1607
1608         STRV_FOREACH(c, deps) {
1609                 int state;
1610
1611                 if (strv_contains(*units, *c)) {
1612                         if (!arg_plain) {
1613                                 r = list_dependencies_print("...", level + 1, (branches << 1) | (c[1] == NULL ? 0 : 1), 1);
1614                                 if (r < 0)
1615                                         return r;
1616                         }
1617                         continue;
1618                 }
1619
1620                 state = check_one_unit(bus, *c, "activating\0active\0reloading\0", true);
1621                 if (state > 0)
1622                         printf("%s%s%s ", ansi_highlight_green(), draw_special_char(DRAW_BLACK_CIRCLE), ansi_highlight_off());
1623                 else
1624                         printf("%s%s%s ", ansi_highlight_red(), draw_special_char(DRAW_BLACK_CIRCLE), ansi_highlight_off());
1625
1626                 r = list_dependencies_print(*c, level, branches, c[1] == NULL);
1627                 if (r < 0)
1628                         return r;
1629
1630                 if (arg_all || unit_name_to_type(*c) == UNIT_TARGET) {
1631                        r = list_dependencies_one(bus, *c, level + 1, units, (branches << 1) | (c[1] == NULL ? 0 : 1));
1632                        if (r < 0)
1633                                return r;
1634                 }
1635         }
1636
1637         if (!arg_plain)
1638                 strv_remove(*units, name);
1639
1640         return 0;
1641 }
1642
1643 static int list_dependencies(sd_bus *bus, char **args) {
1644         _cleanup_strv_free_ char **units = NULL;
1645         _cleanup_free_ char *unit = NULL;
1646         const char *u;
1647
1648         assert(bus);
1649
1650         if (args[1]) {
1651                 unit = unit_name_mangle(args[1], MANGLE_NOGLOB);
1652                 if (!unit)
1653                         return log_oom();
1654                 u = unit;
1655         } else
1656                 u = SPECIAL_DEFAULT_TARGET;
1657
1658         pager_open_if_enabled();
1659
1660         puts(u);
1661
1662         return list_dependencies_one(bus, u, 0, &units, 0);
1663 }
1664
1665 struct machine_info {
1666         bool is_host;
1667         char *name;
1668         char *state;
1669         char *control_group;
1670         uint32_t n_failed_units;
1671         uint32_t n_jobs;
1672         usec_t timestamp;
1673 };
1674
1675 static const struct bus_properties_map machine_info_property_map[] = {
1676         { "SystemState",        "s", NULL, offsetof(struct machine_info, state)          },
1677         { "NJobs",              "u", NULL, offsetof(struct machine_info, n_jobs)         },
1678         { "NFailedUnits",       "u", NULL, offsetof(struct machine_info, n_failed_units) },
1679         { "ControlGroup",       "s", NULL, offsetof(struct machine_info, control_group)  },
1680         { "UserspaceTimestamp", "t", NULL, offsetof(struct machine_info, timestamp)      },
1681         {}
1682 };
1683
1684 static void free_machines_list(struct machine_info *machine_infos, int n) {
1685         int i;
1686
1687         if (!machine_infos)
1688                 return;
1689
1690         for (i = 0; i < n; i++) {
1691                 free(machine_infos[i].name);
1692                 free(machine_infos[i].state);
1693                 free(machine_infos[i].control_group);
1694         }
1695
1696         free(machine_infos);
1697 }
1698
1699 static int compare_machine_info(const void *a, const void *b) {
1700         const struct machine_info *u = a, *v = b;
1701
1702         if (u->is_host != v->is_host)
1703                 return u->is_host > v->is_host ? -1 : 1;
1704
1705         return strcasecmp(u->name, v->name);
1706 }
1707
1708 static int get_machine_properties(sd_bus *bus, struct machine_info *mi) {
1709         _cleanup_bus_close_unref_ sd_bus *container = NULL;
1710         int r;
1711
1712         assert(mi);
1713
1714         if (!bus) {
1715                 r = sd_bus_open_system_container(&container, mi->name);
1716                 if (r < 0)
1717                         return r;
1718
1719                 bus = container;
1720         }
1721
1722         r = bus_map_all_properties(bus, "org.freedesktop.systemd1", "/org/freedesktop/systemd1", machine_info_property_map, mi);
1723         if (r < 0)
1724                 return r;
1725
1726         return 0;
1727 }
1728
1729 static bool output_show_machine(const char *name, char **patterns) {
1730         char **i;
1731
1732         assert(name);
1733
1734         if (strv_isempty(patterns))
1735                 return true;
1736
1737         STRV_FOREACH(i, patterns)
1738                 if (fnmatch(*i, name, FNM_NOESCAPE) == 0)
1739                         return true;
1740
1741         return false;
1742 }
1743
1744 static int get_machine_list(
1745                 sd_bus *bus,
1746                 struct machine_info **_machine_infos,
1747                 char **patterns) {
1748
1749         struct machine_info *machine_infos = NULL;
1750         _cleanup_strv_free_ char **m = NULL;
1751         _cleanup_free_ char *hn = NULL;
1752         size_t sz = 0;
1753         char **i;
1754         int c = 0;
1755
1756         hn = gethostname_malloc();
1757         if (!hn)
1758                 return log_oom();
1759
1760         if (output_show_machine(hn, patterns)) {
1761                 if (!GREEDY_REALLOC0(machine_infos, sz, c+1))
1762                         return log_oom();
1763
1764                 machine_infos[c].is_host = true;
1765                 machine_infos[c].name = hn;
1766                 hn = NULL;
1767
1768                 get_machine_properties(bus, &machine_infos[c]);
1769                 c++;
1770         }
1771
1772         sd_get_machine_names(&m);
1773         STRV_FOREACH(i, m) {
1774                 _cleanup_free_ char *class = NULL;
1775
1776                 if (!output_show_machine(*i, patterns))
1777                         continue;
1778
1779                 sd_machine_get_class(*i, &class);
1780                 if (!streq_ptr(class, "container"))
1781                         continue;
1782
1783                 if (!GREEDY_REALLOC0(machine_infos, sz, c+1)) {
1784                         free_machines_list(machine_infos, c);
1785                         return log_oom();
1786                 }
1787
1788                 machine_infos[c].is_host = false;
1789                 machine_infos[c].name = strdup(*i);
1790                 if (!machine_infos[c].name) {
1791                         free_machines_list(machine_infos, c);
1792                         return log_oom();
1793                 }
1794
1795                 get_machine_properties(NULL, &machine_infos[c]);
1796                 c++;
1797         }
1798
1799         *_machine_infos = machine_infos;
1800         return c;
1801 }
1802
1803 static void output_machines_list(struct machine_info *machine_infos, unsigned n) {
1804         struct machine_info *m;
1805         unsigned
1806                 circle_len = 0,
1807                 namelen = sizeof("NAME") - 1,
1808                 statelen = sizeof("STATE") - 1,
1809                 failedlen = sizeof("FAILED") - 1,
1810                 jobslen = sizeof("JOBS") - 1;
1811
1812         assert(machine_infos || n == 0);
1813
1814         for (m = machine_infos; m < machine_infos + n; m++) {
1815                 namelen = MAX(namelen, strlen(m->name) + (m->is_host ? sizeof(" (host)") - 1 : 0));
1816                 statelen = MAX(statelen, m->state ? strlen(m->state) : 0);
1817                 failedlen = MAX(failedlen, DECIMAL_STR_WIDTH(m->n_failed_units));
1818                 jobslen = MAX(jobslen, DECIMAL_STR_WIDTH(m->n_jobs));
1819
1820                 if (!arg_no_legend && !streq_ptr(m->state, "running"))
1821                         circle_len = 2;
1822         }
1823
1824         if (!arg_no_legend) {
1825                 if (circle_len > 0)
1826                         fputs("  ", stdout);
1827
1828                 printf("%-*s %-*s %-*s %-*s\n",
1829                          namelen, "NAME",
1830                         statelen, "STATE",
1831                        failedlen, "FAILED",
1832                          jobslen, "JOBS");
1833         }
1834
1835         for (m = machine_infos; m < machine_infos + n; m++) {
1836                 const char *on_state = "", *off_state = "";
1837                 const char *on_failed = "", *off_failed = "";
1838                 bool circle = false;
1839
1840                 if (streq_ptr(m->state, "degraded")) {
1841                         on_state = ansi_highlight_red();
1842                         off_state = ansi_highlight_off();
1843                         circle = true;
1844                 } else if (!streq_ptr(m->state, "running")) {
1845                         on_state = ansi_highlight_yellow();
1846                         off_state = ansi_highlight_off();
1847                         circle = true;
1848                 }
1849
1850                 if (m->n_failed_units > 0) {
1851                         on_failed = ansi_highlight_red();
1852                         off_failed = ansi_highlight_off();
1853                 } else
1854                         on_failed = off_failed = "";
1855
1856                 if (circle_len > 0)
1857                         printf("%s%s%s ", on_state, circle ? draw_special_char(DRAW_BLACK_CIRCLE) : " ", off_state);
1858
1859                 if (m->is_host)
1860                         printf("%-*s (host) %s%-*s%s %s%*u%s %*u\n",
1861                                (int) (namelen - (sizeof(" (host)")-1)), strna(m->name),
1862                                on_state, statelen, strna(m->state), off_state,
1863                                on_failed, failedlen, m->n_failed_units, off_failed,
1864                                jobslen, m->n_jobs);
1865                 else
1866                         printf("%-*s %s%-*s%s %s%*u%s %*u\n",
1867                                namelen, strna(m->name),
1868                                on_state, statelen, strna(m->state), off_state,
1869                                on_failed, failedlen, m->n_failed_units, off_failed,
1870                                jobslen, m->n_jobs);
1871         }
1872
1873         if (!arg_no_legend)
1874                 printf("\n%u machines listed.\n", n);
1875 }
1876
1877 static int list_machines(sd_bus *bus, char **args) {
1878         struct machine_info *machine_infos = NULL;
1879         int r;
1880
1881         assert(bus);
1882
1883         if (geteuid() != 0) {
1884                 log_error("Must be root.");
1885                 return -EPERM;
1886         }
1887
1888         pager_open_if_enabled();
1889
1890         r = get_machine_list(bus, &machine_infos, strv_skip_first(args));
1891         if (r < 0)
1892                 return r;
1893
1894         qsort_safe(machine_infos, r, sizeof(struct machine_info), compare_machine_info);
1895         output_machines_list(machine_infos, r);
1896         free_machines_list(machine_infos, r);
1897
1898         return 0;
1899 }
1900
1901 static int get_default(sd_bus *bus, char **args) {
1902         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
1903         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1904         _cleanup_free_ char *_path = NULL;
1905         const char *path;
1906         int r;
1907
1908         if (!bus || avoid_bus()) {
1909                 r = unit_file_get_default(arg_scope, arg_root, &_path);
1910                 if (r < 0)
1911                         return log_error_errno(r, "Failed to get default target: %m");
1912                 path = _path;
1913
1914         } else {
1915                 r = sd_bus_call_method(
1916                                 bus,
1917                                 "org.freedesktop.systemd1",
1918                                 "/org/freedesktop/systemd1",
1919                                 "org.freedesktop.systemd1.Manager",
1920                                 "GetDefaultTarget",
1921                                 &error,
1922                                 &reply,
1923                                 NULL);
1924                 if (r < 0) {
1925                         log_error("Failed to get default target: %s", bus_error_message(&error, -r));
1926                         return r;
1927                 }
1928
1929                 r = sd_bus_message_read(reply, "s", &path);
1930                 if (r < 0)
1931                         return bus_log_parse_error(r);
1932         }
1933
1934         if (path)
1935                 printf("%s\n", path);
1936
1937         return 0;
1938 }
1939
1940 static void dump_unit_file_changes(const UnitFileChange *changes, unsigned n_changes) {
1941         unsigned i;
1942
1943         assert(changes || n_changes == 0);
1944
1945         for (i = 0; i < n_changes; i++) {
1946                 if (changes[i].type == UNIT_FILE_SYMLINK)
1947                         log_info("Created symlink from %s to %s.", changes[i].path, changes[i].source);
1948                 else
1949                         log_info("Removed symlink %s.", changes[i].path);
1950         }
1951 }
1952
1953 static int deserialize_and_dump_unit_file_changes(sd_bus_message *m) {
1954         const char *type, *path, *source;
1955         int r;
1956
1957         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sss)");
1958         if (r < 0)
1959                 return bus_log_parse_error(r);
1960
1961         while ((r = sd_bus_message_read(m, "(sss)", &type, &path, &source)) > 0) {
1962                 if (!arg_quiet) {
1963                         if (streq(type, "symlink"))
1964                                 log_info("Created symlink from %s to %s.", path, source);
1965                         else
1966                                 log_info("Removed symlink %s.", path);
1967                 }
1968         }
1969         if (r < 0)
1970                 return bus_log_parse_error(r);
1971
1972         r = sd_bus_message_exit_container(m);
1973         if (r < 0)
1974                 return bus_log_parse_error(r);
1975
1976         return 0;
1977 }
1978
1979 static int set_default(sd_bus *bus, char **args) {
1980         _cleanup_free_ char *unit = NULL;
1981         UnitFileChange *changes = NULL;
1982         unsigned n_changes = 0;
1983         int r;
1984
1985         unit = unit_name_mangle_with_suffix(args[1], MANGLE_NOGLOB, ".target");
1986         if (!unit)
1987                 return log_oom();
1988
1989         if (!bus || avoid_bus()) {
1990                 r = unit_file_set_default(arg_scope, arg_root, unit, true, &changes, &n_changes);
1991                 if (r < 0)
1992                         return log_error_errno(r, "Failed to set default target: %m");
1993
1994                 if (!arg_quiet)
1995                         dump_unit_file_changes(changes, n_changes);
1996
1997                 r = 0;
1998         } else {
1999                 _cleanup_bus_message_unref_ sd_bus_message *reply = NULL, *m = NULL;
2000                 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
2001
2002                 r = sd_bus_message_new_method_call(
2003                                 bus,
2004                                 &m,
2005                                 "org.freedesktop.systemd1",
2006                                 "/org/freedesktop/systemd1",
2007                                 "org.freedesktop.systemd1.Manager",
2008                                 "SetDefaultTarget");
2009                 if (r < 0)
2010                         return bus_log_create_error(r);
2011
2012                 r = sd_bus_message_set_allow_interactive_authorization(m, arg_ask_password);
2013                 if (r < 0)
2014                         return bus_log_create_error(r);
2015
2016                 r = sd_bus_message_append(m, "sb", unit, 1);
2017                 if (r < 0)
2018                         return bus_log_create_error(r);
2019
2020                 r = sd_bus_call(bus, m, 0, &error, &reply);
2021                 if (r < 0) {
2022                         log_error("Failed to set default target: %s", bus_error_message(&error, -r));
2023                         return r;
2024                 }
2025
2026                 r = deserialize_and_dump_unit_file_changes(reply);
2027                 if (r < 0)
2028                         return r;
2029
2030                 /* Try to reload if enabled */
2031                 if (!arg_no_reload)
2032                         r = daemon_reload(bus, args);
2033                 else
2034                         r = 0;
2035         }
2036
2037         unit_file_changes_free(changes, n_changes);
2038
2039         return r;
2040 }
2041
2042 struct job_info {
2043         uint32_t id;
2044         const char *name, *type, *state;
2045 };
2046
2047 static void output_jobs_list(const struct job_info* jobs, unsigned n, bool skipped) {
2048         unsigned id_len, unit_len, type_len, state_len;
2049         const struct job_info *j;
2050         const char *on, *off;
2051         bool shorten = false;
2052
2053         assert(n == 0 || jobs);
2054
2055         if (n == 0) {
2056                 on = ansi_highlight_green();
2057                 off = ansi_highlight_off();
2058
2059                 printf("%sNo jobs %s.%s\n", on, skipped ? "listed" : "running", off);
2060                 return;
2061         }
2062
2063         pager_open_if_enabled();
2064
2065         id_len = strlen("JOB");
2066         unit_len = strlen("UNIT");
2067         type_len = strlen("TYPE");
2068         state_len = strlen("STATE");
2069
2070         for (j = jobs; j < jobs + n; j++) {
2071                 uint32_t id = j->id;
2072                 assert(j->name && j->type && j->state);
2073
2074                 id_len = MAX(id_len, DECIMAL_STR_WIDTH(id));
2075                 unit_len = MAX(unit_len, strlen(j->name));
2076                 type_len = MAX(type_len, strlen(j->type));
2077                 state_len = MAX(state_len, strlen(j->state));
2078         }
2079
2080         if (!arg_full && id_len + 1 + unit_len + type_len + 1 + state_len > columns()) {
2081                 unit_len = MAX(33u, columns() - id_len - type_len - state_len - 3);
2082                 shorten = true;
2083         }
2084
2085         if (!arg_no_legend)
2086                 printf("%*s %-*s %-*s %-*s\n",
2087                        id_len, "JOB",
2088                        unit_len, "UNIT",
2089                        type_len, "TYPE",
2090                        state_len, "STATE");
2091
2092         for (j = jobs; j < jobs + n; j++) {
2093                 _cleanup_free_ char *e = NULL;
2094
2095                 if (streq(j->state, "running")) {
2096                         on = ansi_highlight();
2097                         off = ansi_highlight_off();
2098                 } else
2099                         on = off = "";
2100
2101                 e = shorten ? ellipsize(j->name, unit_len, 33) : NULL;
2102                 printf("%*u %s%-*s%s %-*s %s%-*s%s\n",
2103                        id_len, j->id,
2104                        on, unit_len, e ? e : j->name, off,
2105                        type_len, j->type,
2106                        on, state_len, j->state, off);
2107         }
2108
2109         if (!arg_no_legend) {
2110                 on = ansi_highlight();
2111                 off = ansi_highlight_off();
2112
2113                 printf("\n%s%u jobs listed%s.\n", on, n, off);
2114         }
2115 }
2116
2117 static bool output_show_job(struct job_info *job, char **patterns) {
2118         char **pattern;
2119
2120         assert(job);
2121
2122         if (strv_isempty(patterns))
2123                 return true;
2124
2125         STRV_FOREACH(pattern, patterns)
2126                 if (fnmatch(*pattern, job->name, FNM_NOESCAPE) == 0)
2127                         return true;
2128         return false;
2129 }
2130
2131 static int list_jobs(sd_bus *bus, char **args) {
2132         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
2133         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
2134         const char *name, *type, *state, *job_path, *unit_path;
2135         _cleanup_free_ struct job_info *jobs = NULL;
2136         size_t size = 0;
2137         unsigned c = 0;
2138         uint32_t id;
2139         int r;
2140         bool skipped = false;
2141
2142         r = sd_bus_call_method(
2143                         bus,
2144                         "org.freedesktop.systemd1",
2145                         "/org/freedesktop/systemd1",
2146                         "org.freedesktop.systemd1.Manager",
2147                         "ListJobs",
2148                         &error,
2149                         &reply,
2150                         NULL);
2151         if (r < 0) {
2152                 log_error("Failed to list jobs: %s", bus_error_message(&error, r));
2153                 return r;
2154         }
2155
2156         r = sd_bus_message_enter_container(reply, 'a', "(usssoo)");
2157         if (r < 0)
2158                 return bus_log_parse_error(r);
2159
2160         while ((r = sd_bus_message_read(reply, "(usssoo)", &id, &name, &type, &state, &job_path, &unit_path)) > 0) {
2161                 struct job_info job = { id, name, type, state };
2162
2163                 if (!output_show_job(&job, strv_skip_first(args))) {
2164                         skipped = true;
2165                         continue;
2166                 }
2167
2168                 if (!GREEDY_REALLOC(jobs, size, c + 1))
2169                         return log_oom();
2170
2171                 jobs[c++] = job;
2172         }
2173         if (r < 0)
2174                 return bus_log_parse_error(r);
2175
2176         r = sd_bus_message_exit_container(reply);
2177         if (r < 0)
2178                 return bus_log_parse_error(r);
2179
2180         output_jobs_list(jobs, c, skipped);
2181         return r;
2182 }
2183
2184 static int cancel_job(sd_bus *bus, char **args) {
2185         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
2186         char **name;
2187         int r = 0;
2188
2189         assert(args);
2190
2191         if (strv_length(args) <= 1)
2192                 return daemon_reload(bus, args);
2193
2194         STRV_FOREACH(name, args+1) {
2195                 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2196                 uint32_t id;
2197                 int q;
2198
2199                 q = safe_atou32(*name, &id);
2200                 if (q < 0)
2201                         return log_error_errno(q, "Failed to parse job id \"%s\": %m", *name);
2202
2203                 q = sd_bus_message_new_method_call(
2204                                 bus,
2205                                 &m,
2206                                 "org.freedesktop.systemd1",
2207                                 "/org/freedesktop/systemd1",
2208                                 "org.freedesktop.systemd1.Manager",
2209                                 "CancelJob");
2210                 if (q < 0)
2211                         return bus_log_create_error(q);
2212
2213                 q = sd_bus_message_set_allow_interactive_authorization(m, arg_ask_password);
2214                 if (q < 0)
2215                         return bus_log_create_error(1);
2216
2217                 q = sd_bus_message_append(m, "u", id);
2218                 if (q < 0)
2219                         return bus_log_create_error(q);
2220
2221                 q = sd_bus_call(bus, m, 0, &error, NULL);
2222                 if (q < 0) {
2223                         log_error("Failed to cancel job %"PRIu32": %s", id, bus_error_message(&error, q));
2224                         if (r == 0)
2225                                 r = q;
2226                 }
2227         }
2228
2229         return r;
2230 }
2231
2232 static int need_daemon_reload(sd_bus *bus, const char *unit) {
2233         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
2234         const char *path;
2235         int b, r;
2236
2237         /* We ignore all errors here, since this is used to show a
2238          * warning only */
2239
2240         /* We don't use unit_dbus_path_from_name() directly since we
2241          * don't want to load the unit if it isn't loaded. */
2242
2243         r = sd_bus_call_method(
2244                         bus,
2245                         "org.freedesktop.systemd1",
2246                         "/org/freedesktop/systemd1",
2247                         "org.freedesktop.systemd1.Manager",
2248                         "GetUnit",
2249                         NULL,
2250                         &reply,
2251                         "s", unit);
2252         if (r < 0)
2253                 return r;
2254
2255         r = sd_bus_message_read(reply, "o", &path);
2256         if (r < 0)
2257                 return r;
2258
2259         r = sd_bus_get_property_trivial(
2260                         bus,
2261                         "org.freedesktop.systemd1",
2262                         path,
2263                         "org.freedesktop.systemd1.Unit",
2264                         "NeedDaemonReload",
2265                         NULL,
2266                         'b', &b);
2267         if (r < 0)
2268                 return r;
2269
2270         return b;
2271 }
2272
2273 static void warn_unit_file_changed(const char *name) {
2274         log_warning("%sWarning:%s %s changed on disk. Run 'systemctl%s daemon-reload' to reload units.",
2275                     ansi_highlight_red(),
2276                     ansi_highlight_off(),
2277                     name,
2278                     arg_scope == UNIT_FILE_SYSTEM ? "" : " --user");
2279 }
2280
2281 typedef struct WaitData {
2282         Set *set;
2283
2284         char *name;
2285         char *result;
2286 } WaitData;
2287
2288 static int wait_filter(sd_bus *bus, sd_bus_message *m, void *data, sd_bus_error *error) {
2289         WaitData *d = data;
2290
2291         assert(bus);
2292         assert(m);
2293         assert(d);
2294
2295         log_debug("Got D-Bus request: %s.%s() on %s",
2296                   sd_bus_message_get_interface(m),
2297                   sd_bus_message_get_member(m),
2298                   sd_bus_message_get_path(m));
2299
2300         if (sd_bus_message_is_signal(m, "org.freedesktop.DBus.Local", "Disconnected")) {
2301                 log_error("Warning! D-Bus connection terminated.");
2302                 sd_bus_close(bus);
2303         } else if (sd_bus_message_is_signal(m, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2304                 uint32_t id;
2305                 const char *path, *result, *unit;
2306                 char *ret;
2307                 int r;
2308
2309                 r = sd_bus_message_read(m, "uoss", &id, &path, &unit, &result);
2310                 if (r >= 0) {
2311                         ret = set_remove(d->set, (char*) path);
2312                         if (!ret)
2313                                 return 0;
2314
2315                         free(ret);
2316
2317                         if (!isempty(result))
2318                                 d->result = strdup(result);
2319
2320                         if (!isempty(unit))
2321                                 d->name = strdup(unit);
2322
2323                         return 0;
2324                 }
2325 #ifndef NOLEGACY
2326                 r = sd_bus_message_read(m, "uos", &id, &path, &result);
2327                 if (r >= 0) {
2328                         ret = set_remove(d->set, (char*) path);
2329                         if (!ret)
2330                                 return 0;
2331
2332                         free(ret);
2333
2334                         if (*result)
2335                                 d->result = strdup(result);
2336
2337                         return 0;
2338                 }
2339 #endif
2340
2341                 bus_log_parse_error(r);
2342         }
2343
2344         return 0;
2345 }
2346
2347 static int enable_wait_for_jobs(sd_bus *bus) {
2348         int r;
2349
2350         assert(bus);
2351
2352         r = sd_bus_add_match(
2353                         bus,
2354                         NULL,
2355                         "type='signal',"
2356                         "sender='org.freedesktop.systemd1',"
2357                         "interface='org.freedesktop.systemd1.Manager',"
2358                         "member='JobRemoved',"
2359                         "path='/org/freedesktop/systemd1'",
2360                         NULL, NULL);
2361         if (r < 0) {
2362                 log_error("Failed to add match");
2363                 return -EIO;
2364         }
2365
2366         /* This is slightly dirty, since we don't undo the match registrations. */
2367         return 0;
2368 }
2369
2370 static int bus_process_wait(sd_bus *bus) {
2371         int r;
2372
2373         for (;;) {
2374                 r = sd_bus_process(bus, NULL);
2375                 if (r < 0)
2376                         return r;
2377                 if (r > 0)
2378                         return 0;
2379                 r = sd_bus_wait(bus, (uint64_t) -1);
2380                 if (r < 0)
2381                         return r;
2382         }
2383 }
2384
2385 static int check_wait_response(WaitData *d) {
2386         int r = 0;
2387
2388         assert(d->result);
2389
2390         if (!arg_quiet) {
2391                 if (streq(d->result, "canceled"))
2392                         log_error("Job for %s canceled.", strna(d->name));
2393                 else if (streq(d->result, "timeout"))
2394                         log_error("Job for %s timed out.", strna(d->name));
2395                 else if (streq(d->result, "dependency"))
2396                         log_error("A dependency job for %s failed. See 'journalctl -xe' for details.", strna(d->name));
2397                 else if (streq(d->result, "invalid"))
2398                         log_error("Job for %s invalid.", strna(d->name));
2399                 else if (streq(d->result, "assert"))
2400                         log_error("Assertion failed on job for %s.", strna(d->name));
2401                 else if (streq(d->result, "unsupported"))
2402                         log_error("Operation on or unit type of %s not supported on this system.", strna(d->name));
2403                 else if (!streq(d->result, "done") && !streq(d->result, "skipped")) {
2404                         if (d->name) {
2405                                 bool quotes;
2406
2407                                 quotes = chars_intersect(d->name, SHELL_NEED_QUOTES);
2408
2409                                 log_error("Job for %s failed. See \"systemctl status %s%s%s\" and \"journalctl -xe\" for details.",
2410                                           d->name,
2411                                           quotes ? "'" : "", d->name, quotes ? "'" : "");
2412                         } else
2413                                 log_error("Job failed. See \"journalctl -xe\" for details.");
2414                 }
2415         }
2416
2417         if (streq(d->result, "canceled"))
2418                 r = -ECANCELED;
2419         else if (streq(d->result, "timeout"))
2420                 r = -ETIME;
2421         else if (streq(d->result, "dependency"))
2422                 r = -EIO;
2423         else if (streq(d->result, "invalid"))
2424                 r = -ENOEXEC;
2425         else if (streq(d->result, "assert"))
2426                 r = -EPROTO;
2427         else if (streq(d->result, "unsupported"))
2428                 r = -ENOTSUP;
2429         else if (!streq(d->result, "done") && !streq(d->result, "skipped"))
2430                 r = -EIO;
2431
2432         return r;
2433 }
2434
2435 static int wait_for_jobs(sd_bus *bus, Set *s) {
2436         _cleanup_bus_slot_unref_ sd_bus_slot *slot = NULL;
2437         WaitData d = { .set = s };
2438         int r = 0, q;
2439
2440         assert(bus);
2441         assert(s);
2442
2443         q = sd_bus_add_filter(bus, &slot, wait_filter, &d);
2444         if (q < 0)
2445                 return log_oom();
2446
2447         while (!set_isempty(s)) {
2448                 q = bus_process_wait(bus);
2449                 if (q < 0)
2450                         return log_error_errno(q, "Failed to wait for response: %m");
2451
2452                 if (d.result) {
2453                         q = check_wait_response(&d);
2454                         /* Return the first error as it is most likely to be
2455                          * meaningful. */
2456                         if (q < 0 && r == 0)
2457                                 r = q;
2458                         log_debug("Got result %s/%s for job %s",
2459                                   strna(d.result), strerror(-q), strna(d.name));
2460                 }
2461
2462                 free(d.name);
2463                 d.name = NULL;
2464
2465                 free(d.result);
2466                 d.result = NULL;
2467         }
2468
2469         return r;
2470 }
2471
2472 static int check_one_unit(sd_bus *bus, const char *name, const char *good_states, bool quiet) {
2473         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
2474         _cleanup_free_ char *n = NULL, *state = NULL;
2475         const char *path;
2476         int r;
2477
2478         assert(name);
2479
2480         n = unit_name_mangle(name, MANGLE_NOGLOB);
2481         if (!n)
2482                 return log_oom();
2483
2484         /* We don't use unit_dbus_path_from_name() directly since we
2485          * don't want to load the unit if it isn't loaded. */
2486
2487         r = sd_bus_call_method(
2488                         bus,
2489                         "org.freedesktop.systemd1",
2490                         "/org/freedesktop/systemd1",
2491                         "org.freedesktop.systemd1.Manager",
2492                         "GetUnit",
2493                         NULL,
2494                         &reply,
2495                         "s", n);
2496         if (r < 0) {
2497                 if (!quiet)
2498                         puts("unknown");
2499                 return 0;
2500         }
2501
2502         r = sd_bus_message_read(reply, "o", &path);
2503         if (r < 0)
2504                 return bus_log_parse_error(r);
2505
2506         r = sd_bus_get_property_string(
2507                         bus,
2508                         "org.freedesktop.systemd1",
2509                         path,
2510                         "org.freedesktop.systemd1.Unit",
2511                         "ActiveState",
2512                         NULL,
2513                         &state);
2514         if (r < 0) {
2515                 if (!quiet)
2516                         puts("unknown");
2517                 return 0;
2518         }
2519
2520         if (!quiet)
2521                 puts(state);
2522
2523         return nulstr_contains(good_states, state);
2524 }
2525
2526 static int check_triggering_units(
2527                 sd_bus *bus,
2528                 const char *name) {
2529
2530         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
2531         _cleanup_free_ char *path = NULL, *n = NULL, *state = NULL;
2532         _cleanup_strv_free_ char **triggered_by = NULL;
2533         bool print_warning_label = true;
2534         char **i;
2535         int r;
2536
2537         n = unit_name_mangle(name, MANGLE_NOGLOB);
2538         if (!n)
2539                 return log_oom();
2540
2541         path = unit_dbus_path_from_name(n);
2542         if (!path)
2543                 return log_oom();
2544
2545         r = sd_bus_get_property_string(
2546                         bus,
2547                         "org.freedesktop.systemd1",
2548                         path,
2549                         "org.freedesktop.systemd1.Unit",
2550                         "LoadState",
2551                         &error,
2552                         &state);
2553         if (r < 0) {
2554                 log_error("Failed to get load state of %s: %s", n, bus_error_message(&error, r));
2555                 return r;
2556         }
2557
2558         if (streq(state, "masked"))
2559                 return 0;
2560
2561         r = sd_bus_get_property_strv(
2562                         bus,
2563                         "org.freedesktop.systemd1",
2564                         path,
2565                         "org.freedesktop.systemd1.Unit",
2566                         "TriggeredBy",
2567                         &error,
2568                         &triggered_by);
2569         if (r < 0) {
2570                 log_error("Failed to get triggered by array of %s: %s", n, bus_error_message(&error, r));
2571                 return r;
2572         }
2573
2574         STRV_FOREACH(i, triggered_by) {
2575                 r = check_one_unit(bus, *i, "active\0reloading\0", true);
2576                 if (r < 0)
2577                         return log_error_errno(r, "Failed to check unit: %m");
2578
2579                 if (r == 0)
2580                         continue;
2581
2582                 if (print_warning_label) {
2583                         log_warning("Warning: Stopping %s, but it can still be activated by:", n);
2584                         print_warning_label = false;
2585                 }
2586
2587                 log_warning("  %s", *i);
2588         }
2589
2590         return 0;
2591 }
2592
2593 static const struct {
2594         const char *verb;
2595         const char *method;
2596 } unit_actions[] = {
2597         { "start",                 "StartUnit" },
2598         { "stop",                  "StopUnit" },
2599         { "condstop",              "StopUnit" },
2600         { "reload",                "ReloadUnit" },
2601         { "restart",               "RestartUnit" },
2602         { "try-restart",           "TryRestartUnit" },
2603         { "condrestart",           "TryRestartUnit" },
2604         { "reload-or-restart",     "ReloadOrRestartUnit" },
2605         { "reload-or-try-restart", "ReloadOrTryRestartUnit" },
2606         { "condreload",            "ReloadOrTryRestartUnit" },
2607         { "force-reload",          "ReloadOrTryRestartUnit" }
2608 };
2609
2610 static const char *verb_to_method(const char *verb) {
2611        uint i;
2612
2613        for (i = 0; i < ELEMENTSOF(unit_actions); i++)
2614                 if (streq_ptr(unit_actions[i].verb, verb))
2615                         return unit_actions[i].method;
2616
2617        return "StartUnit";
2618 }
2619
2620 static const char *method_to_verb(const char *method) {
2621        uint i;
2622
2623        for (i = 0; i < ELEMENTSOF(unit_actions); i++)
2624                 if (streq_ptr(unit_actions[i].method, method))
2625                         return unit_actions[i].verb;
2626
2627        return "n/a";
2628 }
2629
2630 static int start_unit_one(
2631                 sd_bus *bus,
2632                 const char *method,
2633                 const char *name,
2634                 const char *mode,
2635                 sd_bus_error *error,
2636                 Set *s) {
2637
2638         _cleanup_bus_message_unref_ sd_bus_message *m = NULL, *reply = NULL;
2639         const char *path;
2640         int r;
2641
2642         assert(method);
2643         assert(name);
2644         assert(mode);
2645         assert(error);
2646
2647         log_debug("Calling manager for %s on %s, %s", method, name, mode);
2648
2649         r = sd_bus_message_new_method_call(
2650                         bus,
2651                         &m,
2652                         "org.freedesktop.systemd1",
2653                         "/org/freedesktop/systemd1",
2654                         "org.freedesktop.systemd1.Manager",
2655                         method);
2656         if (r < 0)
2657                 return bus_log_create_error(r);
2658
2659         r = sd_bus_message_set_allow_interactive_authorization(m, arg_ask_password);
2660         if (r < 0)
2661                 return bus_log_create_error(r);
2662
2663         r = sd_bus_message_append(m, "ss", name, mode);
2664         if (r < 0)
2665                 return bus_log_create_error(r);
2666
2667         r = sd_bus_call(bus, m, 0, error, &reply);
2668         if (r < 0) {
2669                 const char *verb;
2670
2671                 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
2672                         /* There's always a fallback possible for
2673                          * legacy actions. */
2674                         return -EADDRNOTAVAIL;
2675
2676                 verb = method_to_verb(method);
2677
2678                 log_error("Failed to %s %s: %s", verb, name, bus_error_message(error, r));
2679                 return r;
2680         }
2681
2682         r = sd_bus_message_read(reply, "o", &path);
2683         if (r < 0)
2684                 return bus_log_parse_error(r);
2685
2686         if (need_daemon_reload(bus, name) > 0)
2687                 warn_unit_file_changed(name);
2688
2689         if (s) {
2690                 char *p;
2691
2692                 p = strdup(path);
2693                 if (!p)
2694                         return log_oom();
2695
2696                 log_debug("Adding %s to the set", p);
2697                 r = set_consume(s, p);
2698                 if (r < 0)
2699                         return log_oom();
2700         }
2701
2702         return 0;
2703 }
2704
2705 static int expand_names(sd_bus *bus, char **names, const char* suffix, char ***ret) {
2706
2707         _cleanup_strv_free_ char **mangled = NULL, **globs = NULL;
2708         char **name;
2709         int r = 0, i;
2710
2711         STRV_FOREACH(name, names) {
2712                 char *t;
2713
2714                 if (suffix)
2715                         t = unit_name_mangle_with_suffix(*name, MANGLE_GLOB, suffix);
2716                 else
2717                         t = unit_name_mangle(*name, MANGLE_GLOB);
2718                 if (!t)
2719                         return log_oom();
2720
2721                 if (string_is_glob(t))
2722                         r = strv_consume(&globs, t);
2723                 else
2724                         r = strv_consume(&mangled, t);
2725                 if (r < 0)
2726                         return log_oom();
2727         }
2728
2729         /* Query the manager only if any of the names are a glob, since
2730          * this is fairly expensive */
2731         if (!strv_isempty(globs)) {
2732                 _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
2733                 _cleanup_free_ UnitInfo *unit_infos = NULL;
2734
2735                 r = get_unit_list(bus, NULL, globs, &unit_infos, 0, &reply);
2736                 if (r < 0)
2737                         return r;
2738
2739                 for (i = 0; i < r; i++)
2740                         if (strv_extend(&mangled, unit_infos[i].id) < 0)
2741                                 return log_oom();
2742         }
2743
2744         *ret = mangled;
2745         mangled = NULL; /* do not free */
2746
2747         return 0;
2748 }
2749
2750 static const struct {
2751         const char *target;
2752         const char *verb;
2753         const char *mode;
2754 } action_table[_ACTION_MAX] = {
2755         [ACTION_HALT]         = { SPECIAL_HALT_TARGET,         "halt",         "replace-irreversibly" },
2756         [ACTION_POWEROFF]     = { SPECIAL_POWEROFF_TARGET,     "poweroff",     "replace-irreversibly" },
2757         [ACTION_REBOOT]       = { SPECIAL_REBOOT_TARGET,       "reboot",       "replace-irreversibly" },
2758         [ACTION_KEXEC]        = { SPECIAL_KEXEC_TARGET,        "kexec",        "replace-irreversibly" },
2759         [ACTION_RUNLEVEL2]    = { SPECIAL_RUNLEVEL2_TARGET,    NULL,           "isolate" },
2760         [ACTION_RUNLEVEL3]    = { SPECIAL_RUNLEVEL3_TARGET,    NULL,           "isolate" },
2761         [ACTION_RUNLEVEL4]    = { SPECIAL_RUNLEVEL4_TARGET,    NULL,           "isolate" },
2762         [ACTION_RUNLEVEL5]    = { SPECIAL_RUNLEVEL5_TARGET,    NULL,           "isolate" },
2763         [ACTION_RESCUE]       = { SPECIAL_RESCUE_TARGET,       "rescue",       "isolate" },
2764         [ACTION_EMERGENCY]    = { SPECIAL_EMERGENCY_TARGET,    "emergency",    "isolate" },
2765         [ACTION_DEFAULT]      = { SPECIAL_DEFAULT_TARGET,      "default",      "isolate" },
2766         [ACTION_EXIT]         = { SPECIAL_EXIT_TARGET,         "exit",         "replace-irreversibly" },
2767         [ACTION_SUSPEND]      = { SPECIAL_SUSPEND_TARGET,      "suspend",      "replace-irreversibly" },
2768         [ACTION_HIBERNATE]    = { SPECIAL_HIBERNATE_TARGET,    "hibernate",    "replace-irreversibly" },
2769         [ACTION_HYBRID_SLEEP] = { SPECIAL_HYBRID_SLEEP_TARGET, "hybrid-sleep", "replace-irreversibly" },
2770 };
2771
2772 static enum action verb_to_action(const char *verb) {
2773         enum action i;
2774
2775         for (i = _ACTION_INVALID; i < _ACTION_MAX; i++)
2776                 if (streq_ptr(action_table[i].verb, verb))
2777                         return i;
2778
2779         return _ACTION_INVALID;
2780 }
2781
2782 static int start_unit(sd_bus *bus, char **args) {
2783         _cleanup_set_free_free_ Set *s = NULL;
2784         _cleanup_strv_free_ char **names = NULL;
2785         const char *method, *mode, *one_name, *suffix = NULL;
2786         char **name;
2787         int r = 0;
2788
2789         assert(bus);
2790
2791         ask_password_agent_open_if_enabled();
2792
2793         if (arg_action == ACTION_SYSTEMCTL) {
2794                 enum action action;
2795                 method = verb_to_method(args[0]);
2796                 action = verb_to_action(args[0]);
2797
2798                 if (streq(args[0], "isolate")) {
2799                         mode = "isolate";
2800                         suffix = ".target";
2801                 } else
2802                         mode = action_table[action].mode ?: arg_job_mode;
2803
2804                 one_name = action_table[action].target;
2805         } else {
2806                 assert(arg_action < ELEMENTSOF(action_table));
2807                 assert(action_table[arg_action].target);
2808
2809                 method = "StartUnit";
2810
2811                 mode = action_table[arg_action].mode;
2812                 one_name = action_table[arg_action].target;
2813         }
2814
2815         if (one_name)
2816                 names = strv_new(one_name, NULL);
2817         else {
2818                 r = expand_names(bus, args + 1, suffix, &names);
2819                 if (r < 0)
2820                         log_error_errno(r, "Failed to expand names: %m");
2821         }
2822
2823         if (!arg_no_block) {
2824                 r = enable_wait_for_jobs(bus);
2825                 if (r < 0)
2826                         return log_error_errno(r, "Could not watch jobs: %m");
2827
2828                 s = set_new(&string_hash_ops);
2829                 if (!s)
2830                         return log_oom();
2831         }
2832
2833         STRV_FOREACH(name, names) {
2834                 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
2835                 int q;
2836
2837                 q = start_unit_one(bus, method, *name, mode, &error, s);
2838                 if (r >= 0 && q < 0)
2839                         r = translate_bus_error_to_exit_status(q, &error);
2840         }
2841
2842         if (!arg_no_block) {
2843                 int q;
2844
2845                 q = wait_for_jobs(bus, s);
2846                 if (q < 0)
2847                         return q;
2848
2849                 /* When stopping units, warn if they can still be triggered by
2850                  * another active unit (socket, path, timer) */
2851                 if (!arg_quiet && streq(method, "StopUnit"))
2852                         STRV_FOREACH(name, names)
2853                                 check_triggering_units(bus, *name);
2854         }
2855
2856         return r;
2857 }
2858
2859 /* Ask systemd-logind, which might grant access to unprivileged users
2860  * through PolicyKit */
2861 static int reboot_with_logind(sd_bus *bus, enum action a) {
2862 #ifdef HAVE_LOGIND
2863         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
2864         const char *method;
2865         int r;
2866
2867         if (!bus)
2868                 return -EIO;
2869
2870         polkit_agent_open_if_enabled();
2871
2872         switch (a) {
2873
2874         case ACTION_REBOOT:
2875                 method = "Reboot";
2876                 break;
2877
2878         case ACTION_POWEROFF:
2879                 method = "PowerOff";
2880                 break;
2881
2882         case ACTION_SUSPEND:
2883                 method = "Suspend";
2884                 break;
2885
2886         case ACTION_HIBERNATE:
2887                 method = "Hibernate";
2888                 break;
2889
2890         case ACTION_HYBRID_SLEEP:
2891                 method = "HybridSleep";
2892                 break;
2893
2894         default:
2895                 return -EINVAL;
2896         }
2897
2898         r = sd_bus_call_method(
2899                         bus,
2900                         "org.freedesktop.login1",
2901                         "/org/freedesktop/login1",
2902                         "org.freedesktop.login1.Manager",
2903                         method,
2904                         &error,
2905                         NULL,
2906                         "b", arg_ask_password);
2907         if (r < 0)
2908                 log_error("Failed to execute operation: %s", bus_error_message(&error, r));
2909
2910         return r;
2911 #else
2912         return -ENOSYS;
2913 #endif
2914 }
2915
2916 static int check_inhibitors(sd_bus *bus, enum action a) {
2917 #ifdef HAVE_LOGIND
2918         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
2919         _cleanup_strv_free_ char **sessions = NULL;
2920         const char *what, *who, *why, *mode;
2921         uint32_t uid, pid;
2922         unsigned c = 0;
2923         char **s;
2924         int r;
2925
2926         if (!bus)
2927                 return 0;
2928
2929         if (arg_ignore_inhibitors || arg_force > 0)
2930                 return 0;
2931
2932         if (arg_when > 0)
2933                 return 0;
2934
2935         if (geteuid() == 0)
2936                 return 0;
2937
2938         if (!on_tty())
2939                 return 0;
2940
2941         r = sd_bus_call_method(
2942                         bus,
2943                         "org.freedesktop.login1",
2944                         "/org/freedesktop/login1",
2945                         "org.freedesktop.login1.Manager",
2946                         "ListInhibitors",
2947                         NULL,
2948                         &reply,
2949                         NULL);
2950         if (r < 0)
2951                 /* If logind is not around, then there are no inhibitors... */
2952                 return 0;
2953
2954         r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssuu)");
2955         if (r < 0)
2956                 return bus_log_parse_error(r);
2957
2958         while ((r = sd_bus_message_read(reply, "(ssssuu)", &what, &who, &why, &mode, &uid, &pid)) > 0) {
2959                 _cleanup_free_ char *comm = NULL, *user = NULL;
2960                 _cleanup_strv_free_ char **sv = NULL;
2961
2962                 if (!streq(mode, "block"))
2963                         continue;
2964
2965                 sv = strv_split(what, ":");
2966                 if (!sv)
2967                         return log_oom();
2968
2969                 if (!strv_contains(sv,
2970                                   a == ACTION_HALT ||
2971                                   a == ACTION_POWEROFF ||
2972                                   a == ACTION_REBOOT ||
2973                                   a == ACTION_KEXEC ? "shutdown" : "sleep"))
2974                         continue;
2975
2976                 get_process_comm(pid, &comm);
2977                 user = uid_to_name(uid);
2978
2979                 log_warning("Operation inhibited by \"%s\" (PID "PID_FMT" \"%s\", user %s), reason is \"%s\".",
2980                             who, pid, strna(comm), strna(user), why);
2981
2982                 c++;
2983         }
2984         if (r < 0)
2985                 return bus_log_parse_error(r);
2986
2987         r = sd_bus_message_exit_container(reply);
2988         if (r < 0)
2989                 return bus_log_parse_error(r);
2990
2991         /* Check for current sessions */
2992         sd_get_sessions(&sessions);
2993         STRV_FOREACH(s, sessions) {
2994                 _cleanup_free_ char *type = NULL, *tty = NULL, *seat = NULL, *user = NULL, *service = NULL, *class = NULL;
2995
2996                 if (sd_session_get_uid(*s, &uid) < 0 || uid == getuid())
2997                         continue;
2998
2999                 if (sd_session_get_class(*s, &class) < 0 || !streq(class, "user"))
3000                         continue;
3001
3002                 if (sd_session_get_type(*s, &type) < 0 || (!streq(type, "x11") && !streq(type, "tty")))
3003                         continue;
3004
3005                 sd_session_get_tty(*s, &tty);
3006                 sd_session_get_seat(*s, &seat);
3007                 sd_session_get_service(*s, &service);
3008                 user = uid_to_name(uid);
3009
3010                 log_warning("User %s is logged in on %s.", strna(user), isempty(tty) ? (isempty(seat) ? strna(service) : seat) : tty);
3011                 c++;
3012         }
3013
3014         if (c <= 0)
3015                 return 0;
3016
3017         log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'systemctl %s -i'.",
3018                   action_table[a].verb);
3019
3020         return -EPERM;
3021 #else
3022         return 0;
3023 #endif
3024 }
3025
3026 static int start_special(sd_bus *bus, char **args) {
3027         enum action a;
3028         int r;
3029
3030         assert(args);
3031
3032         a = verb_to_action(args[0]);
3033
3034         r = check_inhibitors(bus, a);
3035         if (r < 0)
3036                 return r;
3037
3038         if (arg_force >= 2 && geteuid() != 0) {
3039                 log_error("Must be root.");
3040                 return -EPERM;
3041         }
3042
3043         if (arg_force >= 2 &&
3044             (a == ACTION_HALT ||
3045              a == ACTION_POWEROFF ||
3046              a == ACTION_REBOOT))
3047                 return halt_now(a);
3048
3049         if (arg_force >= 1 &&
3050             (a == ACTION_HALT ||
3051              a == ACTION_POWEROFF ||
3052              a == ACTION_REBOOT ||
3053              a == ACTION_KEXEC ||
3054              a == ACTION_EXIT))
3055                 return daemon_reload(bus, args);
3056
3057         /* first try logind, to allow authentication with polkit */
3058         if (geteuid() != 0 &&
3059             (a == ACTION_POWEROFF ||
3060              a == ACTION_REBOOT ||
3061              a == ACTION_SUSPEND ||
3062              a == ACTION_HIBERNATE ||
3063              a == ACTION_HYBRID_SLEEP)) {
3064                 r = reboot_with_logind(bus, a);
3065                 if (r >= 0)
3066                         return r;
3067         }
3068
3069         r = start_unit(bus, args);
3070         if (r == EXIT_SUCCESS)
3071                 warn_wall(a);
3072
3073         return r;
3074 }
3075
3076 static int check_unit_generic(sd_bus *bus, int code, const char *good_states, char **args) {
3077         _cleanup_strv_free_ char **names = NULL;
3078         char **name;
3079         int r;
3080
3081         assert(bus);
3082         assert(args);
3083
3084         r = expand_names(bus, args, NULL, &names);
3085         if (r < 0)
3086                 return log_error_errno(r, "Failed to expand names: %m");
3087
3088         STRV_FOREACH(name, names) {
3089                 int state;
3090
3091                 state = check_one_unit(bus, *name, good_states, arg_quiet);
3092                 if (state < 0)
3093                         return state;
3094                 if (state == 0)
3095                         r = code;
3096         }
3097
3098         return r;
3099 }
3100
3101 static int check_unit_active(sd_bus *bus, char **args) {
3102         /* According to LSB: 3, "program is not running" */
3103         return check_unit_generic(bus, 3, "active\0reloading\0", args + 1);
3104 }
3105
3106 static int check_unit_failed(sd_bus *bus, char **args) {
3107         return check_unit_generic(bus, 1, "failed\0", args + 1);
3108 }
3109
3110 static int kill_unit(sd_bus *bus, char **args) {
3111         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
3112         _cleanup_strv_free_ char **names = NULL;
3113         char **name;
3114         int r, q;
3115
3116         assert(bus);
3117         assert(args);
3118
3119         if (!arg_kill_who)
3120                 arg_kill_who = "all";
3121
3122         r = expand_names(bus, args + 1, NULL, &names);
3123         if (r < 0)
3124                 log_error_errno(r, "Failed to expand names: %m");
3125
3126         STRV_FOREACH(name, names) {
3127                 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
3128
3129                 q = sd_bus_message_new_method_call(
3130                                 bus,
3131                                 &m,
3132                                 "org.freedesktop.systemd1",
3133                                 "/org/freedesktop/systemd1",
3134                                 "org.freedesktop.systemd1.Manager",
3135                                 "KillUnit");
3136                 if (q < 0)
3137                         return bus_log_create_error(q);
3138
3139                 q = sd_bus_message_set_allow_interactive_authorization(m, arg_ask_password);
3140                 if (q < 0)
3141                         return bus_log_create_error(q);
3142
3143                 q = sd_bus_message_append(m, "ssi", *names, arg_kill_who, arg_signal);
3144                 if (q < 0)
3145                         return bus_log_create_error(q);
3146
3147                 q = sd_bus_call(bus, m, 0, &error, NULL);
3148                 if (q < 0) {
3149                         log_error("Failed to kill unit %s: %s", *names, bus_error_message(&error, q));
3150                         if (r == 0)
3151                                 r = q;
3152                 }
3153         }
3154
3155         return r;
3156 }
3157
3158 typedef struct ExecStatusInfo {
3159         char *name;
3160
3161         char *path;
3162         char **argv;
3163
3164         bool ignore;
3165
3166         usec_t start_timestamp;
3167         usec_t exit_timestamp;
3168         pid_t pid;
3169         int code;
3170         int status;
3171
3172         LIST_FIELDS(struct ExecStatusInfo, exec);
3173 } ExecStatusInfo;
3174
3175 static void exec_status_info_free(ExecStatusInfo *i) {
3176         assert(i);
3177
3178         free(i->name);
3179         free(i->path);
3180         strv_free(i->argv);
3181         free(i);
3182 }
3183
3184 static int exec_status_info_deserialize(sd_bus_message *m, ExecStatusInfo *i) {
3185         uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
3186         const char *path;
3187         uint32_t pid;
3188         int32_t code, status;
3189         int ignore, r;
3190
3191         assert(m);
3192         assert(i);
3193
3194         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_STRUCT, "sasbttttuii");
3195         if (r < 0)
3196                 return bus_log_parse_error(r);
3197         else if (r == 0)
3198                 return 0;
3199
3200         r = sd_bus_message_read(m, "s", &path);
3201         if (r < 0)
3202                 return bus_log_parse_error(r);
3203
3204         i->path = strdup(path);
3205         if (!i->path)
3206                 return log_oom();
3207
3208         r = sd_bus_message_read_strv(m, &i->argv);
3209         if (r < 0)
3210                 return bus_log_parse_error(r);
3211
3212         r = sd_bus_message_read(m,
3213                                 "bttttuii",
3214                                 &ignore,
3215                                 &start_timestamp, &start_timestamp_monotonic,
3216                                 &exit_timestamp, &exit_timestamp_monotonic,
3217                                 &pid,
3218                                 &code, &status);
3219         if (r < 0)
3220                 return bus_log_parse_error(r);
3221
3222         i->ignore = ignore;
3223         i->start_timestamp = (usec_t) start_timestamp;
3224         i->exit_timestamp = (usec_t) exit_timestamp;
3225         i->pid = (pid_t) pid;
3226         i->code = code;
3227         i->status = status;
3228
3229         r = sd_bus_message_exit_container(m);
3230         if (r < 0)
3231                 return bus_log_parse_error(r);
3232
3233         return 1;
3234 }
3235
3236 typedef struct UnitStatusInfo {
3237         const char *id;
3238         const char *load_state;
3239         const char *active_state;
3240         const char *sub_state;
3241         const char *unit_file_state;
3242         const char *unit_file_preset;
3243
3244         const char *description;
3245         const char *following;
3246
3247         char **documentation;
3248
3249         const char *fragment_path;
3250         const char *source_path;
3251         const char *control_group;
3252
3253         char **dropin_paths;
3254
3255         const char *load_error;
3256         const char *result;
3257
3258         usec_t inactive_exit_timestamp;
3259         usec_t inactive_exit_timestamp_monotonic;
3260         usec_t active_enter_timestamp;
3261         usec_t active_exit_timestamp;
3262         usec_t inactive_enter_timestamp;
3263
3264         bool need_daemon_reload;
3265
3266         /* Service */
3267         pid_t main_pid;
3268         pid_t control_pid;
3269         const char *status_text;
3270         const char *pid_file;
3271         bool running:1;
3272         int status_errno;
3273
3274         usec_t start_timestamp;
3275         usec_t exit_timestamp;
3276
3277         int exit_code, exit_status;
3278
3279         usec_t condition_timestamp;
3280         bool condition_result;
3281         bool failed_condition_trigger;
3282         bool failed_condition_negate;
3283         const char *failed_condition;
3284         const char *failed_condition_parameter;
3285
3286         usec_t assert_timestamp;
3287         bool assert_result;
3288         bool failed_assert_trigger;
3289         bool failed_assert_negate;
3290         const char *failed_assert;
3291         const char *failed_assert_parameter;
3292
3293         /* Socket */
3294         unsigned n_accepted;
3295         unsigned n_connections;
3296         bool accept;
3297
3298         /* Pairs of type, path */
3299         char **listen;
3300
3301         /* Device */
3302         const char *sysfs_path;
3303
3304         /* Mount, Automount */
3305         const char *where;
3306
3307         /* Swap */
3308         const char *what;
3309
3310         LIST_HEAD(ExecStatusInfo, exec);
3311 } UnitStatusInfo;
3312
3313 static void print_status_info(
3314                 UnitStatusInfo *i,
3315                 bool *ellipsized) {
3316
3317         ExecStatusInfo *p;
3318         const char *active_on, *active_off, *on, *off, *ss;
3319         usec_t timestamp;
3320         char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], *s1;
3321         char since2[FORMAT_TIMESTAMP_MAX], *s2;
3322         const char *path;
3323         int flags =
3324                 arg_all * OUTPUT_SHOW_ALL |
3325                 (!on_tty() || pager_have()) * OUTPUT_FULL_WIDTH |
3326                 on_tty() * OUTPUT_COLOR |
3327                 !arg_quiet * OUTPUT_WARN_CUTOFF |
3328                 arg_full * OUTPUT_FULL_WIDTH;
3329         char **t, **t2;
3330
3331         assert(i);
3332
3333         /* This shows pretty information about a unit. See
3334          * print_property() for a low-level property printer */
3335
3336         if (streq_ptr(i->active_state, "failed")) {
3337                 active_on = ansi_highlight_red();
3338                 active_off = ansi_highlight_off();
3339         } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
3340                 active_on = ansi_highlight_green();
3341                 active_off = ansi_highlight_off();
3342         } else
3343                 active_on = active_off = "";
3344
3345         printf("%s%s%s %s", active_on, draw_special_char(DRAW_BLACK_CIRCLE), active_off, strna(i->id));
3346
3347         if (i->description && !streq_ptr(i->id, i->description))
3348                 printf(" - %s", i->description);
3349
3350         printf("\n");
3351
3352         if (i->following)
3353                 printf("   Follow: unit currently follows state of %s\n", i->following);
3354
3355         if (streq_ptr(i->load_state, "error")) {
3356                 on = ansi_highlight_red();
3357                 off = ansi_highlight_off();
3358         } else
3359                 on = off = "";
3360
3361         path = i->source_path ? i->source_path : i->fragment_path;
3362
3363         if (i->load_error)
3364                 printf("   Loaded: %s%s%s (Reason: %s)\n",
3365                        on, strna(i->load_state), off, i->load_error);
3366         else if (path && !isempty(i->unit_file_state) && !isempty(i->unit_file_preset))
3367                 printf("   Loaded: %s%s%s (%s; %s; vendor preset: %s)\n",
3368                        on, strna(i->load_state), off, path, i->unit_file_state, i->unit_file_preset);
3369         else if (path && !isempty(i->unit_file_state))
3370                 printf("   Loaded: %s%s%s (%s; %s)\n",
3371                        on, strna(i->load_state), off, path, i->unit_file_state);
3372         else if (path)
3373                 printf("   Loaded: %s%s%s (%s)\n",
3374                        on, strna(i->load_state), off, path);
3375         else
3376                 printf("   Loaded: %s%s%s\n",
3377                        on, strna(i->load_state), off);
3378
3379         if (!strv_isempty(i->dropin_paths)) {
3380                 _cleanup_free_ char *dir = NULL;
3381                 bool last = false;
3382                 char ** dropin;
3383
3384                 STRV_FOREACH(dropin, i->dropin_paths) {
3385                         if (! dir || last) {
3386                                 printf(dir ? "        " : "  Drop-In: ");
3387
3388                                 free(dir);
3389                                 dir = NULL;
3390
3391                                 if (path_get_parent(*dropin, &dir) < 0) {
3392                                         log_oom();
3393                                         return;
3394                                 }
3395
3396                                 printf("%s\n           %s", dir,
3397                                        draw_special_char(DRAW_TREE_RIGHT));
3398                         }
3399
3400                         last = ! (*(dropin + 1) && startswith(*(dropin + 1), dir));
3401
3402                         printf("%s%s", basename(*dropin), last ? "\n" : ", ");
3403                 }
3404         }
3405
3406         ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
3407         if (ss)
3408                 printf("   Active: %s%s (%s)%s",
3409                        active_on, strna(i->active_state), ss, active_off);
3410         else
3411                 printf("   Active: %s%s%s",
3412                        active_on, strna(i->active_state), active_off);
3413
3414         if (!isempty(i->result) && !streq(i->result, "success"))
3415                 printf(" (Result: %s)", i->result);
3416
3417         timestamp = (streq_ptr(i->active_state, "active")      ||
3418                      streq_ptr(i->active_state, "reloading"))   ? i->active_enter_timestamp :
3419                     (streq_ptr(i->active_state, "inactive")    ||
3420                      streq_ptr(i->active_state, "failed"))      ? i->inactive_enter_timestamp :
3421                     streq_ptr(i->active_state, "activating")    ? i->inactive_exit_timestamp :
3422                                                                   i->active_exit_timestamp;
3423
3424         s1 = format_timestamp_relative(since1, sizeof(since1), timestamp);
3425         s2 = format_timestamp(since2, sizeof(since2), timestamp);
3426
3427         if (s1)
3428                 printf(" since %s; %s\n", s2, s1);
3429         else if (s2)
3430                 printf(" since %s\n", s2);
3431         else
3432                 printf("\n");
3433
3434         if (!i->condition_result && i->condition_timestamp > 0) {
3435                 s1 = format_timestamp_relative(since1, sizeof(since1), i->condition_timestamp);
3436                 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
3437
3438                 printf("Condition: start %scondition failed%s at %s%s%s\n",
3439                        ansi_highlight_yellow(), ansi_highlight_off(),
3440                        s2, s1 ? "; " : "", s1 ? s1 : "");
3441                 if (i->failed_condition_trigger)
3442                         printf("           none of the trigger conditions were met\n");
3443                 else if (i->failed_condition)
3444                         printf("           %s=%s%s was not met\n",
3445                                i->failed_condition,
3446                                i->failed_condition_negate ? "!" : "",
3447                                i->failed_condition_parameter);
3448         }
3449
3450         if (!i->assert_result && i->assert_timestamp > 0) {
3451                 s1 = format_timestamp_relative(since1, sizeof(since1), i->assert_timestamp);
3452                 s2 = format_timestamp(since2, sizeof(since2), i->assert_timestamp);
3453
3454                 printf("   Assert: start %sassertion failed%s at %s%s%s\n",
3455                        ansi_highlight_red(), ansi_highlight_off(),
3456                        s2, s1 ? "; " : "", s1 ? s1 : "");
3457                 if (i->failed_assert_trigger)
3458                         printf("           none of the trigger assertions were met\n");
3459                 else if (i->failed_assert)
3460                         printf("           %s=%s%s was not met\n",
3461                                i->failed_assert,
3462                                i->failed_assert_negate ? "!" : "",
3463                                i->failed_assert_parameter);
3464         }
3465
3466         if (i->sysfs_path)
3467                 printf("   Device: %s\n", i->sysfs_path);
3468         if (i->where)
3469                 printf("    Where: %s\n", i->where);
3470         if (i->what)
3471                 printf("     What: %s\n", i->what);
3472
3473         STRV_FOREACH(t, i->documentation)
3474                 printf(" %*s %s\n", 9, t == i->documentation ? "Docs:" : "", *t);
3475
3476         STRV_FOREACH_PAIR(t, t2, i->listen)
3477                 printf(" %*s %s (%s)\n", 9, t == i->listen ? "Listen:" : "", *t2, *t);
3478
3479         if (i->accept)
3480                 printf(" Accepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
3481
3482         LIST_FOREACH(exec, p, i->exec) {
3483                 _cleanup_free_ char *argv = NULL;
3484                 bool good;
3485
3486                 /* Only show exited processes here */
3487                 if (p->code == 0)
3488                         continue;
3489
3490                 argv = strv_join(p->argv, " ");
3491                 printf("  Process: %u %s=%s ", p->pid, p->name, strna(argv));
3492
3493                 good = is_clean_exit_lsb(p->code, p->status, NULL);
3494                 if (!good) {
3495                         on = ansi_highlight_red();
3496                         off = ansi_highlight_off();
3497                 } else
3498                         on = off = "";
3499
3500                 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
3501
3502                 if (p->code == CLD_EXITED) {
3503                         const char *c;
3504
3505                         printf("status=%i", p->status);
3506
3507                         c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD);
3508                         if (c)
3509                                 printf("/%s", c);
3510
3511                 } else
3512                         printf("signal=%s", signal_to_string(p->status));
3513
3514                 printf(")%s\n", off);
3515
3516                 if (i->main_pid == p->pid &&
3517                     i->start_timestamp == p->start_timestamp &&
3518                     i->exit_timestamp == p->start_timestamp)
3519                         /* Let's not show this twice */
3520                         i->main_pid = 0;
3521
3522                 if (p->pid == i->control_pid)
3523                         i->control_pid = 0;
3524         }
3525
3526         if (i->main_pid > 0 || i->control_pid > 0) {
3527                 if (i->main_pid > 0) {
3528                         printf(" Main PID: "PID_FMT, i->main_pid);
3529
3530                         if (i->running) {
3531                                 _cleanup_free_ char *comm = NULL;
3532                                 get_process_comm(i->main_pid, &comm);
3533                                 if (comm)
3534                                         printf(" (%s)", comm);
3535                         } else if (i->exit_code > 0) {
3536                                 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
3537
3538                                 if (i->exit_code == CLD_EXITED) {
3539                                         const char *c;
3540
3541                                         printf("status=%i", i->exit_status);
3542
3543                                         c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD);
3544                                         if (c)
3545                                                 printf("/%s", c);
3546
3547                                 } else
3548                                         printf("signal=%s", signal_to_string(i->exit_status));
3549                                 printf(")");
3550                         }
3551
3552                         if (i->control_pid > 0)
3553                                 printf(";");
3554                 }
3555
3556                 if (i->control_pid > 0) {
3557                         _cleanup_free_ char *c = NULL;
3558
3559                         printf(" %8s: "PID_FMT, i->main_pid ? "" : " Control", i->control_pid);
3560
3561                         get_process_comm(i->control_pid, &c);
3562                         if (c)
3563                                 printf(" (%s)", c);
3564                 }
3565
3566                 printf("\n");
3567         }
3568
3569         if (i->status_text)
3570                 printf("   Status: \"%s\"\n", i->status_text);
3571         if (i->status_errno > 0)
3572                 printf("    Error: %i (%s)\n", i->status_errno, strerror(i->status_errno));
3573
3574         if (i->control_group &&
3575             (i->main_pid > 0 || i->control_pid > 0 ||
3576              ((arg_transport != BUS_TRANSPORT_LOCAL && arg_transport != BUS_TRANSPORT_CONTAINER) || cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, i->control_group, false) == 0))) {
3577                 unsigned c;
3578
3579                 printf("   CGroup: %s\n", i->control_group);
3580
3581                 if (arg_transport == BUS_TRANSPORT_LOCAL || arg_transport == BUS_TRANSPORT_CONTAINER) {
3582                         unsigned k = 0;
3583                         pid_t extra[2];
3584                         static const char prefix[] = "           ";
3585
3586                         c = columns();
3587                         if (c > sizeof(prefix) - 1)
3588                                 c -= sizeof(prefix) - 1;
3589                         else
3590                                 c = 0;
3591
3592                         if (i->main_pid > 0)
3593                                 extra[k++] = i->main_pid;
3594
3595                         if (i->control_pid > 0)
3596                                 extra[k++] = i->control_pid;
3597
3598                         show_cgroup_and_extra(SYSTEMD_CGROUP_CONTROLLER, i->control_group, prefix, c, false, extra, k, flags);
3599                 }
3600         }
3601
3602         if (i->id && arg_transport == BUS_TRANSPORT_LOCAL) {
3603                 show_journal_by_unit(stdout,
3604                                      i->id,
3605                                      arg_output,
3606                                      0,
3607                                      i->inactive_exit_timestamp_monotonic,
3608                                      arg_lines,
3609                                      getuid(),
3610                                      flags | OUTPUT_BEGIN_NEWLINE,
3611                                      arg_scope == UNIT_FILE_SYSTEM,
3612                                      ellipsized);
3613         }
3614
3615         if (i->need_daemon_reload)
3616                 warn_unit_file_changed(i->id);
3617 }
3618
3619 static void show_unit_help(UnitStatusInfo *i) {
3620         char **p;
3621
3622         assert(i);
3623
3624         if (!i->documentation) {
3625                 log_info("Documentation for %s not known.", i->id);
3626                 return;
3627         }
3628
3629         STRV_FOREACH(p, i->documentation)