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