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