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