chiark / gitweb /
systemctl: rename 'listen'
[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
41 #include "sd-daemon.h"
42 #include "sd-shutdown.h"
43 #include "sd-login.h"
44 #include "sd-bus.h"
45 #include "log.h"
46 #include "util.h"
47 #include "macro.h"
48 #include "set.h"
49 #include "utmp-wtmp.h"
50 #include "special.h"
51 #include "initreq.h"
52 #include "path-util.h"
53 #include "strv.h"
54 #include "cgroup-show.h"
55 #include "cgroup-util.h"
56 #include "list.h"
57 #include "path-lookup.h"
58 #include "conf-parser.h"
59 #include "exit-status.h"
60 #include "bus-errors.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 "path-util.h"
69 #include "socket-util.h"
70 #include "fileio.h"
71 #include "bus-util.h"
72 #include "bus-message.h"
73 #include "bus-error.h"
74
75 static char **arg_types = NULL;
76 static char **arg_states = NULL;
77 static char **arg_properties = NULL;
78 static bool arg_all = false;
79 static bool original_stdout_is_tty;
80 static enum dependency {
81         DEPENDENCY_FORWARD,
82         DEPENDENCY_REVERSE,
83         DEPENDENCY_AFTER,
84         DEPENDENCY_BEFORE,
85 } arg_dependency = DEPENDENCY_FORWARD;
86 static const char *arg_job_mode = "replace";
87 static UnitFileScope arg_scope = UNIT_FILE_SYSTEM;
88 static bool arg_no_block = false;
89 static bool arg_no_legend = false;
90 static bool arg_no_pager = false;
91 static bool arg_no_wtmp = false;
92 static bool arg_no_wall = false;
93 static bool arg_no_reload = false;
94 static bool arg_show_types = false;
95 static bool arg_ignore_inhibitors = false;
96 static bool arg_dry = false;
97 static bool arg_quiet = false;
98 static bool arg_full = false;
99 static int arg_force = 0;
100 static bool arg_ask_password = true;
101 static bool arg_runtime = false;
102 static char **arg_wall = NULL;
103 static const char *arg_kill_who = NULL;
104 static int arg_signal = SIGTERM;
105 static const char *arg_root = NULL;
106 static usec_t arg_when = 0;
107 static enum action {
108         _ACTION_INVALID,
109         ACTION_SYSTEMCTL,
110         ACTION_HALT,
111         ACTION_POWEROFF,
112         ACTION_REBOOT,
113         ACTION_KEXEC,
114         ACTION_EXIT,
115         ACTION_SUSPEND,
116         ACTION_HIBERNATE,
117         ACTION_HYBRID_SLEEP,
118         ACTION_RUNLEVEL2,
119         ACTION_RUNLEVEL3,
120         ACTION_RUNLEVEL4,
121         ACTION_RUNLEVEL5,
122         ACTION_RESCUE,
123         ACTION_EMERGENCY,
124         ACTION_DEFAULT,
125         ACTION_RELOAD,
126         ACTION_REEXEC,
127         ACTION_RUNLEVEL,
128         ACTION_CANCEL_SHUTDOWN,
129         _ACTION_MAX
130 } arg_action = ACTION_SYSTEMCTL;
131 static BusTransport arg_transport = BUS_TRANSPORT_LOCAL;
132 static char *arg_host = NULL;
133 static unsigned arg_lines = 10;
134 static OutputMode arg_output = OUTPUT_SHORT;
135 static bool arg_plain = false;
136
137 static int daemon_reload(sd_bus *bus, char **args);
138 static void halt_now(enum action a);
139
140 static void pager_open_if_enabled(void) {
141
142         if (arg_no_pager)
143                 return;
144
145         pager_open(false);
146 }
147
148 static void ask_password_agent_open_if_enabled(void) {
149
150         /* Open the password agent as a child process if necessary */
151
152         if (!arg_ask_password)
153                 return;
154
155         if (arg_scope != UNIT_FILE_SYSTEM)
156                 return;
157
158         if (arg_transport != BUS_TRANSPORT_LOCAL)
159                 return;
160
161         ask_password_agent_open();
162 }
163
164 #ifdef HAVE_LOGIND
165 static void polkit_agent_open_if_enabled(void) {
166
167         /* Open the polkit agent as a child process if necessary */
168
169         if (!arg_ask_password)
170                 return;
171
172         if (arg_scope != UNIT_FILE_SYSTEM)
173                 return;
174
175         if (arg_transport != BUS_TRANSPORT_LOCAL)
176                 return;
177
178         polkit_agent_open();
179 }
180 #endif
181
182 static int translate_bus_error_to_exit_status(int r, const sd_bus_error *error) {
183         assert(error);
184
185         if (!sd_bus_error_is_set(error))
186                 return r;
187
188         if (sd_bus_error_has_name(error, SD_BUS_ERROR_ACCESS_DENIED) ||
189             sd_bus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
190             sd_bus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
191             sd_bus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
192                 return EXIT_NOPERMISSION;
193
194         if (sd_bus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
195                 return EXIT_NOTINSTALLED;
196
197         if (sd_bus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
198             sd_bus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
199                 return EXIT_NOTIMPLEMENTED;
200
201         if (sd_bus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
202                 return EXIT_NOTCONFIGURED;
203
204         if (r != 0)
205                 return r;
206
207         return EXIT_FAILURE;
208 }
209
210 static void warn_wall(enum action a) {
211         static const char *table[_ACTION_MAX] = {
212                 [ACTION_HALT]            = "The system is going down for system halt NOW!",
213                 [ACTION_REBOOT]          = "The system is going down for reboot NOW!",
214                 [ACTION_POWEROFF]        = "The system is going down for power-off NOW!",
215                 [ACTION_KEXEC]           = "The system is going down for kexec reboot NOW!",
216                 [ACTION_RESCUE]          = "The system is going down to rescue mode NOW!",
217                 [ACTION_EMERGENCY]       = "The system is going down to emergency mode NOW!",
218                 [ACTION_CANCEL_SHUTDOWN] = "The system shutdown has been cancelled NOW!"
219         };
220
221         if (arg_no_wall)
222                 return;
223
224         if (arg_wall) {
225                 _cleanup_free_ char *p;
226
227                 p = strv_join(arg_wall, " ");
228                 if (!p) {
229                         log_oom();
230                         return;
231                 }
232
233                 if (*p) {
234                         utmp_wall(p, NULL);
235                         return;
236                 }
237         }
238
239         if (!table[a])
240                 return;
241
242         utmp_wall(table[a], NULL);
243 }
244
245 static bool avoid_bus(void) {
246
247         if (running_in_chroot() > 0)
248                 return true;
249
250         if (sd_booted() <= 0)
251                 return true;
252
253         if (!isempty(arg_root))
254                 return true;
255
256         if (arg_scope == UNIT_FILE_GLOBAL)
257                 return true;
258
259         return false;
260 }
261
262 static int compare_unit_info(const void *a, const void *b) {
263         const UnitInfo *u = a, *v = b;
264         const char *d1, *d2;
265
266         d1 = strrchr(u->id, '.');
267         d2 = strrchr(v->id, '.');
268
269         if (d1 && d2) {
270                 int r;
271
272                 r = strcasecmp(d1, d2);
273                 if (r != 0)
274                         return r;
275         }
276
277         return strcasecmp(u->id, v->id);
278 }
279
280 static bool output_show_unit(const UnitInfo *u) {
281         const char *dot;
282
283         if (!strv_isempty(arg_states))
284                 return
285                         strv_contains(arg_states, u->load_state) ||
286                         strv_contains(arg_states, u->sub_state) ||
287                         strv_contains(arg_states, u->active_state);
288
289         return (!arg_types || ((dot = strrchr(u->id, '.')) &&
290                                strv_find(arg_types, dot+1))) &&
291                 (arg_all || !(streq(u->active_state, "inactive")
292                               || u->following[0]) || u->job_id > 0);
293 }
294
295 static void output_units_list(const UnitInfo *unit_infos, unsigned c) {
296         unsigned id_len, max_id_len, load_len, active_len, sub_len, job_len, desc_len;
297         const UnitInfo *u;
298         unsigned n_shown = 0;
299         int job_count = 0;
300
301         max_id_len = sizeof("UNIT")-1;
302         load_len = sizeof("LOAD")-1;
303         active_len = sizeof("ACTIVE")-1;
304         sub_len = sizeof("SUB")-1;
305         job_len = sizeof("JOB")-1;
306         desc_len = 0;
307
308         for (u = unit_infos; u < unit_infos + c; u++) {
309                 if (!output_show_unit(u))
310                         continue;
311
312                 max_id_len = MAX(max_id_len, strlen(u->id));
313                 load_len = MAX(load_len, strlen(u->load_state));
314                 active_len = MAX(active_len, strlen(u->active_state));
315                 sub_len = MAX(sub_len, strlen(u->sub_state));
316
317                 if (u->job_id != 0) {
318                         job_len = MAX(job_len, strlen(u->job_type));
319                         job_count++;
320                 }
321         }
322
323         if (!arg_full && original_stdout_is_tty) {
324                 unsigned basic_len;
325
326                 id_len = MIN(max_id_len, 25u);
327                 basic_len = 5 + id_len + 5 + active_len + sub_len;
328
329                 if (job_count)
330                         basic_len += job_len + 1;
331
332                 if (basic_len < (unsigned) columns()) {
333                         unsigned extra_len, incr;
334                         extra_len = columns() - basic_len;
335
336                         /* Either UNIT already got 25, or is fully satisfied.
337                          * Grant up to 25 to DESC now. */
338                         incr = MIN(extra_len, 25u);
339                         desc_len += incr;
340                         extra_len -= incr;
341
342                         /* split the remaining space between UNIT and DESC,
343                          * but do not give UNIT more than it needs. */
344                         if (extra_len > 0) {
345                                 incr = MIN(extra_len / 2, max_id_len - id_len);
346                                 id_len += incr;
347                                 desc_len += extra_len - incr;
348                         }
349                 }
350         } else
351                 id_len = max_id_len;
352
353         for (u = unit_infos; u < unit_infos + c; u++) {
354                 _cleanup_free_ char *e = NULL;
355                 const char *on_loaded, *off_loaded, *on = "";
356                 const char *on_active, *off_active, *off = "";
357
358                 if (!output_show_unit(u))
359                         continue;
360
361                 if (!n_shown && !arg_no_legend) {
362                         printf("%-*s %-*s %-*s %-*s ",
363                                id_len, "UNIT",
364                                load_len, "LOAD",
365                                active_len, "ACTIVE",
366                                sub_len, "SUB");
367
368                         if (job_count)
369                                 printf("%-*s ", job_len, "JOB");
370
371                         if (!arg_full && arg_no_pager)
372                                 printf("%.*s\n", desc_len, "DESCRIPTION");
373                         else
374                                 printf("%s\n", "DESCRIPTION");
375                 }
376
377                 n_shown++;
378
379                 if (streq(u->load_state, "error") ||
380                     streq(u->load_state, "not-found")) {
381                         on_loaded = on = ansi_highlight_red();
382                         off_loaded = off = ansi_highlight_off();
383                 } else
384                         on_loaded = off_loaded = "";
385
386                 if (streq(u->active_state, "failed")) {
387                         on_active = on = ansi_highlight_red();
388                         off_active = off = ansi_highlight_off();
389                 } else
390                         on_active = off_active = "";
391
392                 e = arg_full ? NULL : ellipsize(u->id, id_len, 33);
393
394                 printf("%s%-*s%s %s%-*s%s %s%-*s %-*s%s %-*s",
395                        on, id_len, e ? e : u->id, off,
396                        on_loaded, load_len, u->load_state, off_loaded,
397                        on_active, active_len, u->active_state,
398                        sub_len, u->sub_state, off_active,
399                        job_count ? job_len + 1 : 0, u->job_id ? u->job_type : "");
400
401                 if (desc_len > 0)
402                         printf("%.*s\n", desc_len, u->description);
403                 else
404                         printf("%s\n", u->description);
405         }
406
407         if (!arg_no_legend) {
408                 const char *on, *off;
409
410                 if (n_shown) {
411                         printf("\nLOAD   = Reflects whether the unit definition was properly loaded.\n"
412                                "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
413                                "SUB    = The low-level unit activation state, values depend on unit type.\n");
414                         if (job_count)
415                                 printf("JOB    = Pending job for the unit.\n");
416                         puts("");
417                         on = ansi_highlight();
418                         off = ansi_highlight_off();
419                 } else {
420                         on = ansi_highlight_red();
421                         off = ansi_highlight_off();
422                 }
423
424                 if (arg_all)
425                         printf("%s%u loaded units listed.%s\n"
426                                "To show all installed unit files use 'systemctl list-unit-files'.\n",
427                                on, n_shown, off);
428                 else
429                         printf("%s%u loaded units listed.%s Pass --all to see loaded but inactive units, too.\n"
430                                "To show all installed unit files use 'systemctl list-unit-files'.\n",
431                                on, n_shown, off);
432         }
433 }
434
435 static int get_unit_list(
436                 sd_bus *bus,
437                 sd_bus_message **_reply,
438                 UnitInfo **_unit_infos) {
439
440         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
441         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
442         _cleanup_free_ UnitInfo *unit_infos = NULL;
443         size_t size = 0;
444         int r, c = 0;
445         UnitInfo u;
446
447         assert(bus);
448         assert(_reply);
449         assert(_unit_infos);
450
451         r = sd_bus_call_method(
452                         bus,
453                         "org.freedesktop.systemd1",
454                         "/org/freedesktop/systemd1",
455                         "org.freedesktop.systemd1.Manager",
456                         "ListUnits",
457                         &error,
458                         &reply,
459                         NULL);
460         if (r < 0) {
461                 log_error("Failed to list units: %s", bus_error_message(&error, r));
462                 return r;
463         }
464
465         r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssssouso)");
466         if (r < 0)
467                 return bus_log_parse_error(r);
468
469         while ((r = bus_parse_unit_info(reply, &u)) > 0) {
470
471                 if (!GREEDY_REALLOC(unit_infos, size, c+1))
472                         return log_oom();
473
474                 unit_infos[c++] = u;
475         }
476         if (r < 0)
477                 return bus_log_parse_error(r);
478
479         r = sd_bus_message_exit_container(reply);
480         if (r < 0)
481                 return bus_log_parse_error(r);
482
483         *_reply = reply;
484         reply = NULL;
485
486         *_unit_infos = unit_infos;
487         unit_infos = NULL;
488
489         return c;
490 }
491
492 static int list_units(sd_bus *bus, char **args) {
493         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
494         _cleanup_free_ UnitInfo *unit_infos = NULL;
495         int r;
496
497         pager_open_if_enabled();
498
499         r = get_unit_list(bus, &reply, &unit_infos);
500         if (r < 0)
501                 return r;
502
503         qsort_safe(unit_infos, r, sizeof(UnitInfo), compare_unit_info);
504         output_units_list(unit_infos, r);
505
506         return 0;
507 }
508
509 static int get_triggered_units(
510                 sd_bus *bus,
511                 const char* path,
512                 char*** ret) {
513
514         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
515         int r;
516
517         r = sd_bus_get_property_strv(
518                         bus,
519                         "org.freedesktop.systemd1",
520                         path,
521                         "org.freedesktop.systemd1.Unit",
522                         "Triggers",
523                         &error,
524                         ret);
525
526         if (r < 0)
527                 log_error("Failed to determine triggers: %s", bus_error_message(&error, r));
528
529         return 0;
530 }
531
532 static int get_listening(
533                 sd_bus *bus,
534                 const char* unit_path,
535                 char*** listening,
536                 unsigned *c) {
537
538         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
539         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
540         const char *type, *path;
541         int r;
542
543         r = sd_bus_get_property(
544                         bus,
545                         "org.freedesktop.systemd1",
546                         unit_path,
547                         "org.freedesktop.systemd1.Socket",
548                         "Listen",
549                         &error,
550                         &reply,
551                         "a(ss)");
552         if (r < 0) {
553                 log_error("Failed to get list of listening sockets: %s", bus_error_message(&error, r));
554                 return r;
555         }
556
557         r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ss)");
558         if (r < 0)
559                 return bus_log_parse_error(r);
560
561         while ((r = sd_bus_message_read(reply, "(ss)", &type, &path)) > 0) {
562
563                 r = strv_extend(listening, type);
564                 if (r < 0)
565                         return log_oom();
566
567                 r = strv_extend(listening, path);
568                 if (r < 0)
569                         return log_oom();
570
571                 (*c)++;
572         }
573         if (r < 0)
574                 return bus_log_parse_error(r);
575
576         r = sd_bus_message_exit_container(reply);
577         if (r < 0)
578                 return bus_log_parse_error(r);
579
580         return 0;
581 }
582
583 struct socket_info {
584         const char* id;
585
586         char* type;
587         char* path;
588
589         /* Note: triggered is a list here, although it almost certainly
590          * will always be one unit. Nevertheless, dbus API allows for multiple
591          * values, so let's follow that.*/
592         char** triggered;
593
594         /* The strv above is shared. free is set only in the first one. */
595         bool own_triggered;
596 };
597
598 static int socket_info_compare(struct socket_info *a, struct socket_info *b) {
599         int o;
600
601         o = strcmp(a->path, b->path);
602         if (o == 0)
603                 o = strcmp(a->type, b->type);
604
605         return o;
606 }
607
608 static int output_sockets_list(struct socket_info *socket_infos, unsigned cs) {
609         struct socket_info *s;
610         unsigned pathlen = sizeof("LISTEN") - 1,
611                 typelen = (sizeof("TYPE") - 1) * arg_show_types,
612                 socklen = sizeof("UNIT") - 1,
613                 servlen = sizeof("ACTIVATES") - 1;
614         const char *on, *off;
615
616         for (s = socket_infos; s < socket_infos + cs; s++) {
617                 unsigned tmp = 0;
618                 char **a;
619
620                 socklen = MAX(socklen, strlen(s->id));
621                 if (arg_show_types)
622                         typelen = MAX(typelen, strlen(s->type));
623                 pathlen = MAX(pathlen, strlen(s->path));
624
625                 STRV_FOREACH(a, s->triggered)
626                         tmp += strlen(*a) + 2*(a != s->triggered);
627                 servlen = MAX(servlen, tmp);
628         }
629
630         if (cs) {
631                 if (!arg_no_legend)
632                         printf("%-*s %-*.*s%-*s %s\n",
633                                pathlen, "LISTEN",
634                                typelen + arg_show_types, typelen + arg_show_types, "TYPE ",
635                                socklen, "UNIT",
636                                "ACTIVATES");
637
638                 for (s = socket_infos; s < socket_infos + cs; s++) {
639                         char **a;
640
641                         if (arg_show_types)
642                                 printf("%-*s %-*s %-*s",
643                                        pathlen, s->path, typelen, s->type, socklen, s->id);
644                         else
645                                 printf("%-*s %-*s",
646                                        pathlen, s->path, socklen, s->id);
647                         STRV_FOREACH(a, s->triggered)
648                                 printf("%s %s",
649                                        a == s->triggered ? "" : ",", *a);
650                         printf("\n");
651                 }
652
653                 on = ansi_highlight();
654                 off = ansi_highlight_off();
655                 if (!arg_no_legend)
656                         printf("\n");
657         } else {
658                 on = ansi_highlight_red();
659                 off = ansi_highlight_off();
660         }
661
662         if (!arg_no_legend) {
663                 printf("%s%u sockets listed.%s\n", on, cs, off);
664                 if (!arg_all)
665                         printf("Pass --all to see loaded but inactive sockets, too.\n");
666         }
667
668         return 0;
669 }
670
671 static int list_sockets(sd_bus *bus, char **args) {
672         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
673         _cleanup_free_ UnitInfo *unit_infos = NULL;
674         struct socket_info *socket_infos = NULL;
675         const UnitInfo *u;
676         struct socket_info *s;
677         unsigned cu = 0, cs = 0;
678         size_t size = 0;
679         int r;
680
681         pager_open_if_enabled();
682
683         r = get_unit_list(bus, &reply, &unit_infos);
684         if (r < 0)
685                 return r;
686
687         cu = (unsigned) r;
688
689         for (u = unit_infos; u < unit_infos + cu; u++) {
690                 _cleanup_strv_free_ char **listening = NULL, **triggered = NULL;
691                 unsigned c = 0, i;
692
693                 if (!output_show_unit(u))
694                         continue;
695
696                 if (!endswith(u->id, ".socket"))
697                         continue;
698
699                 r = get_triggered_units(bus, u->unit_path, &triggered);
700                 if (r < 0)
701                         goto cleanup;
702
703                 r = get_listening(bus, u->unit_path, &listening, &c);
704                 if (r < 0)
705                         goto cleanup;
706
707                 if (!GREEDY_REALLOC(socket_infos, size, cs + c)) {
708                         r = log_oom();
709                         goto cleanup;
710                 }
711
712                 for (i = 0; i < c; i++)
713                         socket_infos[cs + i] = (struct socket_info) {
714                                 .id = u->id,
715                                 .type = listening[i*2],
716                                 .path = listening[i*2 + 1],
717                                 .triggered = triggered,
718                                 .own_triggered = i==0,
719                         };
720
721                 /* from this point on we will cleanup those socket_infos */
722                 cs += c;
723                 free(listening);
724                 listening = triggered = NULL; /* avoid cleanup */
725         }
726
727         qsort_safe(socket_infos, cs, sizeof(struct socket_info),
728                    (__compar_fn_t) socket_info_compare);
729
730         output_sockets_list(socket_infos, cs);
731
732  cleanup:
733         assert(cs == 0 || socket_infos);
734         for (s = socket_infos; s < socket_infos + cs; s++) {
735                 free(s->type);
736                 free(s->path);
737                 if (s->own_triggered)
738                         strv_free(s->triggered);
739         }
740         free(socket_infos);
741
742         return r;
743 }
744
745 static int compare_unit_file_list(const void *a, const void *b) {
746         const char *d1, *d2;
747         const UnitFileList *u = a, *v = b;
748
749         d1 = strrchr(u->path, '.');
750         d2 = strrchr(v->path, '.');
751
752         if (d1 && d2) {
753                 int r;
754
755                 r = strcasecmp(d1, d2);
756                 if (r != 0)
757                         return r;
758         }
759
760         return strcasecmp(path_get_file_name(u->path), path_get_file_name(v->path));
761 }
762
763 static bool output_show_unit_file(const UnitFileList *u) {
764         const char *dot;
765
766         return !arg_types || ((dot = strrchr(u->path, '.')) && strv_find(arg_types, dot+1));
767 }
768
769 static void output_unit_file_list(const UnitFileList *units, unsigned c) {
770         unsigned max_id_len, id_cols, state_cols, n_shown = 0;
771         const UnitFileList *u;
772
773         max_id_len = sizeof("UNIT FILE")-1;
774         state_cols = sizeof("STATE")-1;
775
776         for (u = units; u < units + c; u++) {
777                 if (!output_show_unit_file(u))
778                         continue;
779
780                 max_id_len = MAX(max_id_len, strlen(path_get_file_name(u->path)));
781                 state_cols = MAX(state_cols, strlen(unit_file_state_to_string(u->state)));
782         }
783
784         if (!arg_full) {
785                 unsigned basic_cols;
786
787                 id_cols = MIN(max_id_len, 25u);
788                 basic_cols = 1 + id_cols + state_cols;
789                 if (basic_cols < (unsigned) columns())
790                         id_cols += MIN(columns() - basic_cols, max_id_len - id_cols);
791         } else
792                 id_cols = max_id_len;
793
794         if (!arg_no_legend)
795                 printf("%-*s %-*s\n",
796                        id_cols, "UNIT FILE",
797                        state_cols, "STATE");
798
799         for (u = units; u < units + c; u++) {
800                 _cleanup_free_ char *e = NULL;
801                 const char *on, *off;
802                 const char *id;
803
804                 if (!output_show_unit_file(u))
805                         continue;
806
807                 n_shown++;
808
809                 if (u->state == UNIT_FILE_MASKED ||
810                     u->state == UNIT_FILE_MASKED_RUNTIME ||
811                     u->state == UNIT_FILE_DISABLED ||
812                     u->state == UNIT_FILE_INVALID) {
813                         on  = ansi_highlight_red();
814                         off = ansi_highlight_off();
815                 } else if (u->state == UNIT_FILE_ENABLED) {
816                         on  = ansi_highlight_green();
817                         off = ansi_highlight_off();
818                 } else
819                         on = off = "";
820
821                 id = path_get_file_name(u->path);
822
823                 e = arg_full ? NULL : ellipsize(id, id_cols, 33);
824
825                 printf("%-*s %s%-*s%s\n",
826                        id_cols, e ? e : id,
827                        on, state_cols, unit_file_state_to_string(u->state), off);
828         }
829
830         if (!arg_no_legend)
831                 printf("\n%u unit files listed.\n", n_shown);
832 }
833
834 static int list_unit_files(sd_bus *bus, char **args) {
835         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
836         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
837         _cleanup_free_ UnitFileList *units = NULL;
838         unsigned c = 0;
839         const char *state;
840         char *path;
841         int r;
842
843         pager_open_if_enabled();
844
845         if (avoid_bus()) {
846                 Hashmap *h;
847                 UnitFileList *u;
848                 Iterator i;
849                 unsigned n_units;
850
851                 h = hashmap_new(string_hash_func, string_compare_func);
852                 if (!h)
853                         return log_oom();
854
855                 r = unit_file_get_list(arg_scope, arg_root, h);
856                 if (r < 0) {
857                         unit_file_list_free(h);
858                         log_error("Failed to get unit file list: %s", strerror(-r));
859                         return r;
860                 }
861
862                 n_units = hashmap_size(h);
863                 units = new(UnitFileList, n_units);
864                 if (!units) {
865                         unit_file_list_free(h);
866                         return log_oom();
867                 }
868
869                 HASHMAP_FOREACH(u, h, i) {
870                         memcpy(units + c++, u, sizeof(UnitFileList));
871                         free(u);
872                 }
873
874                 assert(c == n_units);
875                 hashmap_free(h);
876         } else {
877                 size_t size = 0;
878
879                 r = sd_bus_call_method(
880                                 bus,
881                                 "org.freedesktop.systemd1",
882                                 "/org/freedesktop/systemd1",
883                                 "org.freedesktop.systemd1.Manager",
884                                 "ListUnitFiles",
885                                 &error,
886                                 &reply,
887                                 NULL);
888                 if (r < 0) {
889                         log_error("Failed to list unit files: %s", bus_error_message(&error, r));
890                         return r;
891                 }
892
893                 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ss)");
894                 if (r < 0)
895                         return bus_log_parse_error(r);
896
897                 while ((r = sd_bus_message_read(reply, "(ss)", &path, &state)) > 0) {
898
899                         if (!GREEDY_REALLOC(units, size, c + 1))
900                                 return log_oom();
901
902                         units[c++] = (struct UnitFileList) {
903                                 path,
904                                 unit_file_state_from_string(state)
905                         };
906                 }
907                 if (r < 0)
908                         return bus_log_parse_error(r);
909
910                 r = sd_bus_message_exit_container(reply);
911                 if (r < 0)
912                         return bus_log_parse_error(r);
913         }
914
915         if (c > 0) {
916                 qsort(units, c, sizeof(UnitFileList), compare_unit_file_list);
917                 output_unit_file_list(units, c);
918         }
919
920         return 0;
921 }
922
923 static int list_dependencies_print(const char *name, int level, unsigned int branches, bool last) {
924         _cleanup_free_ char *n = NULL;
925         size_t max_len = MAX(columns(),20u);
926         size_t len = 0;
927         int i;
928
929         if (!arg_plain) {
930
931                 for (i = level - 1; i >= 0; i--) {
932                         len += 2;
933                         if(len > max_len - 3 && !arg_full) {
934                                 printf("%s...\n",max_len % 2 ? "" : " ");
935                                 return 0;
936                         }
937                         printf("%s", draw_special_char(branches & (1 << i) ? DRAW_TREE_VERT : DRAW_TREE_SPACE));
938                 }
939                 len += 2;
940
941                 if(len > max_len - 3 && !arg_full) {
942                         printf("%s...\n",max_len % 2 ? "" : " ");
943                         return 0;
944                 }
945
946                 printf("%s", draw_special_char(last ? DRAW_TREE_RIGHT : DRAW_TREE_BRANCH));
947         }
948
949         if (arg_full){
950                 printf("%s\n", name);
951                 return 0;
952         }
953
954         n = ellipsize(name, max_len-len, 100);
955         if(!n)
956                 return log_oom();
957
958         printf("%s\n", n);
959         return 0;
960 }
961
962 static int list_dependencies_get_dependencies(sd_bus *bus, const char *name, char ***deps) {
963
964         static const char *dependencies[] = {
965                 [DEPENDENCY_FORWARD] = "Requires\0"
966                                        "RequiresOverridable\0"
967                                        "Requisite\0"
968                                        "RequisiteOverridable\0"
969                                        "Wants\0",
970                 [DEPENDENCY_REVERSE] = "RequiredBy\0"
971                                        "RequiredByOverridable\0"
972                                        "WantedBy\0"
973                                        "PartOf\0",
974                 [DEPENDENCY_AFTER]   = "After\0",
975                 [DEPENDENCY_BEFORE]  = "Before\0",
976         };
977
978         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
979         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
980         _cleanup_strv_free_ char **ret = NULL;
981         _cleanup_free_ char *path = NULL;
982         int r;
983
984         assert(bus);
985         assert(name);
986         assert(deps);
987         assert(arg_dependency < ELEMENTSOF(dependencies));
988
989         path = unit_dbus_path_from_name(name);
990         if (!path)
991                 return log_oom();
992
993         r = sd_bus_call_method(
994                         bus,
995                         "org.freedesktop.systemd1",
996                         path,
997                         "org.freedesktop.DBus.Properties",
998                         "GetAll",
999                         &error,
1000                         &reply,
1001                         "s", "org.freedesktop.systemd1.Unit");
1002         if (r < 0) {
1003                 log_error("Failed to get properties of %s: %s", name, bus_error_message(&error, r));
1004                 return r;
1005         }
1006
1007         r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "{sv}");
1008         if (r < 0)
1009                 return bus_log_parse_error(r);
1010
1011         while ((r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
1012                 const char *prop;
1013
1014                 r = sd_bus_message_read(reply, "s", &prop);
1015                 if (r < 0)
1016                         return bus_log_parse_error(r);
1017
1018                 if (!nulstr_contains(dependencies[arg_dependency], prop)) {
1019                         r = sd_bus_message_skip(reply, "v");
1020                         if (r < 0)
1021                                 return bus_log_parse_error(r);
1022                 } else {
1023
1024                         r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_VARIANT, "as");
1025                         if (r < 0)
1026                                 return bus_log_parse_error(r);
1027
1028                         r = bus_message_read_strv_extend(reply, &ret);
1029                         if (r < 0)
1030                                 return bus_log_parse_error(r);
1031
1032                         r = sd_bus_message_exit_container(reply);
1033                         if (r < 0)
1034                                 return bus_log_parse_error(r);
1035                 }
1036
1037                 r = sd_bus_message_exit_container(reply);
1038                 if (r < 0)
1039                         return bus_log_parse_error(r);
1040
1041         }
1042         if (r < 0)
1043                 return bus_log_parse_error(r);
1044
1045         r = sd_bus_message_exit_container(reply);
1046         if (r < 0)
1047                 return bus_log_parse_error(r);
1048
1049         *deps = ret;
1050         ret = NULL;
1051
1052         return 0;
1053 }
1054
1055 static int list_dependencies_compare(const void *_a, const void *_b) {
1056         const char **a = (const char**) _a, **b = (const char**) _b;
1057
1058         if (unit_name_to_type(*a) == UNIT_TARGET && unit_name_to_type(*b) != UNIT_TARGET)
1059                 return 1;
1060         if (unit_name_to_type(*a) != UNIT_TARGET && unit_name_to_type(*b) == UNIT_TARGET)
1061                 return -1;
1062
1063         return strcasecmp(*a, *b);
1064 }
1065
1066 static int list_dependencies_one(
1067                 sd_bus *bus,
1068                 const char *name,
1069                 int level,
1070                 char ***units,
1071                 unsigned int branches) {
1072
1073         _cleanup_strv_free_ char **deps = NULL, **u;
1074         char **c;
1075         int r = 0;
1076
1077         assert(bus);
1078         assert(name);
1079         assert(units);
1080
1081         u = strv_append(*units, name);
1082         if (!u)
1083                 return log_oom();
1084
1085         r = list_dependencies_get_dependencies(bus, name, &deps);
1086         if (r < 0)
1087                 return r;
1088
1089         qsort_safe(deps, strv_length(deps), sizeof (char*), list_dependencies_compare);
1090
1091         STRV_FOREACH(c, deps) {
1092                 if (strv_contains(u, *c)) {
1093                         if (!arg_plain) {
1094                                 r = list_dependencies_print("...", level + 1, (branches << 1) | (c[1] == NULL ? 0 : 1), 1);
1095                                 if (r < 0)
1096                                         return r;
1097                         }
1098                         continue;
1099                 }
1100
1101                 r = list_dependencies_print(*c, level, branches, c[1] == NULL);
1102                 if (r < 0)
1103                         return r;
1104
1105                 if (arg_all || unit_name_to_type(*c) == UNIT_TARGET) {
1106                        r = list_dependencies_one(bus, *c, level + 1, &u, (branches << 1) | (c[1] == NULL ? 0 : 1));
1107                        if(r < 0)
1108                                return r;
1109                 }
1110         }
1111
1112         if (arg_plain) {
1113                 strv_free(*units);
1114                 *units = u;
1115                 u = NULL;
1116         }
1117
1118         return 0;
1119 }
1120
1121 static int list_dependencies(sd_bus *bus, char **args) {
1122         _cleanup_strv_free_ char **units = NULL;
1123         _cleanup_free_ char *unit = NULL;
1124         const char *u;
1125
1126         assert(bus);
1127
1128         if (args[1]) {
1129                 unit = unit_name_mangle(args[1]);
1130                 if (!unit)
1131                         return log_oom();
1132                 u = unit;
1133         } else
1134                 u = SPECIAL_DEFAULT_TARGET;
1135
1136         pager_open_if_enabled();
1137
1138         puts(u);
1139
1140         return list_dependencies_one(bus, u, 0, &units, 0);
1141 }
1142
1143 static int get_default(sd_bus *bus, char **args) {
1144         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
1145         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1146         _cleanup_free_ char *_path = NULL;
1147         const char *path;
1148         int r;
1149
1150         if (!bus || avoid_bus()) {
1151                 r = unit_file_get_default(arg_scope, arg_root, &_path);
1152                 if (r < 0) {
1153                         log_error("Failed to get default target: %s", strerror(-r));
1154                         return r;
1155                 }
1156                 path = _path;
1157
1158         } else {
1159                 r = sd_bus_call_method(
1160                                 bus,
1161                                 "org.freedesktop.systemd1",
1162                                 "/org/freedesktop/systemd1",
1163                                 "org.freedesktop.systemd1.Manager",
1164                                 "GetDefaultTarget",
1165                                 &error,
1166                                 &reply,
1167                                 NULL);
1168                 if (r < 0) {
1169                         log_error("Failed to get default target: %s", bus_error_message(&error, -r));
1170                         return r;
1171                 }
1172
1173                 r = sd_bus_message_read(reply, "s", &path);
1174                 if (r < 0)
1175                         return bus_log_parse_error(r);
1176         }
1177
1178         if (path)
1179                 printf("%s\n", path);
1180
1181         return 0;
1182 }
1183
1184 struct job_info {
1185         uint32_t id;
1186         const char *name, *type, *state;
1187 };
1188
1189 static void output_jobs_list(const struct job_info* jobs, unsigned n) {
1190         unsigned id_len, unit_len, type_len, state_len;
1191         const struct job_info *j;
1192         const char *on, *off;
1193         bool shorten = false;
1194
1195         assert(n == 0 || jobs);
1196
1197         if (n == 0) {
1198                 on = ansi_highlight_green();
1199                 off = ansi_highlight_off();
1200
1201                 printf("%sNo jobs running.%s\n", on, off);
1202                 return;
1203         }
1204
1205         pager_open_if_enabled();
1206
1207         id_len = unit_len = type_len = state_len = 0;
1208         for (j = jobs; j < jobs + n; j++) {
1209                 uint32_t id = j->id;
1210                 assert(j->name && j->type && j->state);
1211
1212                 id_len = MAX(id_len, DECIMAL_STR_WIDTH(id));
1213                 unit_len = MAX(unit_len, strlen(j->name));
1214                 type_len = MAX(type_len, strlen(j->type));
1215                 state_len = MAX(state_len, strlen(j->state));
1216         }
1217
1218         if (!arg_full && id_len + 1 + unit_len + type_len + 1 + state_len > columns()) {
1219                 unit_len = MAX(33u, columns() - id_len - type_len - state_len - 3);
1220                 shorten = true;
1221         }
1222
1223         printf("%*s %-*s %-*s %-*s\n",
1224                id_len, "JOB",
1225                unit_len, "UNIT",
1226                type_len, "TYPE",
1227                state_len, "STATE");
1228
1229         for (j = jobs; j < jobs + n; j++) {
1230                 _cleanup_free_ char *e = NULL;
1231
1232                 if (streq(j->state, "running")) {
1233                         on = ansi_highlight();
1234                         off = ansi_highlight_off();
1235                 } else
1236                         on = off = "";
1237
1238                 e = shorten ? ellipsize(j->name, unit_len, 33) : NULL;
1239                 printf("%*u %s%-*s%s %-*s %s%-*s%s\n",
1240                        id_len, j->id,
1241                        on, unit_len, e ? e : j->name, off,
1242                        type_len, j->type,
1243                        on, state_len, j->state, off);
1244         }
1245
1246         on = ansi_highlight();
1247         off = ansi_highlight_off();
1248
1249         printf("\n%s%u jobs listed%s.\n", on, n, off);
1250 }
1251
1252 static int list_jobs(sd_bus *bus, char **args) {
1253         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1254         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
1255         const char *name, *type, *state, *job_path, *unit_path;
1256         _cleanup_free_ struct job_info *jobs = NULL;
1257         size_t size = 0;
1258         unsigned c = 0;
1259         uint32_t id;
1260         int r;
1261
1262         r = sd_bus_call_method(
1263                         bus,
1264                         "org.freedesktop.systemd1",
1265                         "/org/freedesktop/systemd1",
1266                         "org.freedesktop.systemd1.Manager",
1267                         "ListJobs",
1268                         &error,
1269                         &reply,
1270                         NULL);
1271         if (r < 0) {
1272                 log_error("Failed to list jobs: %s", bus_error_message(&error, r));
1273                 return r;
1274         }
1275
1276         r = sd_bus_message_enter_container(reply, 'a', "(usssoo)");
1277         if (r < 0)
1278                 return bus_log_parse_error(r);
1279
1280         while ((r = sd_bus_message_read(reply, "(usssoo)", &id, &name, &type, &state, &job_path, &unit_path)) > 0) {
1281
1282                 if (!GREEDY_REALLOC(jobs, size, c + 1))
1283                         return log_oom();
1284
1285                 jobs[c++] = (struct job_info) {
1286                         id,
1287                         name,
1288                         type,
1289                         state
1290                 };
1291         }
1292         if (r < 0)
1293                 return bus_log_parse_error(r);
1294
1295         r = sd_bus_message_exit_container(reply);
1296         if (r < 0)
1297                 return bus_log_parse_error(r);
1298
1299         output_jobs_list(jobs, c);
1300         return r;
1301 }
1302
1303 static int cancel_job(sd_bus *bus, char **args) {
1304         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1305         char **name;
1306
1307         assert(args);
1308
1309         if (strv_length(args) <= 1)
1310                 return daemon_reload(bus, args);
1311
1312         STRV_FOREACH(name, args+1) {
1313                 uint32_t id;
1314                 int r;
1315
1316                 r = safe_atou32(*name, &id);
1317                 if (r < 0) {
1318                         log_error("Failed to parse job id \"%s\": %s", *name, strerror(-r));
1319                         return r;
1320                 }
1321
1322                 r = sd_bus_call_method(
1323                                 bus,
1324                                 "org.freedesktop.systemd1",
1325                                 "/org/freedesktop/systemd1",
1326                                 "org.freedesktop.systemd1.Manager",
1327                                 "CancelJob",
1328                                 &error,
1329                                 NULL,
1330                                 "u", id);
1331                 if (r < 0) {
1332                         log_error("Failed to cancel job %u: %s", (unsigned) id, bus_error_message(&error, r));
1333                         return r;
1334                 }
1335         }
1336
1337         return 0;
1338 }
1339
1340 static int need_daemon_reload(sd_bus *bus, const char *unit) {
1341         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
1342         _cleanup_free_ char *n = NULL;
1343         const char *path;
1344         int b, r;
1345
1346         /* We ignore all errors here, since this is used to show a
1347          * warning only */
1348
1349         n = unit_name_mangle(unit);
1350         if (!n)
1351                 return -ENOMEM;
1352
1353         /* We don't use unit_dbus_path_from_name() directly since we
1354          * don't want to load the unit if it isn't loaded. */
1355
1356         r = sd_bus_call_method(
1357                         bus,
1358                         "org.freedesktop.systemd1",
1359                         "/org/freedesktop/systemd1",
1360                         "org.freedesktop.systemd1.Manager",
1361                         "GetUnit",
1362                         NULL,
1363                         &reply,
1364                         "s", n);
1365         if (r < 0)
1366                 return r;
1367
1368         r = sd_bus_message_read(reply, "o", &path);
1369         if (r < 0)
1370                 return r;
1371
1372         r = sd_bus_get_property_trivial(
1373                         bus,
1374                         "org.freedesktop.systemd1",
1375                         path,
1376                         "org.freedesktop.systemd1.Unit",
1377                         "NeedDaemonReload",
1378                         NULL,
1379                         'b', &b);
1380         if (r < 0)
1381                 return r;
1382
1383         return b;
1384 }
1385
1386 typedef struct WaitData {
1387         Set *set;
1388
1389         char *name;
1390         char *result;
1391 } WaitData;
1392
1393 static int wait_filter(sd_bus *bus, sd_bus_message *m, void *data) {
1394         WaitData *d = data;
1395
1396         assert(bus);
1397         assert(m);
1398         assert(d);
1399
1400         log_debug("Got D-Bus request: %s.%s() on %s",
1401                   sd_bus_message_get_interface(m),
1402                   sd_bus_message_get_member(m),
1403                   sd_bus_message_get_path(m));
1404
1405         if (sd_bus_message_is_signal(m, "org.freedesktop.DBus.Local", "Disconnected")) {
1406                 log_error("Warning! D-Bus connection terminated.");
1407                 sd_bus_close(bus);
1408         } else if (sd_bus_message_is_signal(m, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1409                 uint32_t id;
1410                 const char *path, *result, *unit;
1411                 char *ret;
1412                 int r;
1413
1414                 r = sd_bus_message_read(m, "uoss", &id, &path, &unit, &result);
1415                 if (r >= 0) {
1416                         ret = set_remove(d->set, (char*) path);
1417                         if (!ret)
1418                                 return 0;
1419
1420                         free(ret);
1421
1422                         if (!isempty(result))
1423                                 d->result = strdup(result);
1424
1425                         if (!isempty(unit))
1426                                 d->name = strdup(unit);
1427
1428                         return 0;
1429                 }
1430 #ifndef NOLEGACY
1431                 r = sd_bus_message_read(m, "uos", &id, &path, &result);
1432                 if (r >= 0) {
1433                         ret = set_remove(d->set, (char*) path);
1434                         if (!ret)
1435                                 return 0;
1436
1437                         free(ret);
1438
1439                         if (*result)
1440                                 d->result = strdup(result);
1441
1442                         return 0;
1443                 }
1444 #endif
1445
1446                 log_error("Failed to parse message.");
1447         }
1448
1449         return 0;
1450 }
1451
1452 static int enable_wait_for_jobs(sd_bus *bus) {
1453         int r;
1454
1455         assert(bus);
1456
1457         r = sd_bus_add_match(
1458                         bus,
1459                         "type='signal',"
1460                         "sender='org.freedesktop.systemd1',"
1461                         "interface='org.freedesktop.systemd1.Manager',"
1462                         "member='JobRemoved',"
1463                         "path='/org/freedesktop/systemd1'",
1464                         NULL, NULL);
1465         if (r < 0) {
1466                 log_error("Failed to add match");
1467                 return -EIO;
1468         }
1469
1470         /* This is slightly dirty, since we don't undo the match registrations. */
1471         return 0;
1472 }
1473
1474 static int wait_for_jobs(sd_bus *bus, Set *s) {
1475         WaitData d = { .set = s };
1476         int r;
1477
1478         assert(bus);
1479         assert(s);
1480
1481         r = sd_bus_add_filter(bus, wait_filter, &d);
1482         if (r < 0)
1483                 return log_oom();
1484
1485         while (!set_isempty(s)) {
1486                 for(;;) {
1487                         r = sd_bus_process(bus, NULL);
1488                         if (r < 0)
1489                                 return r;
1490                         if (r > 0)
1491                                 break;
1492                         r = sd_bus_wait(bus, (uint64_t) -1);
1493                         if (r < 0)
1494                                 return r;
1495                 }
1496
1497                 if (!d.result)
1498                         goto free_name;
1499
1500                 if (!arg_quiet) {
1501                         if (streq(d.result, "timeout"))
1502                                 log_error("Job for %s timed out.", strna(d.name));
1503                         else if (streq(d.result, "canceled"))
1504                                 log_error("Job for %s canceled.", strna(d.name));
1505                         else if (streq(d.result, "dependency"))
1506                                 log_error("A dependency job for %s failed. See 'journalctl -xn' for details.", strna(d.name));
1507                         else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
1508                                 log_error("Job for %s failed. See 'systemctl status %s' and 'journalctl -xn' for details.", strna(d.name), strna(d.name));
1509                 }
1510
1511                 if (streq_ptr(d.result, "timeout"))
1512                         r = -ETIME;
1513                 else if (streq_ptr(d.result, "canceled"))
1514                         r = -ECANCELED;
1515                 else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
1516                         r = -EIO;
1517
1518                 free(d.result);
1519                 d.result = NULL;
1520
1521         free_name:
1522                 free(d.name);
1523                 d.name = NULL;
1524         }
1525
1526         return sd_bus_remove_filter(bus, wait_filter, &d);
1527 }
1528
1529 static int check_one_unit(sd_bus *bus, const char *name, const char *good_states, bool quiet) {
1530         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
1531         _cleanup_free_ char *n = NULL, *state = NULL;
1532         const char *path;
1533         int r;
1534
1535         assert(name);
1536
1537         n = unit_name_mangle(name);
1538         if (!n)
1539                 return log_oom();
1540
1541         /* We don't use unit_dbus_path_from_name() directly since we
1542          * don't want to load the unit if it isn't loaded. */
1543
1544         r = sd_bus_call_method(
1545                         bus,
1546                         "org.freedesktop.systemd1",
1547                         "/org/freedesktop/systemd1",
1548                         "org.freedesktop.systemd1.Manager",
1549                         "GetUnit",
1550                         NULL,
1551                         &reply,
1552                         "s", n);
1553         if (r < 0) {
1554                 if (!quiet)
1555                         puts("unknown");
1556                 return 0;
1557         }
1558
1559         r = sd_bus_message_read(reply, "o", &path);
1560         if (r < 0)
1561                 return bus_log_parse_error(r);
1562
1563         r = sd_bus_get_property_string(
1564                         bus,
1565                         "org.freedesktop.systemd1",
1566                         path,
1567                         "org.freedesktop.systemd1.Unit",
1568                         "ActiveState",
1569                         NULL,
1570                         &state);
1571         if (r < 0) {
1572                 if (!quiet)
1573                         puts("unknown");
1574                 return 0;
1575         }
1576
1577         if (!quiet)
1578                 puts(state);
1579
1580         return nulstr_contains(good_states, state);
1581 }
1582
1583 static int check_triggering_units(
1584                 sd_bus *bus,
1585                 const char *name) {
1586
1587         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1588         _cleanup_free_ char *path = NULL, *n = NULL, *state = NULL;
1589         _cleanup_strv_free_ char **triggered_by = NULL;
1590         bool print_warning_label = true;
1591         char **i;
1592         int r;
1593
1594         n = unit_name_mangle(name);
1595         if (!n)
1596                 return log_oom();
1597
1598         path = unit_dbus_path_from_name(n);
1599         if (!path)
1600                 return log_oom();
1601
1602         r = sd_bus_get_property_string(
1603                         bus,
1604                         "org.freedesktop.systemd1",
1605                         path,
1606                         "org.freedesktop.systemd1.Unit",
1607                         "LoadState",
1608                         &error,
1609                         &state);
1610         if (r < 0) {
1611                 log_error("Failed to get load state of %s: %s", n, bus_error_message(&error, r));
1612                 return r;
1613         }
1614
1615         if (streq(state, "masked"))
1616                 return 0;
1617
1618         r = sd_bus_get_property_strv(
1619                         bus,
1620                         "org.freedesktop.systemd1",
1621                         path,
1622                         "org.freedesktop.systemd1.Unit",
1623                         "TriggeredBy",
1624                         &error,
1625                         &triggered_by);
1626         if (r < 0) {
1627                 log_error("Failed to get triggered by array of %s: %s", n, bus_error_message(&error, r));
1628                 return r;
1629         }
1630
1631         STRV_FOREACH(i, triggered_by) {
1632                 r = check_one_unit(bus, *i, "active\0reloading\0", true);
1633                 if (r < 0) {
1634                         log_error("Failed to check unit: %s", strerror(-r));
1635                         return r;
1636                 }
1637
1638                 if (r == 0)
1639                         continue;
1640
1641                 if (print_warning_label) {
1642                         log_warning("Warning: Stopping %s, but it can still be activated by:", n);
1643                         print_warning_label = false;
1644                 }
1645
1646                 log_warning("  %s", *i);
1647         }
1648
1649         return 0;
1650 }
1651
1652 static int start_unit_one(
1653                 sd_bus *bus,
1654                 const char *method,
1655                 const char *name,
1656                 const char *mode,
1657                 sd_bus_error *error,
1658                 Set *s) {
1659
1660         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
1661         _cleanup_free_ char *n;
1662         const char *path;
1663         int r;
1664
1665         assert(method);
1666         assert(name);
1667         assert(mode);
1668         assert(error);
1669
1670         n = unit_name_mangle(name);
1671         if (!n)
1672                 return log_oom();
1673
1674         r = sd_bus_call_method(
1675                         bus,
1676                         "org.freedesktop.systemd1",
1677                         "/org/freedesktop/systemd1",
1678                         "org.freedesktop.systemd1.Manager",
1679                         method,
1680                         error,
1681                         &reply,
1682                         "ss", n, mode);
1683         if (r < 0) {
1684                 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
1685                         /* There's always a fallback possible for
1686                          * legacy actions. */
1687                         return -EADDRNOTAVAIL;
1688
1689                 log_error("Failed to start %s: %s", name, bus_error_message(error, r));
1690                 return r;
1691         }
1692
1693         r = sd_bus_message_read(reply, "o", &path);
1694         if (r < 0)
1695                 return bus_log_parse_error(r);
1696
1697         if (need_daemon_reload(bus, n) > 0)
1698                 log_warning("Warning: Unit file of %s changed on disk, 'systemctl%s daemon-reload' recommended.",
1699                             n, arg_scope == UNIT_FILE_SYSTEM ? "" : " --user");
1700
1701         if (s) {
1702                 char *p;
1703
1704                 p = strdup(path);
1705                 if (!p)
1706                         return log_oom();
1707
1708                 r = set_consume(s, p);
1709                 if (r < 0)
1710                         return log_oom();
1711         }
1712
1713         return 0;
1714 }
1715
1716 static const struct {
1717         const char *target;
1718         const char *verb;
1719         const char *mode;
1720 } action_table[_ACTION_MAX] = {
1721         [ACTION_HALT]         = { SPECIAL_HALT_TARGET,         "halt",         "replace-irreversibly" },
1722         [ACTION_POWEROFF]     = { SPECIAL_POWEROFF_TARGET,     "poweroff",     "replace-irreversibly" },
1723         [ACTION_REBOOT]       = { SPECIAL_REBOOT_TARGET,       "reboot",       "replace-irreversibly" },
1724         [ACTION_KEXEC]        = { SPECIAL_KEXEC_TARGET,        "kexec",        "replace-irreversibly" },
1725         [ACTION_RUNLEVEL2]    = { SPECIAL_RUNLEVEL2_TARGET,    NULL,           "isolate" },
1726         [ACTION_RUNLEVEL3]    = { SPECIAL_RUNLEVEL3_TARGET,    NULL,           "isolate" },
1727         [ACTION_RUNLEVEL4]    = { SPECIAL_RUNLEVEL4_TARGET,    NULL,           "isolate" },
1728         [ACTION_RUNLEVEL5]    = { SPECIAL_RUNLEVEL5_TARGET,    NULL,           "isolate" },
1729         [ACTION_RESCUE]       = { SPECIAL_RESCUE_TARGET,       "rescue",       "isolate" },
1730         [ACTION_EMERGENCY]    = { SPECIAL_EMERGENCY_TARGET,    "emergency",    "isolate" },
1731         [ACTION_DEFAULT]      = { SPECIAL_DEFAULT_TARGET,      "default",      "isolate" },
1732         [ACTION_EXIT]         = { SPECIAL_EXIT_TARGET,         "exit",         "replace-irreversibly" },
1733         [ACTION_SUSPEND]      = { SPECIAL_SUSPEND_TARGET,      "suspend",      "replace-irreversibly" },
1734         [ACTION_HIBERNATE]    = { SPECIAL_HIBERNATE_TARGET,    "hibernate",    "replace-irreversibly" },
1735         [ACTION_HYBRID_SLEEP] = { SPECIAL_HYBRID_SLEEP_TARGET, "hybrid-sleep", "replace-irreversibly" },
1736 };
1737
1738 static enum action verb_to_action(const char *verb) {
1739         enum action i;
1740
1741         for (i = _ACTION_INVALID; i < _ACTION_MAX; i++)
1742                 if (streq_ptr(action_table[i].verb, verb))
1743                         return i;
1744
1745         return _ACTION_INVALID;
1746 }
1747
1748 static int start_unit(sd_bus *bus, char **args) {
1749         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1750         _cleanup_set_free_free_ Set *s = NULL;
1751         const char *method, *mode, *one_name;
1752         char **name;
1753         int r;
1754
1755         assert(bus);
1756
1757         ask_password_agent_open_if_enabled();
1758
1759         if (arg_action == ACTION_SYSTEMCTL) {
1760                 enum action action;
1761                 method =
1762                         streq(args[0], "stop") ||
1763                         streq(args[0], "condstop")              ? "StopUnit" :
1764                         streq(args[0], "reload")                ? "ReloadUnit" :
1765                         streq(args[0], "restart")               ? "RestartUnit" :
1766
1767                         streq(args[0], "try-restart")           ||
1768                         streq(args[0], "condrestart")           ? "TryRestartUnit" :
1769
1770                         streq(args[0], "reload-or-restart")     ? "ReloadOrRestartUnit" :
1771
1772                         streq(args[0], "reload-or-try-restart") ||
1773                         streq(args[0], "condreload")            ||
1774                         streq(args[0], "force-reload")          ? "ReloadOrTryRestartUnit" :
1775                                                                   "StartUnit";
1776                 action = verb_to_action(args[0]);
1777
1778                 mode = streq(args[0], "isolate") ? "isolate" :
1779                        action_table[action].mode ?: arg_job_mode;
1780
1781                 one_name = action_table[action].target;
1782         } else {
1783                 assert(arg_action < ELEMENTSOF(action_table));
1784                 assert(action_table[arg_action].target);
1785
1786                 method = "StartUnit";
1787
1788                 mode = action_table[arg_action].mode;
1789                 one_name = action_table[arg_action].target;
1790         }
1791
1792         if (!arg_no_block) {
1793                 r = enable_wait_for_jobs(bus);
1794                 if (r < 0) {
1795                         log_error("Could not watch jobs: %s", strerror(-r));
1796                         return r;
1797                 }
1798
1799                 s = set_new(string_hash_func, string_compare_func);
1800                 if (!s)
1801                         return log_oom();
1802         }
1803
1804         if (one_name) {
1805                 r = start_unit_one(bus, method, one_name, mode, &error, s);
1806                 if (r < 0)
1807                         r = translate_bus_error_to_exit_status(r, &error);
1808         } else {
1809                 r = 0;
1810
1811                 STRV_FOREACH(name, args+1) {
1812                         int q;
1813
1814                         q = start_unit_one(bus, method, *name, mode, &error, s);
1815                         if (q < 0) {
1816                                 r = translate_bus_error_to_exit_status(r, &error);
1817                                 sd_bus_error_free(&error);
1818                         }
1819                 }
1820         }
1821
1822         if (!arg_no_block) {
1823                 int q;
1824
1825                 q = wait_for_jobs(bus, s);
1826                 if (q < 0)
1827                         return q;
1828
1829                 /* When stopping units, warn if they can still be triggered by
1830                  * another active unit (socket, path, timer) */
1831                 if (!arg_quiet && streq(method, "StopUnit")) {
1832                         if (one_name)
1833                                 check_triggering_units(bus, one_name);
1834                         else
1835                                 STRV_FOREACH(name, args+1)
1836                                         check_triggering_units(bus, *name);
1837                 }
1838         }
1839
1840         return r;
1841 }
1842
1843 /* Ask systemd-logind, which might grant access to unprivileged users
1844  * through PolicyKit */
1845 static int reboot_with_logind(sd_bus *bus, enum action a) {
1846 #ifdef HAVE_LOGIND
1847         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1848         const char *method;
1849         int r;
1850
1851         if (!bus)
1852                 return -EIO;
1853
1854         polkit_agent_open_if_enabled();
1855
1856         switch (a) {
1857
1858         case ACTION_REBOOT:
1859                 method = "Reboot";
1860                 break;
1861
1862         case ACTION_POWEROFF:
1863                 method = "PowerOff";
1864                 break;
1865
1866         case ACTION_SUSPEND:
1867                 method = "Suspend";
1868                 break;
1869
1870         case ACTION_HIBERNATE:
1871                 method = "Hibernate";
1872                 break;
1873
1874         case ACTION_HYBRID_SLEEP:
1875                 method = "HybridSleep";
1876                 break;
1877
1878         default:
1879                 return -EINVAL;
1880         }
1881
1882         r = sd_bus_call_method(
1883                         bus,
1884                         "org.freedesktop.login1",
1885                         "/org/freedesktop/login1",
1886                         "org.freedesktop.login1.Manager",
1887                         method,
1888                         &error,
1889                         NULL,
1890                         "b", true);
1891         if (r < 0)
1892                 log_error("Failed to execute operation: %s", bus_error_message(&error, r));
1893
1894         return r;
1895 #else
1896         return -ENOSYS;
1897 #endif
1898 }
1899
1900 static int check_inhibitors(sd_bus *bus, enum action a) {
1901 #ifdef HAVE_LOGIND
1902         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1903         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
1904         _cleanup_strv_free_ char **sessions = NULL;
1905         const char *what, *who, *why, *mode;
1906         uint32_t uid, pid;
1907         unsigned c = 0;
1908         char **s;
1909         int r;
1910
1911         if (!bus)
1912                 return 0;
1913
1914         if (arg_ignore_inhibitors || arg_force > 0)
1915                 return 0;
1916
1917         if (arg_when > 0)
1918                 return 0;
1919
1920         if (geteuid() == 0)
1921                 return 0;
1922
1923         if (!on_tty())
1924                 return 0;
1925
1926         r = sd_bus_call_method(
1927                         bus,
1928                         "org.freedesktop.login1",
1929                         "/org/freedesktop/login1",
1930                         "org.freedesktop.login1.Manager",
1931                         "ListInhibitors",
1932                         NULL,
1933                         &reply,
1934                         NULL);
1935         if (r < 0)
1936                 /* If logind is not around, then there are no inhibitors... */
1937                 return 0;
1938
1939         r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssuu)");
1940         if (r < 0)
1941                 return bus_log_parse_error(r);
1942
1943         while ((r = sd_bus_message_read(reply, "(ssssuu)", &what, &who, &why, &mode, &uid, &pid)) > 0) {
1944                 _cleanup_free_ char *comm = NULL, *user = NULL;
1945                 _cleanup_strv_free_ char **sv = NULL;
1946
1947                 if (!streq(mode, "block"))
1948                         continue;
1949
1950                 sv = strv_split(what, ":");
1951                 if (!sv)
1952                         return log_oom();
1953
1954                 if (!strv_contains(sv,
1955                                   a == ACTION_HALT ||
1956                                   a == ACTION_POWEROFF ||
1957                                   a == ACTION_REBOOT ||
1958                                   a == ACTION_KEXEC ? "shutdown" : "sleep"))
1959                         continue;
1960
1961                 get_process_comm(pid, &comm);
1962                 user = uid_to_name(uid);
1963
1964                 log_warning("Operation inhibited by \"%s\" (PID %lu \"%s\", user %s), reason is \"%s\".",
1965                             who, (unsigned long) pid, strna(comm), strna(user), why);
1966
1967                 c++;
1968         }
1969         if (r < 0)
1970                 return bus_log_parse_error(r);
1971
1972         r = sd_bus_message_exit_container(reply);
1973         if (r < 0)
1974                 return bus_log_parse_error(r);
1975
1976         /* Check for current sessions */
1977         sd_get_sessions(&sessions);
1978         STRV_FOREACH(s, sessions) {
1979                 _cleanup_free_ char *type = NULL, *tty = NULL, *seat = NULL, *user = NULL, *service = NULL, *class = NULL;
1980
1981                 if (sd_session_get_uid(*s, &uid) < 0 || uid == getuid())
1982                         continue;
1983
1984                 if (sd_session_get_class(*s, &class) < 0 || !streq(class, "user"))
1985                         continue;
1986
1987                 if (sd_session_get_type(*s, &type) < 0 || (!streq(type, "x11") && !streq(type, "tty")))
1988                         continue;
1989
1990                 sd_session_get_tty(*s, &tty);
1991                 sd_session_get_seat(*s, &seat);
1992                 sd_session_get_service(*s, &service);
1993                 user = uid_to_name(uid);
1994
1995                 log_warning("User %s is logged in on %s.", strna(user), isempty(tty) ? (isempty(seat) ? strna(service) : seat) : tty);
1996                 c++;
1997         }
1998
1999         if (c <= 0)
2000                 return 0;
2001
2002         log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'systemctl %s -i'.",
2003                   action_table[a].verb);
2004
2005         return -EPERM;
2006 #else
2007         return 0;
2008 #endif
2009 }
2010
2011 static int start_special(sd_bus *bus, char **args) {
2012         enum action a;
2013         int r;
2014
2015         assert(args);
2016
2017         a = verb_to_action(args[0]);
2018
2019         r = check_inhibitors(bus, a);
2020         if (r < 0)
2021                 return r;
2022
2023         if (arg_force >= 2 && geteuid() != 0) {
2024                 log_error("Must be root.");
2025                 return -EPERM;
2026         }
2027
2028         if (arg_force >= 2 &&
2029             (a == ACTION_HALT ||
2030              a == ACTION_POWEROFF ||
2031              a == ACTION_REBOOT))
2032                 halt_now(a);
2033
2034         if (arg_force >= 1 &&
2035             (a == ACTION_HALT ||
2036              a == ACTION_POWEROFF ||
2037              a == ACTION_REBOOT ||
2038              a == ACTION_KEXEC ||
2039              a == ACTION_EXIT))
2040                 return daemon_reload(bus, args);
2041
2042         /* first try logind, to allow authentication with polkit */
2043         if (geteuid() != 0 &&
2044             (a == ACTION_POWEROFF ||
2045              a == ACTION_REBOOT ||
2046              a == ACTION_SUSPEND ||
2047              a == ACTION_HIBERNATE ||
2048              a == ACTION_HYBRID_SLEEP)) {
2049                 r = reboot_with_logind(bus, a);
2050                 if (r >= 0)
2051                         return r;
2052         }
2053
2054         r = start_unit(bus, args);
2055         if (r == EXIT_SUCCESS)
2056                 warn_wall(a);
2057
2058         return r;
2059 }
2060
2061 static int check_unit_active(sd_bus *bus, char **args) {
2062         char **name;
2063         int r = 3; /* According to LSB: "program is not running" */
2064
2065         assert(bus);
2066         assert(args);
2067
2068         STRV_FOREACH(name, args+1) {
2069                 int state;
2070
2071                 state = check_one_unit(bus, *name, "active\0reloading\0", arg_quiet);
2072                 if (state < 0)
2073                         return state;
2074                 if (state > 0)
2075                         r = 0;
2076         }
2077
2078         return r;
2079 }
2080
2081 static int check_unit_failed(sd_bus *bus, char **args) {
2082         char **name;
2083         int r = 1;
2084
2085         assert(bus);
2086         assert(args);
2087
2088         STRV_FOREACH(name, args+1) {
2089                 int state;
2090
2091                 state = check_one_unit(bus, *name, "failed\0", arg_quiet);
2092                 if (state < 0)
2093                         return state;
2094                 if (state > 0)
2095                         r = 0;
2096         }
2097
2098         return r;
2099 }
2100
2101 static int kill_unit(sd_bus *bus, char **args) {
2102         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
2103         char **name;
2104         int r = 0;
2105
2106         assert(bus);
2107         assert(args);
2108
2109         if (!arg_kill_who)
2110                 arg_kill_who = "all";
2111
2112         STRV_FOREACH(name, args+1) {
2113                 _cleanup_free_ char *n = NULL;
2114
2115                 n = unit_name_mangle(*name);
2116                 if (!n)
2117                         return log_oom();
2118
2119                 r = sd_bus_call_method(
2120                                 bus,
2121                                 "org.freedesktop.systemd1",
2122                                 "/org/freedesktop/systemd1",
2123                                 "org.freedesktop.systemd1.Manager",
2124                                 "KillUnit",
2125                                 &error,
2126                                 NULL,
2127                                 "ssi", n, arg_kill_who, arg_signal);
2128                 if (r < 0) {
2129                         log_error("Failed to kill unit %s: %s", n, bus_error_message(&error, r));
2130                         return r;
2131                 }
2132         }
2133
2134         return 0;
2135 }
2136
2137 typedef struct ExecStatusInfo {
2138         char *name;
2139
2140         char *path;
2141         char **argv;
2142
2143         bool ignore;
2144
2145         usec_t start_timestamp;
2146         usec_t exit_timestamp;
2147         pid_t pid;
2148         int code;
2149         int status;
2150
2151         LIST_FIELDS(struct ExecStatusInfo, exec);
2152 } ExecStatusInfo;
2153
2154 static void exec_status_info_free(ExecStatusInfo *i) {
2155         assert(i);
2156
2157         free(i->name);
2158         free(i->path);
2159         strv_free(i->argv);
2160         free(i);
2161 }
2162
2163 static int exec_status_info_deserialize(sd_bus_message *m, ExecStatusInfo *i) {
2164         uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
2165         const char *path;
2166         uint32_t pid;
2167         int32_t code, status;
2168         int ignore, r;
2169
2170         assert(m);
2171         assert(i);
2172
2173         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_STRUCT, "sasbttttuii");
2174         if (r < 0)
2175                 return bus_log_parse_error(r);
2176         else if (r == 0)
2177                 return 0;
2178
2179         r = sd_bus_message_read(m, "s", &path);
2180         if (r < 0)
2181                 return bus_log_parse_error(r);
2182
2183         i->path = strdup(path);
2184         if (!i->path)
2185                 return log_oom();
2186
2187         r = sd_bus_message_read_strv(m, &i->argv);
2188         if (r < 0)
2189                 return bus_log_parse_error(r);
2190
2191         r = sd_bus_message_read(m,
2192                                 "bttttuii",
2193                                 &ignore,
2194                                 &start_timestamp, &start_timestamp_monotonic,
2195                                 &exit_timestamp, &exit_timestamp_monotonic,
2196                                 &pid,
2197                                 &code, &status);
2198         if (r < 0)
2199                 return bus_log_parse_error(r);
2200
2201         i->ignore = ignore;
2202         i->start_timestamp = (usec_t) start_timestamp;
2203         i->exit_timestamp = (usec_t) exit_timestamp;
2204         i->pid = (pid_t) pid;
2205         i->code = code;
2206         i->status = status;
2207
2208         r = sd_bus_message_exit_container(m);
2209         if (r < 0)
2210                 return bus_log_parse_error(r);
2211
2212         return 1;
2213 }
2214
2215 typedef struct UnitStatusInfo {
2216         const char *id;
2217         const char *load_state;
2218         const char *active_state;
2219         const char *sub_state;
2220         const char *unit_file_state;
2221
2222         const char *description;
2223         const char *following;
2224
2225         char **documentation;
2226
2227         const char *fragment_path;
2228         const char *source_path;
2229         const char *control_group;
2230
2231         char **dropin_paths;
2232
2233         const char *load_error;
2234         const char *result;
2235
2236         usec_t inactive_exit_timestamp;
2237         usec_t inactive_exit_timestamp_monotonic;
2238         usec_t active_enter_timestamp;
2239         usec_t active_exit_timestamp;
2240         usec_t inactive_enter_timestamp;
2241
2242         bool need_daemon_reload;
2243
2244         /* Service */
2245         pid_t main_pid;
2246         pid_t control_pid;
2247         const char *status_text;
2248         const char *pid_file;
2249         bool running:1;
2250
2251         usec_t start_timestamp;
2252         usec_t exit_timestamp;
2253
2254         int exit_code, exit_status;
2255
2256         usec_t condition_timestamp;
2257         bool condition_result;
2258         bool failed_condition_trigger;
2259         bool failed_condition_negate;
2260         const char *failed_condition;
2261         const char *failed_condition_param;
2262
2263         /* Socket */
2264         unsigned n_accepted;
2265         unsigned n_connections;
2266         bool accept;
2267
2268         /* Pairs of type, path */
2269         char **listen;
2270
2271         /* Device */
2272         const char *sysfs_path;
2273
2274         /* Mount, Automount */
2275         const char *where;
2276
2277         /* Swap */
2278         const char *what;
2279
2280         LIST_HEAD(ExecStatusInfo, exec);
2281 } UnitStatusInfo;
2282
2283 static void print_status_info(
2284                 UnitStatusInfo *i,
2285                 bool *ellipsized) {
2286
2287         ExecStatusInfo *p;
2288         const char *on, *off, *ss;
2289         usec_t timestamp;
2290         char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], *s1;
2291         char since2[FORMAT_TIMESTAMP_MAX], *s2;
2292         const char *path;
2293         int flags =
2294                 arg_all * OUTPUT_SHOW_ALL |
2295                 (!on_tty() || pager_have()) * OUTPUT_FULL_WIDTH |
2296                 on_tty() * OUTPUT_COLOR |
2297                 !arg_quiet * OUTPUT_WARN_CUTOFF |
2298                 arg_full * OUTPUT_FULL_WIDTH;
2299         char **t, **t2;
2300
2301         assert(i);
2302
2303         /* This shows pretty information about a unit. See
2304          * print_property() for a low-level property printer */
2305
2306         printf("%s", strna(i->id));
2307
2308         if (i->description && !streq_ptr(i->id, i->description))
2309                 printf(" - %s", i->description);
2310
2311         printf("\n");
2312
2313         if (i->following)
2314                 printf("   Follow: unit currently follows state of %s\n", i->following);
2315
2316         if (streq_ptr(i->load_state, "error")) {
2317                 on = ansi_highlight_red();
2318                 off = ansi_highlight_off();
2319         } else
2320                 on = off = "";
2321
2322         path = i->source_path ? i->source_path : i->fragment_path;
2323
2324         if (i->load_error)
2325                 printf("   Loaded: %s%s%s (Reason: %s)\n",
2326                        on, strna(i->load_state), off, i->load_error);
2327         else if (path && i->unit_file_state)
2328                 printf("   Loaded: %s%s%s (%s; %s)\n",
2329                        on, strna(i->load_state), off, path, i->unit_file_state);
2330         else if (path)
2331                 printf("   Loaded: %s%s%s (%s)\n",
2332                        on, strna(i->load_state), off, path);
2333         else
2334                 printf("   Loaded: %s%s%s\n",
2335                        on, strna(i->load_state), off);
2336
2337         if (!strv_isempty(i->dropin_paths)) {
2338                 _cleanup_free_ char *dir = NULL;
2339                 bool last = false;
2340                 char ** dropin;
2341
2342                 STRV_FOREACH(dropin, i->dropin_paths) {
2343                         if (! dir || last) {
2344                                 printf(dir ? "        " : "  Drop-In: ");
2345
2346                                 free(dir);
2347                                 dir = NULL;
2348
2349                                 if (path_get_parent(*dropin, &dir) < 0) {
2350                                         log_oom();
2351                                         return;
2352                                 }
2353
2354                                 printf("%s\n           %s", dir,
2355                                        draw_special_char(DRAW_TREE_RIGHT));
2356                         }
2357
2358                         last = ! (*(dropin + 1) && startswith(*(dropin + 1), dir));
2359
2360                         printf("%s%s", path_get_file_name(*dropin), last ? "\n" : ", ");
2361                 }
2362         }
2363
2364         ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
2365
2366         if (streq_ptr(i->active_state, "failed")) {
2367                 on = ansi_highlight_red();
2368                 off = ansi_highlight_off();
2369         } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
2370                 on = ansi_highlight_green();
2371                 off = ansi_highlight_off();
2372         } else
2373                 on = off = "";
2374
2375         if (ss)
2376                 printf("   Active: %s%s (%s)%s",
2377                        on, strna(i->active_state), ss, off);
2378         else
2379                 printf("   Active: %s%s%s",
2380                        on, strna(i->active_state), off);
2381
2382         if (!isempty(i->result) && !streq(i->result, "success"))
2383                 printf(" (Result: %s)", i->result);
2384
2385         timestamp = (streq_ptr(i->active_state, "active")      ||
2386                      streq_ptr(i->active_state, "reloading"))   ? i->active_enter_timestamp :
2387                     (streq_ptr(i->active_state, "inactive")    ||
2388                      streq_ptr(i->active_state, "failed"))      ? i->inactive_enter_timestamp :
2389                     streq_ptr(i->active_state, "activating")    ? i->inactive_exit_timestamp :
2390                                                                   i->active_exit_timestamp;
2391
2392         s1 = format_timestamp_relative(since1, sizeof(since1), timestamp);
2393         s2 = format_timestamp(since2, sizeof(since2), timestamp);
2394
2395         if (s1)
2396                 printf(" since %s; %s\n", s2, s1);
2397         else if (s2)
2398                 printf(" since %s\n", s2);
2399         else
2400                 printf("\n");
2401
2402         if (!i->condition_result && i->condition_timestamp > 0) {
2403                 s1 = format_timestamp_relative(since1, sizeof(since1), i->condition_timestamp);
2404                 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
2405
2406                 printf("           start condition failed at %s%s%s\n",
2407                        s2, s1 ? "; " : "", s1 ? s1 : "");
2408                 if (i->failed_condition_trigger)
2409                         printf("           none of the trigger conditions were met\n");
2410                 else if (i->failed_condition)
2411                         printf("           %s=%s%s was not met\n",
2412                                i->failed_condition,
2413                                i->failed_condition_negate ? "!" : "",
2414                                i->failed_condition_param);
2415         }
2416
2417         if (i->sysfs_path)
2418                 printf("   Device: %s\n", i->sysfs_path);
2419         if (i->where)
2420                 printf("    Where: %s\n", i->where);
2421         if (i->what)
2422                 printf("     What: %s\n", i->what);
2423
2424         STRV_FOREACH(t, i->documentation)
2425                 printf(" %*s %s\n", 9, t == i->documentation ? "Docs:" : "", *t);
2426
2427         STRV_FOREACH_PAIR(t, t2, i->listen)
2428                 printf(" %*s %s (%s)\n", 9, t == i->listen ? "Listen:" : "", *t2, *t);
2429
2430         if (i->accept)
2431                 printf(" Accepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
2432
2433         LIST_FOREACH(exec, p, i->exec) {
2434                 _cleanup_free_ char *argv = NULL;
2435                 bool good;
2436
2437                 /* Only show exited processes here */
2438                 if (p->code == 0)
2439                         continue;
2440
2441                 argv = strv_join(p->argv, " ");
2442                 printf("  Process: %u %s=%s ", p->pid, p->name, strna(argv));
2443
2444                 good = is_clean_exit_lsb(p->code, p->status, NULL);
2445                 if (!good) {
2446                         on = ansi_highlight_red();
2447                         off = ansi_highlight_off();
2448                 } else
2449                         on = off = "";
2450
2451                 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
2452
2453                 if (p->code == CLD_EXITED) {
2454                         const char *c;
2455
2456                         printf("status=%i", p->status);
2457
2458                         c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD);
2459                         if (c)
2460                                 printf("/%s", c);
2461
2462                 } else
2463                         printf("signal=%s", signal_to_string(p->status));
2464
2465                 printf(")%s\n", off);
2466
2467                 if (i->main_pid == p->pid &&
2468                     i->start_timestamp == p->start_timestamp &&
2469                     i->exit_timestamp == p->start_timestamp)
2470                         /* Let's not show this twice */
2471                         i->main_pid = 0;
2472
2473                 if (p->pid == i->control_pid)
2474                         i->control_pid = 0;
2475         }
2476
2477         if (i->main_pid > 0 || i->control_pid > 0) {
2478                 if (i->main_pid > 0) {
2479                         printf(" Main PID: %u", (unsigned) i->main_pid);
2480
2481                         if (i->running) {
2482                                 _cleanup_free_ char *comm = NULL;
2483                                 get_process_comm(i->main_pid, &comm);
2484                                 if (comm)
2485                                         printf(" (%s)", comm);
2486                         } else if (i->exit_code > 0) {
2487                                 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2488
2489                                 if (i->exit_code == CLD_EXITED) {
2490                                         const char *c;
2491
2492                                         printf("status=%i", i->exit_status);
2493
2494                                         c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD);
2495                                         if (c)
2496                                                 printf("/%s", c);
2497
2498                                 } else
2499                                         printf("signal=%s", signal_to_string(i->exit_status));
2500                                 printf(")");
2501                         }
2502
2503                         if (i->control_pid > 0)
2504                                 printf(";");
2505                 }
2506
2507                 if (i->control_pid > 0) {
2508                         _cleanup_free_ char *c = NULL;
2509
2510                         printf(" %8s: %u", i->main_pid ? "" : " Control", (unsigned) i->control_pid);
2511
2512                         get_process_comm(i->control_pid, &c);
2513                         if (c)
2514                                 printf(" (%s)", c);
2515                 }
2516
2517                 printf("\n");
2518         }
2519
2520         if (i->status_text)
2521                 printf("   Status: \"%s\"\n", i->status_text);
2522
2523         if (i->control_group &&
2524             (i->main_pid > 0 || i->control_pid > 0 || cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, i->control_group, false) == 0)) {
2525                 unsigned c;
2526
2527                 printf("   CGroup: %s\n", i->control_group);
2528
2529                 if (arg_transport == BUS_TRANSPORT_LOCAL || arg_transport == BUS_TRANSPORT_CONTAINER) {
2530                         unsigned k = 0;
2531                         pid_t extra[2];
2532                         char prefix[] = "           ";
2533
2534                         c = columns();
2535                         if (c > sizeof(prefix) - 1)
2536                                 c -= sizeof(prefix) - 1;
2537                         else
2538                                 c = 0;
2539
2540                         if (i->main_pid > 0)
2541                                 extra[k++] = i->main_pid;
2542
2543                         if (i->control_pid > 0)
2544                                 extra[k++] = i->control_pid;
2545
2546                         show_cgroup_and_extra(SYSTEMD_CGROUP_CONTROLLER, i->control_group, prefix,
2547                                                       c, false, extra, k, flags);
2548                 }
2549         }
2550
2551         if (i->id && arg_transport == BUS_TRANSPORT_LOCAL) {
2552                 printf("\n");
2553                 show_journal_by_unit(stdout,
2554                                      i->id,
2555                                      arg_output,
2556                                      0,
2557                                      i->inactive_exit_timestamp_monotonic,
2558                                      arg_lines,
2559                                      getuid(),
2560                                      flags,
2561                                      arg_scope == UNIT_FILE_SYSTEM,
2562                                      ellipsized);
2563         }
2564
2565         if (i->need_daemon_reload)
2566                 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %sdaemon-reload' recommended.\n",
2567                        ansi_highlight_red(),
2568                        ansi_highlight_off(),
2569                        arg_scope == UNIT_FILE_SYSTEM ? "" : "--user ");
2570 }
2571
2572 static void show_unit_help(UnitStatusInfo *i) {
2573         char **p;
2574
2575         assert(i);
2576
2577         if (!i->documentation) {
2578                 log_info("Documentation for %s not known.", i->id);
2579                 return;
2580         }
2581
2582         STRV_FOREACH(p, i->documentation) {
2583
2584                 if (startswith(*p, "man:")) {
2585                         const char *args[4] = { "man", NULL, NULL, NULL };
2586                         _cleanup_free_ char *page = NULL, *section = NULL;
2587                         char *e = NULL;
2588                         pid_t pid;
2589                         size_t k;
2590
2591                         k = strlen(*p);
2592
2593                         if ((*p)[k-1] == ')')
2594                                 e = strrchr(*p, '(');
2595
2596                         if (e) {
2597                                 page = strndup((*p) + 4, e - *p - 4);
2598                                 section = strndup(e + 1, *p + k - e - 2);
2599                                 if (!page || !section) {
2600                                         log_oom();
2601                                         return;
2602                                 }
2603
2604                                 args[1] = section;
2605                                 args[2] = page;
2606                         } else
2607                                 args[1] = *p + 4;
2608
2609                         pid = fork();
2610                         if (pid < 0) {
2611                                 log_error("Failed to fork: %m");
2612                                 continue;
2613                         }
2614
2615                         if (pid == 0) {
2616                                 /* Child */
2617                                 execvp(args[0], (char**) args);
2618                                 log_error("Failed to execute man: %m");
2619                                 _exit(EXIT_FAILURE);
2620                         }
2621
2622                         wait_for_terminate(pid, NULL);
2623                 } else
2624                         log_info("Can't show: %s", *p);
2625         }
2626 }
2627
2628 static int status_property(const char *name, sd_bus_message *m, UnitStatusInfo *i, const char *contents) {
2629         int r;
2630
2631         assert(name);
2632         assert(m);
2633         assert(i);
2634
2635         switch (contents[0]) {
2636
2637         case SD_BUS_TYPE_STRING: {
2638                 const char *s;
2639
2640                 r = sd_bus_message_read(m, "s", &s);
2641                 if (r < 0)
2642                         return bus_log_parse_error(r);
2643
2644                 if (!isempty(s)) {
2645                         if (streq(name, "Id"))
2646                                 i->id = s;
2647                         else if (streq(name, "LoadState"))
2648                                 i->load_state = s;
2649                         else if (streq(name, "ActiveState"))
2650                                 i->active_state = s;
2651                         else if (streq(name, "SubState"))
2652                                 i->sub_state = s;
2653                         else if (streq(name, "Description"))
2654                                 i->description = s;
2655                         else if (streq(name, "FragmentPath"))
2656                                 i->fragment_path = s;
2657                         else if (streq(name, "SourcePath"))
2658                                 i->source_path = s;
2659 #ifndef NOLEGACY
2660                         else if (streq(name, "DefaultControlGroup")) {
2661                                 const char *e;
2662                                 e = startswith(s, SYSTEMD_CGROUP_CONTROLLER ":");
2663                                 if (e)
2664                                         i->control_group = e;
2665                         }
2666 #endif
2667                         else if (streq(name, "ControlGroup"))
2668                                 i->control_group = s;
2669                         else if (streq(name, "StatusText"))
2670                                 i->status_text = s;
2671                         else if (streq(name, "PIDFile"))
2672                                 i->pid_file = s;
2673                         else if (streq(name, "SysFSPath"))
2674                                 i->sysfs_path = s;
2675                         else if (streq(name, "Where"))
2676                                 i->where = s;
2677                         else if (streq(name, "What"))
2678                                 i->what = s;
2679                         else if (streq(name, "Following"))
2680                                 i->following = s;
2681                         else if (streq(name, "UnitFileState"))
2682                                 i->unit_file_state = s;
2683                         else if (streq(name, "Result"))
2684                                 i->result = s;
2685                 }
2686
2687                 break;
2688         }
2689
2690         case SD_BUS_TYPE_BOOLEAN: {
2691                 int b;
2692
2693                 r = sd_bus_message_read(m, "b", &b);
2694                 if (r < 0)
2695                         return bus_log_parse_error(r);
2696
2697                 if (streq(name, "Accept"))
2698                         i->accept = b;
2699                 else if (streq(name, "NeedDaemonReload"))
2700                         i->need_daemon_reload = b;
2701                 else if (streq(name, "ConditionResult"))
2702                         i->condition_result = b;
2703
2704                 break;
2705         }
2706
2707         case SD_BUS_TYPE_UINT32: {
2708                 uint32_t u;
2709
2710                 r = sd_bus_message_read(m, "u", &u);
2711                 if (r < 0)
2712                         return bus_log_parse_error(r);
2713
2714                 if (streq(name, "MainPID")) {
2715                         if (u > 0) {
2716                                 i->main_pid = (pid_t) u;
2717                                 i->running = true;
2718                         }
2719                 } else if (streq(name, "ControlPID"))
2720                         i->control_pid = (pid_t) u;
2721                 else if (streq(name, "ExecMainPID")) {
2722                         if (u > 0)
2723                                 i->main_pid = (pid_t) u;
2724                 } else if (streq(name, "NAccepted"))
2725                         i->n_accepted = u;
2726                 else if (streq(name, "NConnections"))
2727                         i->n_connections = u;
2728
2729                 break;
2730         }
2731
2732         case SD_BUS_TYPE_INT32: {
2733                 int32_t j;
2734
2735                 r = sd_bus_message_read(m, "i", &j);
2736                 if (r < 0)
2737                         return bus_log_parse_error(r);
2738
2739                 if (streq(name, "ExecMainCode"))
2740                         i->exit_code = (int) j;
2741                 else if (streq(name, "ExecMainStatus"))
2742                         i->exit_status = (int) j;
2743
2744                 break;
2745         }
2746
2747         case SD_BUS_TYPE_UINT64: {
2748                 uint64_t u;
2749
2750                 r = sd_bus_message_read(m, "t", &u);
2751                 if (r < 0)
2752                         return bus_log_parse_error(r);
2753
2754                 if (streq(name, "ExecMainStartTimestamp"))
2755                         i->start_timestamp = (usec_t) u;
2756                 else if (streq(name, "ExecMainExitTimestamp"))
2757                         i->exit_timestamp = (usec_t) u;
2758                 else if (streq(name, "ActiveEnterTimestamp"))
2759                         i->active_enter_timestamp = (usec_t) u;
2760                 else if (streq(name, "InactiveEnterTimestamp"))
2761                         i->inactive_enter_timestamp = (usec_t) u;
2762                 else if (streq(name, "InactiveExitTimestamp"))
2763                         i->inactive_exit_timestamp = (usec_t) u;
2764                 else if (streq(name, "InactiveExitTimestampMonotonic"))
2765                         i->inactive_exit_timestamp_monotonic = (usec_t) u;
2766                 else if (streq(name, "ActiveExitTimestamp"))
2767                         i->active_exit_timestamp = (usec_t) u;
2768                 else if (streq(name, "ConditionTimestamp"))
2769                         i->condition_timestamp = (usec_t) u;
2770
2771                 break;
2772         }
2773
2774         case SD_BUS_TYPE_ARRAY:
2775
2776                 if (contents[1] == SD_BUS_TYPE_STRUCT_BEGIN && startswith(name, "Exec")) {
2777                         _cleanup_free_ ExecStatusInfo *info = NULL;
2778
2779                         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sasbttttuii)");
2780                         if (r < 0)
2781                                 return bus_log_parse_error(r);
2782
2783                         info = new0(ExecStatusInfo, 1);
2784                         if (!info)
2785                                 return log_oom();
2786
2787                         while ((r = exec_status_info_deserialize(m, info)) > 0) {
2788
2789                                 info->name = strdup(name);
2790                                 if (!info->name)
2791                                         log_oom();
2792
2793                                 LIST_PREPEND(exec, i->exec, info);
2794
2795                                 info = new0(ExecStatusInfo, 1);
2796                                 if (!info)
2797                                         log_oom();
2798                         }
2799
2800                         if (r < 0)
2801                                 return bus_log_parse_error(r);
2802
2803                         r = sd_bus_message_exit_container(m);
2804                         if (r < 0)
2805                                 return bus_log_parse_error(r);
2806
2807                         return 0;
2808
2809                 } else if (contents[1] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "Listen")) {
2810                         const char *type, *path;
2811
2812                         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
2813                         if (r < 0)
2814                                 return bus_log_parse_error(r);
2815
2816                         while ((r = sd_bus_message_read(m, "(ss)", &type, &path)) > 0) {
2817
2818                                 r = strv_extend(&i->listen, type);
2819                                 if (r < 0)
2820                                         return r;
2821
2822                                 r = strv_extend(&i->listen, path);
2823                                 if (r < 0)
2824                                         return r;
2825                         }
2826                         if (r < 0)
2827                                 return bus_log_parse_error(r);
2828
2829                         r = sd_bus_message_exit_container(m);
2830                         if (r < 0)
2831                                 return bus_log_parse_error(r);
2832
2833                         return 0;
2834
2835                 } else if (contents[1] == SD_BUS_TYPE_STRING && streq(name, "DropInPaths")) {
2836
2837                         r = sd_bus_message_read_strv(m, &i->dropin_paths);
2838                         if (r < 0)
2839                                 return bus_log_parse_error(r);
2840
2841                 } else if (contents[1] == SD_BUS_TYPE_STRING && streq(name, "Documentation")) {
2842
2843                         r = sd_bus_message_read_strv(m, &i->documentation);
2844                         if (r < 0)
2845                                 return bus_log_parse_error(r);
2846
2847                 } else if (contents[1] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "Conditions")) {
2848                         const char *cond, *param;
2849                         int trigger, negate;
2850                         int32_t state;
2851
2852                         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sbbsi)");
2853                         if (r < 0)
2854                                 return bus_log_parse_error(r);
2855
2856                         while ((r = sd_bus_message_read(m, "(sbbsi)", &cond, &trigger, &negate, &param, &state)) > 0) {
2857                                 log_debug("%s %d %d %s %d", cond, trigger, negate, param, state);
2858                                 if (state < 0 && (!trigger || !i->failed_condition)) {
2859                                         i->failed_condition = cond;
2860                                         i->failed_condition_trigger = trigger;
2861                                         i->failed_condition_negate = negate;
2862                                         i->failed_condition_param = param;
2863                                 }
2864                         }
2865                         if (r < 0)
2866                                 return bus_log_parse_error(r);
2867
2868                         r = sd_bus_message_exit_container(m);
2869                         if (r < 0)
2870                                 return bus_log_parse_error(r);
2871
2872                 } else
2873                         goto skip;
2874
2875                 break;
2876
2877         case SD_BUS_TYPE_STRUCT_BEGIN:
2878
2879                 if (streq(name, "LoadError")) {
2880                         const char *n, *message;
2881
2882                         r = sd_bus_message_read(m, "(ss)", &n, &message);
2883                         if (r < 0)
2884                                 return bus_log_parse_error(r);
2885
2886                         if (!isempty(message))
2887                                 i->load_error = message;
2888                 } else
2889                         goto skip;
2890
2891                 break;
2892
2893         default:
2894                 goto skip;
2895         }
2896
2897         return 0;
2898
2899 skip:
2900         r = sd_bus_message_skip(m, contents);
2901         if (r < 0)
2902                 return bus_log_parse_error(r);
2903
2904         return 0;
2905 }
2906
2907 static int print_property(const char *name, sd_bus_message *m, const char *contents) {
2908         int r;
2909
2910         assert(name);
2911         assert(m);
2912
2913         /* This is a low-level property printer, see
2914          * print_status_info() for the nicer output */
2915
2916         if (arg_properties && !strv_find(arg_properties, name))
2917                 return 0;
2918
2919         switch (contents[0]) {
2920
2921         case SD_BUS_TYPE_STRUCT_BEGIN:
2922
2923                 if (contents[1] == SD_BUS_TYPE_UINT32 && streq(name, "Job")) {
2924                         uint32_t u;
2925
2926                         r = sd_bus_message_read(m, "(uo)", &u, NULL);
2927                         if (r < 0)
2928                                 return bus_log_parse_error(r);
2929
2930                         if (u > 0)
2931                                 printf("%s=%u\n", name, (unsigned) u);
2932                         else if (arg_all)
2933                                 printf("%s=\n", name);
2934
2935                         return 0;
2936
2937                 } else if (contents[1] == SD_BUS_TYPE_STRING && streq(name, "Unit")) {
2938                         const char *s;
2939
2940                         r = sd_bus_message_read(m, "(so)", &s, NULL);
2941                         if (r < 0)
2942                                 return bus_log_parse_error(r);
2943
2944                         if (arg_all || !isempty(s))
2945                                 printf("%s=%s\n", name, s);
2946
2947                         return 0;
2948
2949                 } else if (contents[1] == SD_BUS_TYPE_STRING && streq(name, "LoadError")) {
2950                         const char *a = NULL, *b = NULL;
2951
2952                         r = sd_bus_message_read(m, "(ss)", &a, &b);
2953                         if (r < 0)
2954                                 return bus_log_parse_error(r);
2955
2956                         if (arg_all || !isempty(a) || !isempty(b))
2957                                 printf("%s=%s \"%s\"\n", name, strempty(a), strempty(b));
2958
2959                         return 0;
2960                 }
2961
2962                 break;
2963
2964         case SD_BUS_TYPE_ARRAY:
2965
2966                 if (contents[1] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "EnvironmentFiles")) {
2967                         const char *path;
2968                         int ignore;
2969
2970                         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sb)");
2971                         if (r < 0)
2972                                 return bus_log_parse_error(r);
2973
2974                         while ((r = sd_bus_message_read(m, "(sb)", &path, &ignore)) > 0)
2975                                 printf("EnvironmentFile=%s (ignore_errors=%s)\n", path, yes_no(ignore));
2976
2977                         if (r < 0)
2978                                 return bus_log_parse_error(r);
2979
2980                         r = sd_bus_message_exit_container(m);
2981                         if (r < 0)
2982                                 return bus_log_parse_error(r);
2983
2984                         return 0;
2985
2986                 } else if (contents[1] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "Paths")) {
2987                         const char *type, *path;
2988
2989                         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
2990                         if (r < 0)
2991                                 return bus_log_parse_error(r);
2992
2993                         while ((r = sd_bus_message_read(m, "(ss)", &type, &path)) > 0)
2994                                 printf("%s=%s\n", type, path);
2995                         if (r < 0)
2996                                 return bus_log_parse_error(r);
2997
2998                         r = sd_bus_message_exit_container(m);
2999                         if (r < 0)
3000                                 return bus_log_parse_error(r);
3001
3002                         return 0;
3003
3004                 } else if (contents[1] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "Listen")) {
3005                         const char *type, *path;
3006
3007                         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
3008                         if (r < 0)
3009                                 return bus_log_parse_error(r);
3010
3011                         while ((r = sd_bus_message_read(m, "(ss)", &type, &path)) > 0)
3012                                 printf("Listen%s=%s\n", type, path);
3013                         if (r < 0)
3014                                 return bus_log_parse_error(r);
3015
3016                         r = sd_bus_message_exit_container(m);
3017                         if (r < 0)
3018                                 return bus_log_parse_error(r);
3019
3020                         return 0;
3021
3022                 } else if (contents[1] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "Timers")) {
3023                         const char *base;
3024                         uint64_t value, next_elapse;
3025
3026                         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(stt)");
3027                         if (r < 0)
3028                                 return bus_log_parse_error(r);
3029
3030                         while ((r = sd_bus_message_read(m, "(stt)", &base, &value, &next_elapse)) > 0) {
3031                                 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
3032
3033                                 printf("%s={ value=%s ; next_elapse=%s }\n",
3034                                        base,
3035                                        format_timespan(timespan1, sizeof(timespan1), value, 0),
3036                                        format_timespan(timespan2, sizeof(timespan2), next_elapse, 0));
3037                         }
3038                         if (r < 0)
3039                                 return bus_log_parse_error(r);
3040
3041                         r = sd_bus_message_exit_container(m);
3042                         if (r < 0)
3043                                 return bus_log_parse_error(r);
3044
3045                         return 0;
3046
3047                 } else if (contents[1] == SD_BUS_TYPE_STRUCT_BEGIN && startswith(name, "Exec")) {
3048                         ExecStatusInfo info = {};
3049
3050                         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sasbttttuii)");
3051                         if (r < 0)
3052                                 return bus_log_parse_error(r);
3053
3054                         while ((r = exec_status_info_deserialize(m, &info)) > 0) {
3055                                 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
3056                                 _cleanup_free_ char *tt;
3057
3058                                 tt = strv_join(info.argv, " ");
3059
3060                                 printf("%s={ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
3061                                        name,
3062                                        strna(info.path),
3063                                        strna(tt),
3064                                        yes_no(info.ignore),
3065                                        strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
3066                                        strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
3067                                        (unsigned) info. pid,
3068                                        sigchld_code_to_string(info.code),
3069                                        info.status,
3070                                        info.code == CLD_EXITED ? "" : "/",
3071                                        strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
3072
3073                                 free(info.path);
3074                                 strv_free(info.argv);
3075                                 zero(info);
3076                         }
3077
3078                         r = sd_bus_message_exit_container(m);
3079                         if (r < 0)
3080                                 return bus_log_parse_error(r);
3081
3082                         return 0;
3083