chiark / gitweb /
util: never use sizeof(sa_family_t) when calculating sockaddr sizes
[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_RUNLEVEL2,
85         ACTION_RUNLEVEL3,
86         ACTION_RUNLEVEL4,
87         ACTION_RUNLEVEL5,
88         ACTION_RESCUE,
89         ACTION_EMERGENCY,
90         ACTION_DEFAULT,
91         ACTION_RELOAD,
92         ACTION_REEXEC,
93         ACTION_RUNLEVEL,
94         ACTION_CANCEL_SHUTDOWN,
95         _ACTION_MAX
96 } arg_action = ACTION_SYSTEMCTL;
97 static enum dot {
98         DOT_ALL,
99         DOT_ORDER,
100         DOT_REQUIRE
101 } arg_dot = DOT_ALL;
102
103 static bool private_bus = false;
104
105 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
106
107 static bool on_tty(void) {
108         static int t = -1;
109
110         if (_unlikely_(t < 0))
111                 t = isatty(STDOUT_FILENO) > 0;
112
113         return t;
114 }
115
116 static const char *ansi_highlight(bool b) {
117
118         if (!on_tty())
119                 return "";
120
121         return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
122 }
123
124 static const char *ansi_highlight_green(bool b) {
125
126         if (!on_tty())
127                 return "";
128
129         return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
130 }
131
132 static bool error_is_no_service(const DBusError *error) {
133         assert(error);
134
135         if (!dbus_error_is_set(error))
136                 return false;
137
138         if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
139                 return true;
140
141         if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
142                 return true;
143
144         return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
145 }
146
147 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
148         assert(error);
149
150         if (!dbus_error_is_set(error))
151                 return r;
152
153         if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
154             dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
155             dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
156             dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
157                 return EXIT_NOPERMISSION;
158
159         if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
160                 return EXIT_NOTINSTALLED;
161
162         if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
163             dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
164                 return EXIT_NOTIMPLEMENTED;
165
166         if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
167                 return EXIT_NOTCONFIGURED;
168
169         if (r != 0)
170                 return r;
171
172         return EXIT_FAILURE;
173 }
174
175 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
176
177         assert(iter);
178         assert(data);
179
180         if (dbus_message_iter_get_arg_type(iter) != type)
181                 return -EIO;
182
183         dbus_message_iter_get_basic(iter, data);
184
185         if (!dbus_message_iter_next(iter) != !next)
186                 return -EIO;
187
188         return 0;
189 }
190
191 static void warn_wall(enum action action) {
192         static const char *table[_ACTION_MAX] = {
193                 [ACTION_HALT]      = "The system is going down for system halt NOW!",
194                 [ACTION_REBOOT]    = "The system is going down for reboot NOW!",
195                 [ACTION_POWEROFF]  = "The system is going down for power-off NOW!",
196                 [ACTION_RESCUE]    = "The system is going down to rescue mode NOW!",
197                 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
198         };
199
200         if (arg_no_wall)
201                 return;
202
203         if (arg_wall) {
204                 char *p;
205
206                 if (!(p = strv_join(arg_wall, " "))) {
207                         log_error("Failed to join strings.");
208                         return;
209                 }
210
211                 if (*p) {
212                         utmp_wall(p);
213                         free(p);
214                         return;
215                 }
216
217                 free(p);
218         }
219
220         if (!table[action])
221                 return;
222
223         utmp_wall(table[action]);
224 }
225
226 struct unit_info {
227         const char *id;
228         const char *description;
229         const char *load_state;
230         const char *active_state;
231         const char *sub_state;
232         const char *following;
233         const char *unit_path;
234         uint32_t job_id;
235         const char *job_type;
236         const char *job_path;
237 };
238
239 static int compare_unit_info(const void *a, const void *b) {
240         const char *d1, *d2;
241         const struct unit_info *u = a, *v = b;
242
243         d1 = strrchr(u->id, '.');
244         d2 = strrchr(v->id, '.');
245
246         if (d1 && d2) {
247                 int r;
248
249                 if ((r = strcasecmp(d1, d2)) != 0)
250                         return r;
251         }
252
253         return strcasecmp(u->id, v->id);
254 }
255
256 static bool output_show_job(const struct unit_info *u) {
257         const char *dot;
258
259         return (!arg_type || ((dot = strrchr(u->id, '.')) &&
260                               streq(dot+1, arg_type))) &&
261                 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0);
262 }
263
264 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
265         unsigned active_len, sub_len, job_len;
266         const struct unit_info *u;
267
268         active_len = sizeof("ACTIVE")-1;
269         sub_len = sizeof("SUB")-1;
270         job_len = sizeof("JOB")-1;
271
272         for (u = unit_infos; u < unit_infos + c; u++) {
273                 if (!output_show_job(u))
274                         continue;
275
276                 active_len = MAX(active_len, strlen(u->active_state));
277                 sub_len = MAX(sub_len, strlen(u->sub_state));
278                 if (u->job_id != 0)
279                         job_len = MAX(job_len, strlen(u->job_type));
280         }
281
282         if (on_tty()) {
283                 printf("%-25s %-6s %-*s %-*s %-*s", "UNIT", "LOAD",
284                        active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
285                 if (columns() >= 80+12 || arg_full)
286                         printf(" %s\n", "DESCRIPTION");
287                 else
288                         printf("\n");
289         }
290
291         for (u = unit_infos; u < unit_infos + c; u++) {
292                 char *e;
293                 int a = 0, b = 0;
294                 const char *on_loaded, *off_loaded;
295                 const char *on_active, *off_active;
296
297                 if (!output_show_job(u))
298                         continue;
299
300                 if (!streq(u->load_state, "loaded")) {
301                         on_loaded = ansi_highlight(true);
302                         off_loaded = ansi_highlight(false);
303                 } else
304                         on_loaded = off_loaded = "";
305
306                 if (streq(u->active_state, "failed")) {
307                         on_active = ansi_highlight(true);
308                         off_active = ansi_highlight(false);
309                 } else
310                         on_active = off_active = "";
311
312                 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
313
314                 printf("%-25s %s%-6s%s %s%-*s %-*s%s%n",
315                        e ? e : u->id,
316                        on_loaded, u->load_state, off_loaded,
317                        on_active, active_len, u->active_state,
318                        sub_len, u->sub_state, off_active,
319                        &a);
320
321                 free(e);
322
323                 a -= strlen(on_loaded) + strlen(off_loaded);
324                 a -= strlen(on_active) + strlen(off_active);
325
326                 if (u->job_id != 0)
327                         printf(" %-*s", job_len, u->job_type);
328                 else
329                         b = 1 + job_len;
330
331                 if (a + b + 1 < columns()) {
332                         if (u->job_id == 0)
333                                 printf(" %-*s", job_len, "");
334
335                         if (arg_full)
336                                 printf(" %s", u->description);
337                         else
338                                 printf(" %.*s", columns() - a - b - 1, u->description);
339                 }
340
341                 fputs("\n", stdout);
342         }
343
344         if (on_tty()) {
345                 printf("\nLOAD   = Reflects whether the unit definition was properly loaded.\n"
346                        "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
347                        "SUB    = The low-level unit activation state, values depend on unit type.\n"
348                        "JOB    = Pending job for the unit.\n");
349
350                 if (arg_all)
351                         printf("\n%u units listed.\n", c);
352                 else
353                         printf("\n%u units listed. Pass --all to see inactive units, too.\n", c);
354         }
355 }
356
357 static int list_units(DBusConnection *bus, char **args, unsigned n) {
358         DBusMessage *m = NULL, *reply = NULL;
359         DBusError error;
360         int r;
361         DBusMessageIter iter, sub, sub2;
362         unsigned c = 0, n_units = 0;
363         struct unit_info *unit_infos = NULL;
364
365         dbus_error_init(&error);
366
367         assert(bus);
368
369         if (!(m = dbus_message_new_method_call(
370                               "org.freedesktop.systemd1",
371                               "/org/freedesktop/systemd1",
372                               "org.freedesktop.systemd1.Manager",
373                               "ListUnits"))) {
374                 log_error("Could not allocate message.");
375                 return -ENOMEM;
376         }
377
378         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
379                 log_error("Failed to issue method call: %s", bus_error_message(&error));
380                 r = -EIO;
381                 goto finish;
382         }
383
384         if (!dbus_message_iter_init(reply, &iter) ||
385             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
386             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT)  {
387                 log_error("Failed to parse reply.");
388                 r = -EIO;
389                 goto finish;
390         }
391
392         dbus_message_iter_recurse(&iter, &sub);
393
394         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
395                 struct unit_info *u;
396
397                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
398                         log_error("Failed to parse reply.");
399                         r = -EIO;
400                         goto finish;
401                 }
402
403                 if (c >= n_units) {
404                         struct unit_info *w;
405
406                         n_units = MAX(2*c, 16);
407                         w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
408
409                         if (!w) {
410                                 log_error("Failed to allocate unit array.");
411                                 r = -ENOMEM;
412                                 goto finish;
413                         }
414
415                         unit_infos = w;
416                 }
417
418                 u = unit_infos+c;
419
420                 dbus_message_iter_recurse(&sub, &sub2);
421
422                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
423                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
424                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
425                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
426                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
427                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
428                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
429                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
430                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
431                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
432                         log_error("Failed to parse reply.");
433                         r = -EIO;
434                         goto finish;
435                 }
436
437                 dbus_message_iter_next(&sub);
438                 c++;
439         }
440
441         qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
442         output_units_list(unit_infos, c);
443
444         r = 0;
445
446 finish:
447         if (m)
448                 dbus_message_unref(m);
449
450         if (reply)
451                 dbus_message_unref(reply);
452
453         free(unit_infos);
454
455         dbus_error_free(&error);
456
457         return r;
458 }
459
460 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
461         static const char * const colors[] = {
462                 "Requires",              "[color=\"black\"]",
463                 "RequiresOverridable",   "[color=\"black\"]",
464                 "Requisite",             "[color=\"darkblue\"]",
465                 "RequisiteOverridable",  "[color=\"darkblue\"]",
466                 "Wants",                 "[color=\"darkgrey\"]",
467                 "Conflicts",             "[color=\"red\"]",
468                 "ConflictedBy",          "[color=\"red\"]",
469                 "After",                 "[color=\"green\"]"
470         };
471
472         const char *c = NULL;
473         unsigned i;
474
475         assert(name);
476         assert(prop);
477         assert(iter);
478
479         for (i = 0; i < ELEMENTSOF(colors); i += 2)
480                 if (streq(colors[i], prop)) {
481                         c = colors[i+1];
482                         break;
483                 }
484
485         if (!c)
486                 return 0;
487
488         if (arg_dot != DOT_ALL)
489                 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
490                         return 0;
491
492         switch (dbus_message_iter_get_arg_type(iter)) {
493
494         case DBUS_TYPE_ARRAY:
495
496                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
497                         DBusMessageIter sub;
498
499                         dbus_message_iter_recurse(iter, &sub);
500
501                         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
502                                 const char *s;
503
504                                 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
505                                 dbus_message_iter_get_basic(&sub, &s);
506                                 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
507
508                                 dbus_message_iter_next(&sub);
509                         }
510
511                         return 0;
512                 }
513         }
514
515         return 0;
516 }
517
518 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
519         DBusMessage *m = NULL, *reply = NULL;
520         const char *interface = "org.freedesktop.systemd1.Unit";
521         int r;
522         DBusError error;
523         DBusMessageIter iter, sub, sub2, sub3;
524
525         assert(bus);
526         assert(path);
527
528         dbus_error_init(&error);
529
530         if (!(m = dbus_message_new_method_call(
531                               "org.freedesktop.systemd1",
532                               path,
533                               "org.freedesktop.DBus.Properties",
534                               "GetAll"))) {
535                 log_error("Could not allocate message.");
536                 r = -ENOMEM;
537                 goto finish;
538         }
539
540         if (!dbus_message_append_args(m,
541                                       DBUS_TYPE_STRING, &interface,
542                                       DBUS_TYPE_INVALID)) {
543                 log_error("Could not append arguments to message.");
544                 r = -ENOMEM;
545                 goto finish;
546         }
547
548         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
549                 log_error("Failed to issue method call: %s", bus_error_message(&error));
550                 r = -EIO;
551                 goto finish;
552         }
553
554         if (!dbus_message_iter_init(reply, &iter) ||
555             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
556             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY)  {
557                 log_error("Failed to parse reply.");
558                 r = -EIO;
559                 goto finish;
560         }
561
562         dbus_message_iter_recurse(&iter, &sub);
563
564         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
565                 const char *prop;
566
567                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
568                         log_error("Failed to parse reply.");
569                         r = -EIO;
570                         goto finish;
571                 }
572
573                 dbus_message_iter_recurse(&sub, &sub2);
574
575                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
576                         log_error("Failed to parse reply.");
577                         r = -EIO;
578                         goto finish;
579                 }
580
581                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT)  {
582                         log_error("Failed to parse reply.");
583                         r = -EIO;
584                         goto finish;
585                 }
586
587                 dbus_message_iter_recurse(&sub2, &sub3);
588
589                 if (dot_one_property(name, prop, &sub3)) {
590                         log_error("Failed to parse reply.");
591                         r = -EIO;
592                         goto finish;
593                 }
594
595                 dbus_message_iter_next(&sub);
596         }
597
598         r = 0;
599
600 finish:
601         if (m)
602                 dbus_message_unref(m);
603
604         if (reply)
605                 dbus_message_unref(reply);
606
607         dbus_error_free(&error);
608
609         return r;
610 }
611
612 static int dot(DBusConnection *bus, char **args, unsigned n) {
613         DBusMessage *m = NULL, *reply = NULL;
614         DBusError error;
615         int r;
616         DBusMessageIter iter, sub, sub2;
617
618         dbus_error_init(&error);
619
620         assert(bus);
621
622         if (!(m = dbus_message_new_method_call(
623                               "org.freedesktop.systemd1",
624                               "/org/freedesktop/systemd1",
625                               "org.freedesktop.systemd1.Manager",
626                               "ListUnits"))) {
627                 log_error("Could not allocate message.");
628                 return -ENOMEM;
629         }
630
631         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
632                 log_error("Failed to issue method call: %s", bus_error_message(&error));
633                 r = -EIO;
634                 goto finish;
635         }
636
637         if (!dbus_message_iter_init(reply, &iter) ||
638             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
639             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT)  {
640                 log_error("Failed to parse reply.");
641                 r = -EIO;
642                 goto finish;
643         }
644
645         printf("digraph systemd {\n");
646
647         dbus_message_iter_recurse(&iter, &sub);
648         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
649                 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
650
651                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
652                         log_error("Failed to parse reply.");
653                         r = -EIO;
654                         goto finish;
655                 }
656
657                 dbus_message_iter_recurse(&sub, &sub2);
658
659                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
660                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
661                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
662                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
663                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
664                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
665                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
666                         log_error("Failed to parse reply.");
667                         r = -EIO;
668                         goto finish;
669                 }
670
671                 if ((r = dot_one(bus, id, unit_path)) < 0)
672                         goto finish;
673
674                 /* printf("\t\"%s\";\n", id); */
675                 dbus_message_iter_next(&sub);
676         }
677
678         printf("}\n");
679
680         log_info("   Color legend: black     = Requires\n"
681                  "                 dark blue = Requisite\n"
682                  "                 dark grey = Wants\n"
683                  "                 red       = Conflicts\n"
684                  "                 green     = After\n");
685
686         if (isatty(fileno(stdout)))
687                 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
688                            "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
689
690         r = 0;
691
692 finish:
693         if (m)
694                 dbus_message_unref(m);
695
696         if (reply)
697                 dbus_message_unref(reply);
698
699         dbus_error_free(&error);
700
701         return r;
702 }
703
704 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
705         DBusMessage *m = NULL, *reply = NULL;
706         DBusError error;
707         int r;
708         DBusMessageIter iter, sub, sub2;
709         unsigned k = 0;
710
711         dbus_error_init(&error);
712
713         assert(bus);
714
715         if (!(m = dbus_message_new_method_call(
716                               "org.freedesktop.systemd1",
717                               "/org/freedesktop/systemd1",
718                               "org.freedesktop.systemd1.Manager",
719                               "ListJobs"))) {
720                 log_error("Could not allocate message.");
721                 return -ENOMEM;
722         }
723
724         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
725                 log_error("Failed to issue method call: %s", bus_error_message(&error));
726                 r = -EIO;
727                 goto finish;
728         }
729
730         if (!dbus_message_iter_init(reply, &iter) ||
731             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
732             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT)  {
733                 log_error("Failed to parse reply.");
734                 r = -EIO;
735                 goto finish;
736         }
737
738         dbus_message_iter_recurse(&iter, &sub);
739
740         if (isatty(STDOUT_FILENO))
741                 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
742
743         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
744                 const char *name, *type, *state, *job_path, *unit_path;
745                 uint32_t id;
746                 char *e;
747
748                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
749                         log_error("Failed to parse reply.");
750                         r = -EIO;
751                         goto finish;
752                 }
753
754                 dbus_message_iter_recurse(&sub, &sub2);
755
756                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
757                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
758                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
759                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
760                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
761                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
762                         log_error("Failed to parse reply.");
763                         r = -EIO;
764                         goto finish;
765                 }
766
767                 e = arg_full ? NULL : ellipsize(name, 25, 33);
768                 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
769                 free(e);
770
771                 k++;
772
773                 dbus_message_iter_next(&sub);
774         }
775
776         if (isatty(STDOUT_FILENO))
777                 printf("\n%u jobs listed.\n", k);
778
779         r = 0;
780
781 finish:
782         if (m)
783                 dbus_message_unref(m);
784
785         if (reply)
786                 dbus_message_unref(reply);
787
788         dbus_error_free(&error);
789
790         return r;
791 }
792
793 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
794         DBusMessage *m = NULL, *reply = NULL;
795         DBusError error;
796         int r;
797         unsigned i;
798
799         dbus_error_init(&error);
800
801         assert(bus);
802         assert(args);
803
804         for (i = 1; i < n; i++) {
805
806                 if (!(m = dbus_message_new_method_call(
807                                       "org.freedesktop.systemd1",
808                                       "/org/freedesktop/systemd1",
809                                       "org.freedesktop.systemd1.Manager",
810                                       "LoadUnit"))) {
811                         log_error("Could not allocate message.");
812                         r = -ENOMEM;
813                         goto finish;
814                 }
815
816                 if (!dbus_message_append_args(m,
817                                               DBUS_TYPE_STRING, &args[i],
818                                               DBUS_TYPE_INVALID)) {
819                         log_error("Could not append arguments to message.");
820                         r = -ENOMEM;
821                         goto finish;
822                 }
823
824                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
825                         log_error("Failed to issue method call: %s", bus_error_message(&error));
826                         r = -EIO;
827                         goto finish;
828                 }
829
830                 dbus_message_unref(m);
831                 dbus_message_unref(reply);
832
833                 m = reply = NULL;
834         }
835
836         r = 0;
837
838 finish:
839         if (m)
840                 dbus_message_unref(m);
841
842         if (reply)
843                 dbus_message_unref(reply);
844
845         dbus_error_free(&error);
846
847         return r;
848 }
849
850 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
851         DBusMessage *m = NULL, *reply = NULL;
852         DBusError error;
853         int r;
854         unsigned i;
855
856         dbus_error_init(&error);
857
858         assert(bus);
859         assert(args);
860
861         if (n <= 1)
862                 return daemon_reload(bus, args, n);
863
864         for (i = 1; i < n; i++) {
865                 unsigned id;
866                 const char *path;
867
868                 if (!(m = dbus_message_new_method_call(
869                                       "org.freedesktop.systemd1",
870                                       "/org/freedesktop/systemd1",
871                                       "org.freedesktop.systemd1.Manager",
872                                       "GetJob"))) {
873                         log_error("Could not allocate message.");
874                         r = -ENOMEM;
875                         goto finish;
876                 }
877
878                 if ((r = safe_atou(args[i], &id)) < 0) {
879                         log_error("Failed to parse job id: %s", strerror(-r));
880                         goto finish;
881                 }
882
883                 assert_cc(sizeof(uint32_t) == sizeof(id));
884                 if (!dbus_message_append_args(m,
885                                               DBUS_TYPE_UINT32, &id,
886                                               DBUS_TYPE_INVALID)) {
887                         log_error("Could not append arguments to message.");
888                         r = -ENOMEM;
889                         goto finish;
890                 }
891
892                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
893                         log_error("Failed to issue method call: %s", bus_error_message(&error));
894                         r = -EIO;
895                         goto finish;
896                 }
897
898                 if (!dbus_message_get_args(reply, &error,
899                                            DBUS_TYPE_OBJECT_PATH, &path,
900                                            DBUS_TYPE_INVALID)) {
901                         log_error("Failed to parse reply: %s", bus_error_message(&error));
902                         r = -EIO;
903                         goto finish;
904                 }
905
906                 dbus_message_unref(m);
907                 if (!(m = dbus_message_new_method_call(
908                                       "org.freedesktop.systemd1",
909                                       path,
910                                       "org.freedesktop.systemd1.Job",
911                                       "Cancel"))) {
912                         log_error("Could not allocate message.");
913                         r = -ENOMEM;
914                         goto finish;
915                 }
916
917                 dbus_message_unref(reply);
918                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
919                         log_error("Failed to issue method call: %s", bus_error_message(&error));
920                         r = -EIO;
921                         goto finish;
922                 }
923
924                 dbus_message_unref(m);
925                 dbus_message_unref(reply);
926                 m = reply = NULL;
927         }
928
929         r = 0;
930
931 finish:
932         if (m)
933                 dbus_message_unref(m);
934
935         if (reply)
936                 dbus_message_unref(reply);
937
938         dbus_error_free(&error);
939
940         return r;
941 }
942
943 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
944         DBusMessage *m = NULL, *reply = NULL;
945         dbus_bool_t b = FALSE;
946         DBusMessageIter iter, sub;
947         const char
948                 *interface = "org.freedesktop.systemd1.Unit",
949                 *property = "NeedDaemonReload",
950                 *path;
951
952         /* We ignore all errors here, since this is used to show a warning only */
953
954         if (!(m = dbus_message_new_method_call(
955                               "org.freedesktop.systemd1",
956                               "/org/freedesktop/systemd1",
957                               "org.freedesktop.systemd1.Manager",
958                               "GetUnit")))
959                 goto finish;
960
961         if (!dbus_message_append_args(m,
962                                       DBUS_TYPE_STRING, &unit,
963                                       DBUS_TYPE_INVALID))
964                 goto finish;
965
966         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
967                 goto finish;
968
969         if (!dbus_message_get_args(reply, NULL,
970                                    DBUS_TYPE_OBJECT_PATH, &path,
971                                    DBUS_TYPE_INVALID))
972                 goto finish;
973
974         dbus_message_unref(m);
975         if (!(m = dbus_message_new_method_call(
976                               "org.freedesktop.systemd1",
977                               path,
978                               "org.freedesktop.DBus.Properties",
979                               "Get")))
980                 goto finish;
981
982         if (!dbus_message_append_args(m,
983                                       DBUS_TYPE_STRING, &interface,
984                                       DBUS_TYPE_STRING, &property,
985                                       DBUS_TYPE_INVALID)) {
986                 goto finish;
987         }
988
989         dbus_message_unref(reply);
990         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
991                 goto finish;
992
993         if (!dbus_message_iter_init(reply, &iter) ||
994             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
995                 goto finish;
996
997         dbus_message_iter_recurse(&iter, &sub);
998
999         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1000                 goto finish;
1001
1002         dbus_message_iter_get_basic(&sub, &b);
1003
1004 finish:
1005         if (m)
1006                 dbus_message_unref(m);
1007
1008         if (reply)
1009                 dbus_message_unref(reply);
1010
1011         return b;
1012 }
1013
1014 typedef struct WaitData {
1015         Set *set;
1016         bool failed;
1017 } WaitData;
1018
1019 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1020         DBusError error;
1021         WaitData *d = data;
1022
1023         assert(connection);
1024         assert(message);
1025         assert(d);
1026
1027         dbus_error_init(&error);
1028
1029         log_debug("Got D-Bus request: %s.%s() on %s",
1030                   dbus_message_get_interface(message),
1031                   dbus_message_get_member(message),
1032                   dbus_message_get_path(message));
1033
1034         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1035                 log_error("Warning! D-Bus connection terminated.");
1036                 dbus_connection_close(connection);
1037
1038         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1039                 uint32_t id;
1040                 const char *path;
1041                 dbus_bool_t success = true;
1042
1043                 if (!dbus_message_get_args(message, &error,
1044                                            DBUS_TYPE_UINT32, &id,
1045                                            DBUS_TYPE_OBJECT_PATH, &path,
1046                                            DBUS_TYPE_BOOLEAN, &success,
1047                                            DBUS_TYPE_INVALID))
1048                         log_error("Failed to parse message: %s", bus_error_message(&error));
1049                 else {
1050                         char *p;
1051
1052                         if ((p = set_remove(d->set, (char*) path)))
1053                                 free(p);
1054
1055                         if (!success)
1056                                 d->failed = true;
1057                 }
1058         }
1059
1060         dbus_error_free(&error);
1061         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1062 }
1063
1064 static int enable_wait_for_jobs(DBusConnection *bus) {
1065         DBusError error;
1066
1067         assert(bus);
1068
1069         if (private_bus)
1070                 return 0;
1071
1072         dbus_error_init(&error);
1073         dbus_bus_add_match(bus,
1074                            "type='signal',"
1075                            "sender='org.freedesktop.systemd1',"
1076                            "interface='org.freedesktop.systemd1.Manager',"
1077                            "member='JobRemoved',"
1078                            "path='/org/freedesktop/systemd1'",
1079                            &error);
1080
1081         if (dbus_error_is_set(&error)) {
1082                 log_error("Failed to add match: %s", bus_error_message(&error));
1083                 dbus_error_free(&error);
1084                 return -EIO;
1085         }
1086
1087         /* This is slightly dirty, since we don't undo the match registrations. */
1088         return 0;
1089 }
1090
1091 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1092         int r;
1093         WaitData d;
1094
1095         assert(bus);
1096         assert(s);
1097
1098         zero(d);
1099         d.set = s;
1100         d.failed = false;
1101
1102         if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1103                 log_error("Failed to add filter.");
1104                 r = -ENOMEM;
1105                 goto finish;
1106         }
1107
1108         while (!set_isempty(s) &&
1109                dbus_connection_read_write_dispatch(bus, -1))
1110                 ;
1111
1112         if (!arg_quiet && d.failed)
1113                 log_error("Job failed, see system logs for details.");
1114
1115         r = d.failed ? -EIO : 0;
1116
1117 finish:
1118         /* This is slightly dirty, since we don't undo the filter registration. */
1119
1120         return r;
1121 }
1122
1123 static int start_unit_one(
1124                 DBusConnection *bus,
1125                 const char *method,
1126                 const char *name,
1127                 const char *mode,
1128                 DBusError *error,
1129                 Set *s) {
1130
1131         DBusMessage *m = NULL, *reply = NULL;
1132         const char *path;
1133         int r;
1134
1135         assert(bus);
1136         assert(method);
1137         assert(name);
1138         assert(mode);
1139         assert(error);
1140         assert(arg_no_block || s);
1141
1142         if (!(m = dbus_message_new_method_call(
1143                               "org.freedesktop.systemd1",
1144                               "/org/freedesktop/systemd1",
1145                               "org.freedesktop.systemd1.Manager",
1146                               method))) {
1147                 log_error("Could not allocate message.");
1148                 r = -ENOMEM;
1149                 goto finish;
1150         }
1151
1152         if (!dbus_message_append_args(m,
1153                                       DBUS_TYPE_STRING, &name,
1154                                       DBUS_TYPE_STRING, &mode,
1155                                       DBUS_TYPE_INVALID)) {
1156                 log_error("Could not append arguments to message.");
1157                 r = -ENOMEM;
1158                 goto finish;
1159         }
1160
1161         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1162
1163                 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1164                         /* There's always a fallback possible for
1165                          * legacy actions. */
1166                         r = -EADDRNOTAVAIL;
1167                         goto finish;
1168                 }
1169
1170                 log_error("Failed to issue method call: %s", bus_error_message(error));
1171                 r = -EIO;
1172                 goto finish;
1173         }
1174
1175         if (!dbus_message_get_args(reply, error,
1176                                    DBUS_TYPE_OBJECT_PATH, &path,
1177                                    DBUS_TYPE_INVALID)) {
1178                 log_error("Failed to parse reply: %s", bus_error_message(error));
1179                 r = -EIO;
1180                 goto finish;
1181         }
1182
1183         if (need_daemon_reload(bus, name))
1184                 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1185                             arg_session ? "--session" : "--system");
1186
1187         if (!arg_no_block) {
1188                 char *p;
1189
1190                 if (!(p = strdup(path))) {
1191                         log_error("Failed to duplicate path.");
1192                         r = -ENOMEM;
1193                         goto finish;
1194                 }
1195
1196                 if ((r = set_put(s, p)) < 0) {
1197                         free(p);
1198                         log_error("Failed to add path to set.");
1199                         goto finish;
1200                 }
1201         }
1202
1203         r = 0;
1204
1205 finish:
1206         if (m)
1207                 dbus_message_unref(m);
1208
1209         if (reply)
1210                 dbus_message_unref(reply);
1211
1212         return r;
1213 }
1214
1215 static enum action verb_to_action(const char *verb) {
1216         if (streq(verb, "halt"))
1217                 return ACTION_HALT;
1218         else if (streq(verb, "poweroff"))
1219                 return ACTION_POWEROFF;
1220         else if (streq(verb, "reboot"))
1221                 return ACTION_REBOOT;
1222         else if (streq(verb, "rescue"))
1223                 return ACTION_RESCUE;
1224         else if (streq(verb, "emergency"))
1225                 return ACTION_EMERGENCY;
1226         else if (streq(verb, "default"))
1227                 return ACTION_DEFAULT;
1228         else
1229                 return ACTION_INVALID;
1230 }
1231
1232 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1233
1234         static const char * const table[_ACTION_MAX] = {
1235                 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1236                 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1237                 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1238                 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1239                 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1240                 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1241                 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1242                 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1243                 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1244                 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET
1245         };
1246
1247         int r, ret = 0;
1248         unsigned i;
1249         const char *method, *mode, *one_name;
1250         Set *s = NULL;
1251         DBusError error;
1252
1253         dbus_error_init(&error);
1254
1255         assert(bus);
1256
1257         if (arg_action == ACTION_SYSTEMCTL) {
1258                 method =
1259                         streq(args[0], "stop")                  ? "StopUnit" :
1260                         streq(args[0], "reload")                ? "ReloadUnit" :
1261                         streq(args[0], "restart")               ? "RestartUnit" :
1262                         streq(args[0], "try-restart")           ||
1263                         streq(args[0], "condrestart")           ? "TryRestartUnit" :
1264                         streq(args[0], "reload-or-restart")     ? "ReloadOrRestartUnit" :
1265                         streq(args[0], "reload-or-try-restart") ||
1266                         streq(args[0], "force-reload")          ? "ReloadOrTryRestartUnit" :
1267                                                                   "StartUnit";
1268
1269                 mode =
1270                         (streq(args[0], "isolate") ||
1271                          streq(args[0], "rescue")  ||
1272                          streq(args[0], "emergency")) ? "isolate" :
1273                                              arg_fail ? "fail" :
1274                                                         "replace";
1275
1276                 one_name = table[verb_to_action(args[0])];
1277
1278         } else {
1279                 assert(arg_action < ELEMENTSOF(table));
1280                 assert(table[arg_action]);
1281
1282                 method = "StartUnit";
1283
1284                 mode = (arg_action == ACTION_EMERGENCY ||
1285                         arg_action == ACTION_RESCUE ||
1286                         arg_action == ACTION_RUNLEVEL2 ||
1287                         arg_action == ACTION_RUNLEVEL3 ||
1288                         arg_action == ACTION_RUNLEVEL4 ||
1289                         arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1290
1291                 one_name = table[arg_action];
1292         }
1293
1294         if (!arg_no_block) {
1295                 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1296                         log_error("Could not watch jobs: %s", strerror(-ret));
1297                         goto finish;
1298                 }
1299
1300                 if (!(s = set_new(string_hash_func, string_compare_func))) {
1301                         log_error("Failed to allocate set.");
1302                         ret = -ENOMEM;
1303                         goto finish;
1304                 }
1305         }
1306
1307         if (one_name) {
1308                 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1309                         goto finish;
1310         } else {
1311                 for (i = 1; i < n; i++)
1312                         if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1313                                 ret = translate_bus_error_to_exit_status(r, &error);
1314                                 dbus_error_free(&error);
1315                         }
1316         }
1317
1318         if (!arg_no_block)
1319                 if ((r = wait_for_jobs(bus, s)) < 0) {
1320                         ret = r;
1321                         goto finish;
1322                 }
1323
1324 finish:
1325         if (s)
1326                 set_free_free(s);
1327
1328         dbus_error_free(&error);
1329
1330         return ret;
1331 }
1332
1333 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1334         int r;
1335
1336         assert(bus);
1337         assert(args);
1338
1339         r = start_unit(bus, args, n);
1340
1341         if (r >= 0)
1342                 warn_wall(verb_to_action(args[0]));
1343
1344         return r;
1345 }
1346
1347 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1348         DBusMessage *m = NULL, *reply = NULL;
1349         const char
1350                 *interface = "org.freedesktop.systemd1.Unit",
1351                 *property = "ActiveState";
1352         int r = 3; /* According to LSB: "program is not running" */
1353         DBusError error;
1354         unsigned i;
1355
1356         assert(bus);
1357         assert(args);
1358
1359         dbus_error_init(&error);
1360
1361         for (i = 1; i < n; i++) {
1362                 const char *path = NULL;
1363                 const char *state;
1364                 DBusMessageIter iter, sub;
1365
1366                 if (!(m = dbus_message_new_method_call(
1367                                       "org.freedesktop.systemd1",
1368                                       "/org/freedesktop/systemd1",
1369                                       "org.freedesktop.systemd1.Manager",
1370                                       "GetUnit"))) {
1371                         log_error("Could not allocate message.");
1372                         r = -ENOMEM;
1373                         goto finish;
1374                 }
1375
1376                 if (!dbus_message_append_args(m,
1377                                               DBUS_TYPE_STRING, &args[i],
1378                                               DBUS_TYPE_INVALID)) {
1379                         log_error("Could not append arguments to message.");
1380                         r = -ENOMEM;
1381                         goto finish;
1382                 }
1383
1384                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1385
1386                         /* Hmm, cannot figure out anything about this unit... */
1387                         if (!arg_quiet)
1388                                 puts("unknown");
1389
1390                         dbus_error_free(&error);
1391                         continue;
1392                 }
1393
1394                 if (!dbus_message_get_args(reply, &error,
1395                                            DBUS_TYPE_OBJECT_PATH, &path,
1396                                            DBUS_TYPE_INVALID)) {
1397                         log_error("Failed to parse reply: %s", bus_error_message(&error));
1398                         r = -EIO;
1399                         goto finish;
1400                 }
1401
1402                 dbus_message_unref(m);
1403                 if (!(m = dbus_message_new_method_call(
1404                                       "org.freedesktop.systemd1",
1405                                       path,
1406                                       "org.freedesktop.DBus.Properties",
1407                                       "Get"))) {
1408                         log_error("Could not allocate message.");
1409                         r = -ENOMEM;
1410                         goto finish;
1411                 }
1412
1413                 if (!dbus_message_append_args(m,
1414                                               DBUS_TYPE_STRING, &interface,
1415                                               DBUS_TYPE_STRING, &property,
1416                                               DBUS_TYPE_INVALID)) {
1417                         log_error("Could not append arguments to message.");
1418                         r = -ENOMEM;
1419                         goto finish;
1420                 }
1421
1422                 dbus_message_unref(reply);
1423                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1424                         log_error("Failed to issue method call: %s", bus_error_message(&error));
1425                         r = -EIO;
1426                         goto finish;
1427                 }
1428
1429                 if (!dbus_message_iter_init(reply, &iter) ||
1430                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
1431                         log_error("Failed to parse reply.");
1432                         r = -EIO;
1433                         goto finish;
1434                 }
1435
1436                 dbus_message_iter_recurse(&iter, &sub);
1437
1438                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
1439                         log_error("Failed to parse reply.");
1440                         r = -EIO;
1441                         goto finish;
1442                 }
1443
1444                 dbus_message_iter_get_basic(&sub, &state);
1445
1446                 if (!arg_quiet)
1447                         puts(state);
1448
1449                 if (streq(state, "active") || streq(state, "reloading"))
1450                         r = 0;
1451
1452                 dbus_message_unref(m);
1453                 dbus_message_unref(reply);
1454                 m = reply = NULL;
1455         }
1456
1457 finish:
1458         if (m)
1459                 dbus_message_unref(m);
1460
1461         if (reply)
1462                 dbus_message_unref(reply);
1463
1464         dbus_error_free(&error);
1465
1466         return r;
1467 }
1468
1469 typedef struct ExecStatusInfo {
1470         char *path;
1471         char **argv;
1472
1473         bool ignore;
1474
1475         usec_t start_timestamp;
1476         usec_t exit_timestamp;
1477         pid_t pid;
1478         int code;
1479         int status;
1480
1481         LIST_FIELDS(struct ExecStatusInfo, exec);
1482 } ExecStatusInfo;
1483
1484 static void exec_status_info_free(ExecStatusInfo *i) {
1485         assert(i);
1486
1487         free(i->path);
1488         strv_free(i->argv);
1489         free(i);
1490 }
1491
1492 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1493         uint64_t start_timestamp, exit_timestamp;
1494         DBusMessageIter sub2, sub3;
1495         const char*path;
1496         unsigned n;
1497         uint32_t pid;
1498         int32_t code, status;
1499         dbus_bool_t ignore;
1500
1501         assert(i);
1502         assert(i);
1503
1504         if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1505                 return -EIO;
1506
1507         dbus_message_iter_recurse(sub, &sub2);
1508
1509         if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1510                 return -EIO;
1511
1512         if (!(i->path = strdup(path)))
1513                 return -ENOMEM;
1514
1515         if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1516             dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1517                 return -EIO;
1518
1519         n = 0;
1520         dbus_message_iter_recurse(&sub2, &sub3);
1521         while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1522                 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1523                 dbus_message_iter_next(&sub3);
1524                 n++;
1525         }
1526
1527
1528         if (!(i->argv = new0(char*, n+1)))
1529                 return -ENOMEM;
1530
1531         n = 0;
1532         dbus_message_iter_recurse(&sub2, &sub3);
1533         while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1534                 const char *s;
1535
1536                 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1537                 dbus_message_iter_get_basic(&sub3, &s);
1538                 dbus_message_iter_next(&sub3);
1539
1540                 if (!(i->argv[n++] = strdup(s)))
1541                         return -ENOMEM;
1542         }
1543
1544         if (!dbus_message_iter_next(&sub2) ||
1545             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1546             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1547             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1548             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1549             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1550             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1551                 return -EIO;
1552
1553         i->ignore = ignore;
1554         i->start_timestamp = (usec_t) start_timestamp;
1555         i->exit_timestamp = (usec_t) exit_timestamp;
1556         i->pid = (pid_t) pid;
1557         i->code = code;
1558         i->status = status;
1559
1560         return 0;
1561 }
1562
1563 typedef struct UnitStatusInfo {
1564         const char *id;
1565         const char *load_state;
1566         const char *active_state;
1567         const char *sub_state;
1568
1569         const char *description;
1570
1571         const char *path;
1572         const char *default_control_group;
1573
1574         usec_t inactive_exit_timestamp;
1575         usec_t active_enter_timestamp;
1576         usec_t active_exit_timestamp;
1577         usec_t inactive_enter_timestamp;
1578
1579         bool need_daemon_reload;
1580
1581         /* Service */
1582         pid_t main_pid;
1583         pid_t control_pid;
1584         const char *status_text;
1585         bool running:1;
1586 #ifdef HAVE_SYSV_COMPAT
1587         bool is_sysv:1;
1588 #endif
1589
1590         usec_t start_timestamp;
1591         usec_t exit_timestamp;
1592
1593         int exit_code, exit_status;
1594
1595         /* Socket */
1596         unsigned n_accepted;
1597         unsigned n_connections;
1598         bool accept;
1599
1600         /* Device */
1601         const char *sysfs_path;
1602
1603         /* Mount, Automount */
1604         const char *where;
1605
1606         /* Swap */
1607         const char *what;
1608
1609         LIST_HEAD(ExecStatusInfo, exec);
1610 } UnitStatusInfo;
1611
1612 static void print_status_info(UnitStatusInfo *i) {
1613         ExecStatusInfo *p;
1614         const char *on, *off, *ss;
1615         usec_t timestamp;
1616         char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1617         char since2[FORMAT_TIMESTAMP_MAX], *s2;
1618
1619         assert(i);
1620
1621         /* This shows pretty information about a unit. See
1622          * print_property() for a low-level property printer */
1623
1624         printf("%s", strna(i->id));
1625
1626         if (i->description && !streq_ptr(i->id, i->description))
1627                 printf(" - %s", i->description);
1628
1629         printf("\n");
1630
1631         if (streq_ptr(i->load_state, "failed")) {
1632                 on = ansi_highlight(true);
1633                 off = ansi_highlight(false);
1634         } else
1635                 on = off = "";
1636
1637         if (i->path)
1638                 printf("\t  Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1639         else
1640                 printf("\t  Loaded: %s%s%s\n", on, strna(i->load_state), off);
1641
1642         ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1643
1644         if (streq_ptr(i->active_state, "failed")) {
1645                 on = ansi_highlight(true);
1646                 off = ansi_highlight(false);
1647         } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1648                 on = ansi_highlight_green(true);
1649                 off = ansi_highlight_green(false);
1650         } else
1651                 on = off = "";
1652
1653         if (ss)
1654                 printf("\t  Active: %s%s (%s)%s",
1655                        on,
1656                        strna(i->active_state),
1657                        ss,
1658                        off);
1659         else
1660                 printf("\t  Active: %s%s%s",
1661                        on,
1662                        strna(i->active_state),
1663                        off);
1664
1665         timestamp = (streq_ptr(i->active_state, "active")      ||
1666                      streq_ptr(i->active_state, "reloading"))   ? i->active_enter_timestamp :
1667                     (streq_ptr(i->active_state, "inactive")    ||
1668                      streq_ptr(i->active_state, "failed"))      ? i->inactive_enter_timestamp :
1669                     streq_ptr(i->active_state, "activating")    ? i->inactive_exit_timestamp :
1670                                                                   i->active_exit_timestamp;
1671
1672         s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1673         s2 = format_timestamp(since2, sizeof(since2), timestamp);
1674
1675         if (s1)
1676                 printf(" since [%s; %s]\n", s2, s1);
1677         else if (s2)
1678                 printf(" since [%s]\n", s2);
1679         else
1680                 printf("\n");
1681
1682         if (i->sysfs_path)
1683                 printf("\t  Device: %s\n", i->sysfs_path);
1684         else if (i->where)
1685                 printf("\t   Where: %s\n", i->where);
1686         else if (i->what)
1687                 printf("\t    What: %s\n", i->what);
1688
1689         if (i->accept)
1690                 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1691
1692         LIST_FOREACH(exec, p, i->exec) {
1693                 char *t;
1694
1695                 /* Only show exited processes here */
1696                 if (p->code == 0)
1697                         continue;
1698
1699                 t = strv_join(p->argv, " ");
1700                 printf("\t Process: %u (%s, code=%s, ", p->pid, strna(t), sigchld_code_to_string(p->code));
1701                 free(t);
1702
1703                 if (p->code == CLD_EXITED) {
1704                         const char *c;
1705
1706                         printf("status=%i", p->status);
1707
1708 #ifdef HAVE_SYSV_COMPAT
1709                         if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1710 #else
1711                         if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1712 #endif
1713                                 printf("/%s", c);
1714
1715                 } else
1716                         printf("signal=%s", signal_to_string(p->status));
1717                 printf(")\n");
1718
1719                 if (i->main_pid == p->pid &&
1720                     i->start_timestamp == p->start_timestamp &&
1721                     i->exit_timestamp == p->start_timestamp)
1722                         /* Let's not show this twice */
1723                         i->main_pid = 0;
1724
1725                 if (p->pid == i->control_pid)
1726                         i->control_pid = 0;
1727         }
1728
1729         if (i->main_pid > 0 || i->control_pid > 0) {
1730                 printf("\t");
1731
1732                 if (i->main_pid > 0) {
1733                         printf("Main PID: %u", (unsigned) i->main_pid);
1734
1735                         if (i->running) {
1736                                 char *t = NULL;
1737                                 get_process_name(i->main_pid, &t);
1738                                 if (t) {
1739                                         printf(" (%s)", t);
1740                                         free(t);
1741                                 }
1742                         } else if (i->exit_code > 0) {
1743                                 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1744
1745                                 if (i->exit_code == CLD_EXITED) {
1746                                         const char *c;
1747
1748                                         printf("status=%i", i->exit_status);
1749
1750 #ifdef HAVE_SYSV_COMPAT
1751                                         if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1752 #else
1753                                         if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
1754 #endif
1755                                                 printf("/%s", c);
1756
1757                                 } else
1758                                         printf("signal=%s", signal_to_string(i->exit_status));
1759                                 printf(")");
1760                         }
1761                 }
1762
1763                 if (i->main_pid > 0 && i->control_pid > 0)
1764                         printf(";");
1765
1766                 if (i->control_pid > 0) {
1767                         char *t = NULL;
1768
1769                         printf(" Control: %u", (unsigned) i->control_pid);
1770
1771                         get_process_name(i->control_pid, &t);
1772                         if (t) {
1773                                 printf(" (%s)", t);
1774                                 free(t);
1775                         }
1776                 }
1777
1778                 printf("\n");
1779         }
1780
1781         if (i->status_text)
1782                 printf("\t  Status: \"%s\"\n", i->status_text);
1783
1784         if (i->default_control_group) {
1785                 unsigned c;
1786
1787                 printf("\t  CGroup: %s\n", i->default_control_group);
1788
1789                 if ((c = columns()) > 18)
1790                         c -= 18;
1791                 else
1792                         c = 0;
1793
1794                 show_cgroup_by_path(i->default_control_group, "\t\t  ", c);
1795         }
1796
1797         if (i->need_daemon_reload)
1798                 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1799                        ansi_highlight(true),
1800                        ansi_highlight(false),
1801                        arg_session ? "--session" : "--system");
1802 }
1803
1804 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1805
1806         switch (dbus_message_iter_get_arg_type(iter)) {
1807
1808         case DBUS_TYPE_STRING: {
1809                 const char *s;
1810
1811                 dbus_message_iter_get_basic(iter, &s);
1812
1813                 if (s[0]) {
1814                         if (streq(name, "Id"))
1815                                 i->id = s;
1816                         else if (streq(name, "LoadState"))
1817                                 i->load_state = s;
1818                         else if (streq(name, "ActiveState"))
1819                                 i->active_state = s;
1820                         else if (streq(name, "SubState"))
1821                                 i->sub_state = s;
1822                         else if (streq(name, "Description"))
1823                                 i->description = s;
1824                         else if (streq(name, "FragmentPath"))
1825                                 i->path = s;
1826 #ifdef HAVE_SYSV_COMPAT
1827                         else if (streq(name, "SysVPath")) {
1828                                 i->is_sysv = true;
1829                                 i->path = s;
1830                         }
1831 #endif
1832                         else if (streq(name, "DefaultControlGroup"))
1833                                 i->default_control_group = s;
1834                         else if (streq(name, "StatusText"))
1835                                 i->status_text = s;
1836                         else if (streq(name, "SysFSPath"))
1837                                 i->sysfs_path = s;
1838                         else if (streq(name, "Where"))
1839                                 i->where = s;
1840                         else if (streq(name, "What"))
1841                                 i->what = s;
1842                 }
1843
1844                 break;
1845         }
1846
1847         case DBUS_TYPE_BOOLEAN: {
1848                 dbus_bool_t b;
1849
1850                 dbus_message_iter_get_basic(iter, &b);
1851
1852                 if (streq(name, "Accept"))
1853                         i->accept = b;
1854                 else if (streq(name, "NeedDaemonReload"))
1855                         i->need_daemon_reload = b;
1856
1857                 break;
1858         }
1859
1860         case DBUS_TYPE_UINT32: {
1861                 uint32_t u;
1862
1863                 dbus_message_iter_get_basic(iter, &u);
1864
1865                 if (streq(name, "MainPID")) {
1866                         if (u > 0) {
1867                                 i->main_pid = (pid_t) u;
1868                                 i->running = true;
1869                         }
1870                 } else if (streq(name, "ControlPID"))
1871                         i->control_pid = (pid_t) u;
1872                 else if (streq(name, "ExecMainPID")) {
1873                         if (u > 0)
1874                                 i->main_pid = (pid_t) u;
1875                 } else if (streq(name, "NAccepted"))
1876                         i->n_accepted = u;
1877                 else if (streq(name, "NConnections"))
1878                         i->n_connections = u;
1879
1880                 break;
1881         }
1882
1883         case DBUS_TYPE_INT32: {
1884                 int32_t j;
1885
1886                 dbus_message_iter_get_basic(iter, &j);
1887
1888                 if (streq(name, "ExecMainCode"))
1889                         i->exit_code = (int) j;
1890                 else if (streq(name, "ExecMainStatus"))
1891                         i->exit_status = (int) j;
1892
1893                 break;
1894         }
1895
1896         case DBUS_TYPE_UINT64: {
1897                 uint64_t u;
1898
1899                 dbus_message_iter_get_basic(iter, &u);
1900
1901                 if (streq(name, "ExecMainStartTimestamp"))
1902                         i->start_timestamp = (usec_t) u;
1903                 else if (streq(name, "ExecMainExitTimestamp"))
1904                         i->exit_timestamp = (usec_t) u;
1905                 else if (streq(name, "ActiveEnterTimestamp"))
1906                         i->active_enter_timestamp = (usec_t) u;
1907                 else if (streq(name, "InactiveEnterTimestamp"))
1908                         i->inactive_enter_timestamp = (usec_t) u;
1909                 else if (streq(name, "InactiveExitTimestamp"))
1910                         i->inactive_exit_timestamp = (usec_t) u;
1911                 else if (streq(name, "ActiveExitTimestamp"))
1912                         i->active_exit_timestamp = (usec_t) u;
1913
1914                 break;
1915         }
1916
1917         case DBUS_TYPE_ARRAY: {
1918
1919                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
1920                     startswith(name, "Exec")) {
1921                         DBusMessageIter sub;
1922
1923                         dbus_message_iter_recurse(iter, &sub);
1924                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1925                                 ExecStatusInfo *info;
1926                                 int r;
1927
1928                                 if (!(info = new0(ExecStatusInfo, 1)))
1929                                         return -ENOMEM;
1930
1931                                 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
1932                                         free(info);
1933                                         return r;
1934                                 }
1935
1936                                 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
1937
1938                                 dbus_message_iter_next(&sub);
1939                         }
1940                 }
1941
1942                 break;
1943         }
1944         }
1945
1946         return 0;
1947 }
1948
1949 static int print_property(const char *name, DBusMessageIter *iter) {
1950         assert(name);
1951         assert(iter);
1952
1953         /* This is a low-level property printer, see
1954          * print_status_info() for the nicer output */
1955
1956         if (arg_property && !strv_find(arg_property, name))
1957                 return 0;
1958
1959         switch (dbus_message_iter_get_arg_type(iter)) {
1960
1961         case DBUS_TYPE_STRING: {
1962                 const char *s;
1963                 dbus_message_iter_get_basic(iter, &s);
1964
1965                 if (arg_all || s[0])
1966                         printf("%s=%s\n", name, s);
1967
1968                 return 0;
1969         }
1970
1971         case DBUS_TYPE_BOOLEAN: {
1972                 dbus_bool_t b;
1973                 dbus_message_iter_get_basic(iter, &b);
1974                 printf("%s=%s\n", name, yes_no(b));
1975
1976                 return 0;
1977         }
1978
1979         case DBUS_TYPE_UINT64: {
1980                 uint64_t u;
1981                 dbus_message_iter_get_basic(iter, &u);
1982
1983                 /* Yes, heuristics! But we can change this check
1984                  * should it turn out to not be sufficient */
1985
1986                 if (strstr(name, "Timestamp")) {
1987                         char timestamp[FORMAT_TIMESTAMP_MAX], *t;
1988
1989                         if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
1990                                 printf("%s=%s\n", name, strempty(t));
1991                 } else if (strstr(name, "USec")) {
1992                         char timespan[FORMAT_TIMESPAN_MAX];
1993
1994                         printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
1995                 } else
1996                         printf("%s=%llu\n", name, (unsigned long long) u);
1997
1998                 return 0;
1999         }
2000
2001         case DBUS_TYPE_UINT32: {
2002                 uint32_t u;
2003                 dbus_message_iter_get_basic(iter, &u);
2004
2005                 if (strstr(name, "UMask") || strstr(name, "Mode"))
2006                         printf("%s=%04o\n", name, u);
2007                 else
2008                         printf("%s=%u\n", name, (unsigned) u);
2009
2010                 return 0;
2011         }
2012
2013         case DBUS_TYPE_INT32: {
2014                 int32_t i;
2015                 dbus_message_iter_get_basic(iter, &i);
2016
2017                 printf("%s=%i\n", name, (int) i);
2018                 return 0;
2019         }
2020
2021         case DBUS_TYPE_DOUBLE: {
2022                 double d;
2023                 dbus_message_iter_get_basic(iter, &d);
2024
2025                 printf("%s=%g\n", name, d);
2026                 return 0;
2027         }
2028
2029         case DBUS_TYPE_STRUCT: {
2030                 DBusMessageIter sub;
2031                 dbus_message_iter_recurse(iter, &sub);
2032
2033                 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2034                         uint32_t u;
2035
2036                         dbus_message_iter_get_basic(&sub, &u);
2037
2038                         if (u)
2039                                 printf("%s=%u\n", name, (unsigned) u);
2040                         else if (arg_all)
2041                                 printf("%s=\n", name);
2042
2043                         return 0;
2044                 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2045                         const char *s;
2046
2047                         dbus_message_iter_get_basic(&sub, &s);
2048
2049                         if (arg_all || s[0])
2050                                 printf("%s=%s\n", name, s);
2051
2052                         return 0;
2053                 }
2054
2055                 break;
2056         }
2057
2058         case DBUS_TYPE_ARRAY:
2059
2060                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2061                         DBusMessageIter sub;
2062                         bool space = false;
2063
2064                         dbus_message_iter_recurse(iter, &sub);
2065                         if (arg_all ||
2066                             dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2067                                 printf("%s=", name);
2068
2069                                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2070                                         const char *s;
2071
2072                                         assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2073                                         dbus_message_iter_get_basic(&sub, &s);
2074                                         printf("%s%s", space ? " " : "", s);
2075
2076                                         space = true;
2077                                         dbus_message_iter_next(&sub);
2078                                 }
2079
2080                                 puts("");
2081                         }
2082
2083                         return 0;
2084
2085                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2086                         DBusMessageIter sub;
2087
2088                         dbus_message_iter_recurse(iter, &sub);
2089                         if (arg_all ||
2090                             dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2091                                 printf("%s=", name);
2092
2093                                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2094                                         uint8_t u;
2095
2096                                         assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2097                                         dbus_message_iter_get_basic(&sub, &u);
2098                                         printf("%02x", u);
2099
2100                                         dbus_message_iter_next(&sub);
2101                                 }
2102
2103                                 puts("");
2104                         }
2105
2106                         return 0;
2107
2108                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2109                         DBusMessageIter sub, sub2;
2110
2111                         dbus_message_iter_recurse(iter, &sub);
2112                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2113                                 const char *type, *path;
2114
2115                                 dbus_message_iter_recurse(&sub, &sub2);
2116
2117                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2118                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2119                                         printf("%s=%s\n", type, path);
2120
2121                                 dbus_message_iter_next(&sub);
2122                         }
2123
2124                         return 0;
2125
2126                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2127                         DBusMessageIter sub, sub2;
2128
2129                         dbus_message_iter_recurse(iter, &sub);
2130                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2131                                 const char *base;
2132                                 uint64_t value, next_elapse;
2133
2134                                 dbus_message_iter_recurse(&sub, &sub2);
2135
2136                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2137                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2138                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2139                                         char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2140
2141                                         printf("%s={ value=%s ; next_elapse=%s }\n",
2142                                                base,
2143                                                format_timespan(timespan1, sizeof(timespan1), value),
2144                                                format_timespan(timespan2, sizeof(timespan2), next_elapse));
2145                                 }
2146
2147                                 dbus_message_iter_next(&sub);
2148                         }
2149
2150                         return 0;
2151
2152                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2153                         DBusMessageIter sub;
2154
2155                         dbus_message_iter_recurse(iter, &sub);
2156                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2157                                 ExecStatusInfo info;
2158
2159                                 zero(info);
2160                                 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2161                                         char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2162                                         char *t;
2163
2164                                         t = strv_join(info.argv, " ");
2165
2166                                         printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2167                                                name,
2168                                                strna(info.path),
2169                                                strna(t),
2170                                                yes_no(info.ignore),
2171                                                strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2172                                                strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2173                                                (unsigned) info. pid,
2174                                                sigchld_code_to_string(info.code),
2175                                                info.status,
2176                                                info.code == CLD_EXITED ? "" : "/",
2177                                                strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2178
2179                                         free(t);
2180                                 }
2181
2182                                 free(info.path);
2183                                 strv_free(info.argv);
2184
2185                                 dbus_message_iter_next(&sub);
2186                         }
2187
2188                         return 0;
2189                 }
2190
2191                 break;
2192         }
2193
2194         if (arg_all)
2195                 printf("%s=[unprintable]\n", name);
2196
2197         return 0;
2198 }
2199
2200 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2201         DBusMessage *m = NULL, *reply = NULL;
2202         const char *interface = "";
2203         int r;
2204         DBusError error;
2205         DBusMessageIter iter, sub, sub2, sub3;
2206         UnitStatusInfo info;
2207         ExecStatusInfo *p;
2208
2209         assert(bus);
2210         assert(path);
2211         assert(new_line);
2212
2213         zero(info);
2214         dbus_error_init(&error);
2215
2216         if (!(m = dbus_message_new_method_call(
2217                               "org.freedesktop.systemd1",
2218                               path,
2219                               "org.freedesktop.DBus.Properties",
2220                               "GetAll"))) {
2221                 log_error("Could not allocate message.");
2222                 r = -ENOMEM;
2223                 goto finish;
2224         }
2225
2226         if (!dbus_message_append_args(m,
2227                                       DBUS_TYPE_STRING, &interface,
2228                                       DBUS_TYPE_INVALID)) {
2229                 log_error("Could not append arguments to message.");
2230                 r = -ENOMEM;
2231                 goto finish;
2232         }
2233
2234         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2235                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2236                 r = -EIO;
2237                 goto finish;
2238         }
2239
2240         if (!dbus_message_iter_init(reply, &iter) ||
2241             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2242             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY)  {
2243                 log_error("Failed to parse reply.");
2244                 r = -EIO;
2245                 goto finish;
2246         }
2247
2248         dbus_message_iter_recurse(&iter, &sub);
2249
2250         if (*new_line)
2251                 printf("\n");
2252
2253         *new_line = true;
2254
2255         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2256                 const char *name;
2257
2258                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2259                         log_error("Failed to parse reply.");
2260                         r = -EIO;
2261                         goto finish;
2262                 }
2263
2264                 dbus_message_iter_recurse(&sub, &sub2);
2265
2266                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2267                         log_error("Failed to parse reply.");
2268                         r = -EIO;
2269                         goto finish;
2270                 }
2271
2272                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT)  {
2273                         log_error("Failed to parse reply.");
2274                         r = -EIO;
2275                         goto finish;
2276                 }
2277
2278                 dbus_message_iter_recurse(&sub2, &sub3);
2279
2280                 if (show_properties)
2281                         r = print_property(name, &sub3);
2282                 else
2283                         r = status_property(name, &sub3, &info);
2284
2285                 if (r < 0) {
2286                         log_error("Failed to parse reply.");
2287                         r = -EIO;
2288                         goto finish;
2289                 }
2290
2291                 dbus_message_iter_next(&sub);
2292         }
2293
2294         r = 0;
2295
2296         if (!show_properties)
2297                 print_status_info(&info);
2298
2299         if (!streq_ptr(info.active_state, "active") &&
2300             !streq_ptr(info.active_state, "reloading"))
2301                 /* According to LSB: "program not running" */
2302                 r = 3;
2303
2304         while ((p = info.exec)) {
2305                 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2306                 exec_status_info_free(p);
2307         }
2308
2309 finish:
2310         if (m)
2311                 dbus_message_unref(m);
2312
2313         if (reply)
2314                 dbus_message_unref(reply);
2315
2316         dbus_error_free(&error);
2317
2318         return r;
2319 }
2320
2321 static int show(DBusConnection *bus, char **args, unsigned n) {
2322         DBusMessage *m = NULL, *reply = NULL;
2323         int r, ret = 0;
2324         DBusError error;
2325         unsigned i;
2326         bool show_properties, new_line = false;
2327
2328         assert(bus);
2329         assert(args);
2330
2331         dbus_error_init(&error);
2332
2333         show_properties = !streq(args[0], "status");
2334
2335         if (show_properties && n <= 1) {
2336                 /* If not argument is specified inspect the manager
2337                  * itself */
2338
2339                 ret = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2340                 goto finish;
2341         }
2342
2343         for (i = 1; i < n; i++) {
2344                 const char *path = NULL;
2345                 uint32_t id;
2346
2347                 if (safe_atou32(args[i], &id) < 0) {
2348
2349                         /* Interpret as unit name */
2350
2351                         if (!(m = dbus_message_new_method_call(
2352                                               "org.freedesktop.systemd1",
2353                                               "/org/freedesktop/systemd1",
2354                                               "org.freedesktop.systemd1.Manager",
2355                                               "LoadUnit"))) {
2356                                 log_error("Could not allocate message.");
2357                                 ret = -ENOMEM;
2358                                 goto finish;
2359                         }
2360
2361                         if (!dbus_message_append_args(m,
2362                                                       DBUS_TYPE_STRING, &args[i],
2363                                                       DBUS_TYPE_INVALID)) {
2364                                 log_error("Could not append arguments to message.");
2365                                 ret = -ENOMEM;
2366                                 goto finish;
2367                         }
2368
2369                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2370
2371                                 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2372                                         log_error("Failed to issue method call: %s", bus_error_message(&error));
2373                                         ret = -EIO;
2374                                         goto finish;
2375                                 }
2376
2377                                 dbus_error_free(&error);
2378
2379                                 dbus_message_unref(m);
2380                                 if (!(m = dbus_message_new_method_call(
2381                                                       "org.freedesktop.systemd1",
2382                                                       "/org/freedesktop/systemd1",
2383                                                       "org.freedesktop.systemd1.Manager",
2384                                                       "GetUnit"))) {
2385                                         log_error("Could not allocate message.");
2386                                         ret = -ENOMEM;
2387                                         goto finish;
2388                                 }
2389
2390                                 if (!dbus_message_append_args(m,
2391                                                               DBUS_TYPE_STRING, &args[i],
2392                                                               DBUS_TYPE_INVALID)) {
2393                                         log_error("Could not append arguments to message.");
2394                                         ret = -ENOMEM;
2395                                         goto finish;
2396                                 }
2397
2398                                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2399                                         log_error("Failed to issue method call: %s", bus_error_message(&error));
2400
2401                                         if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2402                                                 ret = 4; /* According to LSB: "program or service status is unknown" */
2403                                         else
2404                                                 ret = -EIO;
2405                                         goto finish;
2406                                 }
2407                         }
2408
2409                 } else if (show_properties) {
2410
2411                         /* Interpret as job id */
2412
2413                         if (!(m = dbus_message_new_method_call(
2414                                               "org.freedesktop.systemd1",
2415                                               "/org/freedesktop/systemd1",
2416                                               "org.freedesktop.systemd1.Manager",
2417                                               "GetJob"))) {
2418                                 log_error("Could not allocate message.");
2419                                 ret = -ENOMEM;
2420                                 goto finish;
2421                         }
2422
2423                         if (!dbus_message_append_args(m,
2424                                                       DBUS_TYPE_UINT32, &id,
2425                                                       DBUS_TYPE_INVALID)) {
2426                                 log_error("Could not append arguments to message.");
2427                                 ret = -ENOMEM;
2428                                 goto finish;
2429                         }
2430
2431                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2432                                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2433                                 ret = -EIO;
2434                                 goto finish;
2435                         }
2436                 } else {
2437
2438                         /* Interpret as PID */
2439
2440                         if (!(m = dbus_message_new_method_call(
2441                                               "org.freedesktop.systemd1",
2442                                               "/org/freedesktop/systemd1",
2443                                               "org.freedesktop.systemd1.Manager",
2444                                               "GetUnitByPID"))) {
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                 }
2464
2465                 if (!dbus_message_get_args(reply, &error,
2466                                            DBUS_TYPE_OBJECT_PATH, &path,
2467                                            DBUS_TYPE_INVALID)) {
2468                         log_error("Failed to parse reply: %s", bus_error_message(&error));
2469                         ret = -EIO;
2470                         goto finish;
2471                 }
2472
2473                 if ((r = show_one(bus, path, show_properties, &new_line)) != 0)
2474                         ret = r;
2475
2476                 dbus_message_unref(m);
2477                 dbus_message_unref(reply);
2478                 m = reply = NULL;
2479         }
2480
2481 finish:
2482         if (m)
2483                 dbus_message_unref(m);
2484
2485         if (reply)
2486                 dbus_message_unref(reply);
2487
2488         dbus_error_free(&error);
2489
2490         return ret;
2491 }
2492
2493 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2494         DBusError error;
2495         DBusMessage *m = NULL, *reply = NULL;
2496
2497         assert(connection);
2498         assert(message);
2499
2500         dbus_error_init(&error);
2501
2502         log_debug("Got D-Bus request: %s.%s() on %s",
2503                   dbus_message_get_interface(message),
2504                   dbus_message_get_member(message),
2505                   dbus_message_get_path(message));
2506
2507         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2508                 log_error("Warning! D-Bus connection terminated.");
2509                 dbus_connection_close(connection);
2510
2511         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2512                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2513                 const char *id, *path;
2514
2515                 if (!dbus_message_get_args(message, &error,
2516                                            DBUS_TYPE_STRING, &id,
2517                                            DBUS_TYPE_OBJECT_PATH, &path,
2518                                            DBUS_TYPE_INVALID))
2519                         log_error("Failed to parse message: %s", bus_error_message(&error));
2520                 else if (streq(dbus_message_get_member(message), "UnitNew"))
2521                         printf("Unit %s added.\n", id);
2522                 else
2523                         printf("Unit %s removed.\n", id);
2524
2525         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2526                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2527                 uint32_t id;
2528                 const char *path;
2529
2530                 if (!dbus_message_get_args(message, &error,
2531                                            DBUS_TYPE_UINT32, &id,
2532                                            DBUS_TYPE_OBJECT_PATH, &path,
2533                                            DBUS_TYPE_INVALID))
2534                         log_error("Failed to parse message: %s", bus_error_message(&error));
2535                 else if (streq(dbus_message_get_member(message), "JobNew"))
2536                         printf("Job %u added.\n", id);
2537                 else
2538                         printf("Job %u removed.\n", id);
2539
2540
2541         } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2542
2543                 const char *path, *interface, *property = "Id";
2544                 DBusMessageIter iter, sub;
2545
2546                 path = dbus_message_get_path(message);
2547
2548                 if (!dbus_message_get_args(message, &error,
2549                                           DBUS_TYPE_STRING, &interface,
2550                                           DBUS_TYPE_INVALID)) {
2551                         log_error("Failed to parse message: %s", bus_error_message(&error));
2552                         goto finish;
2553                 }
2554
2555                 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2556                     !streq(interface, "org.freedesktop.systemd1.Unit"))
2557                         goto finish;
2558
2559                 if (!(m = dbus_message_new_method_call(
2560                               "org.freedesktop.systemd1",
2561                               path,
2562                               "org.freedesktop.DBus.Properties",
2563                               "Get"))) {
2564                         log_error("Could not allocate message.");
2565                         goto oom;
2566                 }
2567
2568                 if (!dbus_message_append_args(m,
2569                                               DBUS_TYPE_STRING, &interface,
2570                                               DBUS_TYPE_STRING, &property,
2571                                               DBUS_TYPE_INVALID)) {
2572                         log_error("Could not append arguments to message.");
2573                         goto finish;
2574                 }
2575
2576                 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2577                         log_error("Failed to issue method call: %s", bus_error_message(&error));
2578                         goto finish;
2579                 }
2580
2581                 if (!dbus_message_iter_init(reply, &iter) ||
2582                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
2583                         log_error("Failed to parse reply.");
2584                         goto finish;
2585                 }
2586
2587                 dbus_message_iter_recurse(&iter, &sub);
2588
2589                 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2590                         const char *id;
2591
2592                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
2593                                 log_error("Failed to parse reply.");
2594                                 goto finish;
2595                         }
2596
2597                         dbus_message_iter_get_basic(&sub, &id);
2598                         printf("Unit %s changed.\n", id);
2599                 } else {
2600                         uint32_t id;
2601
2602                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32)  {
2603                                 log_error("Failed to parse reply.");
2604                                 goto finish;
2605                         }
2606
2607                         dbus_message_iter_get_basic(&sub, &id);
2608                         printf("Job %u changed.\n", id);
2609                 }
2610         }
2611
2612 finish:
2613         if (m)
2614                 dbus_message_unref(m);
2615
2616         if (reply)
2617                 dbus_message_unref(reply);
2618
2619         dbus_error_free(&error);
2620         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2621
2622 oom:
2623         if (m)
2624                 dbus_message_unref(m);
2625
2626         if (reply)
2627                 dbus_message_unref(reply);
2628
2629         dbus_error_free(&error);
2630         return DBUS_HANDLER_RESULT_NEED_MEMORY;
2631 }
2632
2633 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2634         DBusMessage *m = NULL, *reply = NULL;
2635         DBusError error;
2636         int r;
2637
2638         dbus_error_init(&error);
2639
2640         if (!private_bus) {
2641                 dbus_bus_add_match(bus,
2642                                    "type='signal',"
2643                                    "sender='org.freedesktop.systemd1',"
2644                                    "interface='org.freedesktop.systemd1.Manager',"
2645                                    "path='/org/freedesktop/systemd1'",
2646                                    &error);
2647
2648                 if (dbus_error_is_set(&error)) {
2649                         log_error("Failed to add match: %s", bus_error_message(&error));
2650                         r = -EIO;
2651                         goto finish;
2652                 }
2653
2654                 dbus_bus_add_match(bus,
2655                                    "type='signal',"
2656                                    "sender='org.freedesktop.systemd1',"
2657                                    "interface='org.freedesktop.DBus.Properties',"
2658                                    "member='PropertiesChanged'",
2659                                    &error);
2660
2661                 if (dbus_error_is_set(&error)) {
2662                         log_error("Failed to add match: %s", bus_error_message(&error));
2663                         r = -EIO;
2664                         goto finish;
2665                 }
2666         }
2667
2668         if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2669                 log_error("Failed to add filter.");
2670                 r = -ENOMEM;
2671                 goto finish;
2672         }
2673
2674         if (!(m = dbus_message_new_method_call(
2675                               "org.freedesktop.systemd1",
2676                               "/org/freedesktop/systemd1",
2677                               "org.freedesktop.systemd1.Manager",
2678                               "Subscribe"))) {
2679                 log_error("Could not allocate message.");
2680                 r = -ENOMEM;
2681                 goto finish;
2682         }
2683
2684         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2685                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2686                 r = -EIO;
2687                 goto finish;
2688         }
2689
2690         while (dbus_connection_read_write_dispatch(bus, -1))
2691                 ;
2692
2693         r = 0;
2694
2695 finish:
2696
2697         /* This is slightly dirty, since we don't undo the filter or the matches. */
2698
2699         if (m)
2700                 dbus_message_unref(m);
2701
2702         if (reply)
2703                 dbus_message_unref(reply);
2704
2705         dbus_error_free(&error);
2706
2707         return r;
2708 }
2709
2710 static int dump(DBusConnection *bus, char **args, unsigned n) {
2711         DBusMessage *m = NULL, *reply = NULL;
2712         DBusError error;
2713         int r;
2714         const char *text;
2715
2716         dbus_error_init(&error);
2717
2718         if (!(m = dbus_message_new_method_call(
2719                               "org.freedesktop.systemd1",
2720                               "/org/freedesktop/systemd1",
2721                               "org.freedesktop.systemd1.Manager",
2722                               "Dump"))) {
2723                 log_error("Could not allocate message.");
2724                 return -ENOMEM;
2725         }
2726
2727         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2728                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2729                 r = -EIO;
2730                 goto finish;
2731         }
2732
2733         if (!dbus_message_get_args(reply, &error,
2734                                    DBUS_TYPE_STRING, &text,
2735                                    DBUS_TYPE_INVALID)) {
2736                 log_error("Failed to parse reply: %s", bus_error_message(&error));
2737                 r = -EIO;
2738                 goto finish;
2739         }
2740
2741         fputs(text, stdout);
2742
2743         r = 0;
2744
2745 finish:
2746         if (m)
2747                 dbus_message_unref(m);
2748
2749         if (reply)
2750                 dbus_message_unref(reply);
2751
2752         dbus_error_free(&error);
2753
2754         return r;
2755 }
2756
2757 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2758         DBusMessage *m = NULL, *reply = NULL;
2759         DBusError error;
2760         int r;
2761         const char *name = "", *path, *id;
2762         dbus_bool_t cleanup = FALSE;
2763         DBusMessageIter iter, sub;
2764         const char
2765                 *interface = "org.freedesktop.systemd1.Unit",
2766                 *property = "Id";
2767
2768         dbus_error_init(&error);
2769
2770         if (!(m = dbus_message_new_method_call(
2771                               "org.freedesktop.systemd1",
2772                               "/org/freedesktop/systemd1",
2773                               "org.freedesktop.systemd1.Manager",
2774                               "CreateSnapshot"))) {
2775                 log_error("Could not allocate message.");
2776                 return -ENOMEM;
2777         }
2778
2779         if (n > 1)
2780                 name = args[1];
2781
2782         if (!dbus_message_append_args(m,
2783                                       DBUS_TYPE_STRING, &name,
2784                                       DBUS_TYPE_BOOLEAN, &cleanup,
2785                                       DBUS_TYPE_INVALID)) {
2786                 log_error("Could not append arguments to message.");
2787                 r = -ENOMEM;
2788                 goto finish;
2789         }
2790
2791         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2792                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2793                 r = -EIO;
2794                 goto finish;
2795         }
2796
2797         if (!dbus_message_get_args(reply, &error,
2798                                    DBUS_TYPE_OBJECT_PATH, &path,
2799                                    DBUS_TYPE_INVALID)) {
2800                 log_error("Failed to parse reply: %s", bus_error_message(&error));
2801                 r = -EIO;
2802                 goto finish;
2803         }
2804
2805         dbus_message_unref(m);
2806         if (!(m = dbus_message_new_method_call(
2807                               "org.freedesktop.systemd1",
2808                               path,
2809                               "org.freedesktop.DBus.Properties",
2810                               "Get"))) {
2811                 log_error("Could not allocate message.");
2812                 return -ENOMEM;
2813         }
2814
2815         if (!dbus_message_append_args(m,
2816                                       DBUS_TYPE_STRING, &interface,
2817                                       DBUS_TYPE_STRING, &property,
2818                                       DBUS_TYPE_INVALID)) {
2819                 log_error("Could not append arguments to message.");
2820                 r = -ENOMEM;
2821                 goto finish;
2822         }
2823
2824         dbus_message_unref(reply);
2825         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2826                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2827                 r = -EIO;
2828                 goto finish;
2829         }
2830
2831         if (!dbus_message_iter_init(reply, &iter) ||
2832             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
2833                 log_error("Failed to parse reply.");
2834                 r = -EIO;
2835                 goto finish;
2836         }
2837
2838         dbus_message_iter_recurse(&iter, &sub);
2839
2840         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
2841                 log_error("Failed to parse reply.");
2842                 r = -EIO;
2843                 goto finish;
2844         }
2845
2846         dbus_message_iter_get_basic(&sub, &id);
2847
2848         if (!arg_quiet)
2849                 puts(id);
2850         r = 0;
2851
2852 finish:
2853         if (m)
2854                 dbus_message_unref(m);
2855
2856         if (reply)
2857                 dbus_message_unref(reply);
2858
2859         dbus_error_free(&error);
2860
2861         return r;
2862 }
2863
2864 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2865         DBusMessage *m = NULL, *reply = NULL;
2866         int r;
2867         DBusError error;
2868         unsigned i;
2869
2870         assert(bus);
2871         assert(args);
2872
2873         dbus_error_init(&error);
2874
2875         for (i = 1; i < n; i++) {
2876                 const char *path = NULL;
2877
2878                 if (!(m = dbus_message_new_method_call(
2879                                       "org.freedesktop.systemd1",
2880                                       "/org/freedesktop/systemd1",
2881                                       "org.freedesktop.systemd1.Manager",
2882                                       "GetUnit"))) {
2883                         log_error("Could not allocate message.");
2884                         r = -ENOMEM;
2885                         goto finish;
2886                 }
2887
2888                 if (!dbus_message_append_args(m,
2889                                               DBUS_TYPE_STRING, &args[i],
2890                                               DBUS_TYPE_INVALID)) {
2891                         log_error("Could not append arguments to message.");
2892                         r = -ENOMEM;
2893                         goto finish;
2894                 }
2895
2896                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2897                         log_error("Failed to issue method call: %s", bus_error_message(&error));
2898                         r = -EIO;
2899                         goto finish;
2900                 }
2901
2902                 if (!dbus_message_get_args(reply, &error,
2903                                            DBUS_TYPE_OBJECT_PATH, &path,
2904                                            DBUS_TYPE_INVALID)) {
2905                         log_error("Failed to parse reply: %s", bus_error_message(&error));
2906                         r = -EIO;
2907                         goto finish;
2908                 }
2909
2910                 dbus_message_unref(m);
2911                 if (!(m = dbus_message_new_method_call(
2912                                       "org.freedesktop.systemd1",
2913                                       path,
2914                                       "org.freedesktop.systemd1.Snapshot",
2915                                       "Remove"))) {
2916                         log_error("Could not allocate message.");
2917                         r = -ENOMEM;
2918                         goto finish;
2919                 }
2920
2921                 dbus_message_unref(reply);
2922                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2923                         log_error("Failed to issue method call: %s", bus_error_message(&error));
2924                         r = -EIO;
2925                         goto finish;
2926                 }
2927
2928                 dbus_message_unref(m);
2929                 dbus_message_unref(reply);
2930                 m = reply = NULL;
2931         }
2932
2933         r = 0;
2934
2935 finish:
2936         if (m)
2937                 dbus_message_unref(m);
2938
2939         if (reply)
2940                 dbus_message_unref(reply);
2941
2942         dbus_error_free(&error);
2943
2944         return r;
2945 }
2946
2947 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2948         DBusMessage *m = NULL, *reply = NULL;
2949         DBusError error;
2950         int r;
2951         const char *method;
2952
2953         dbus_error_init(&error);
2954
2955         if (arg_action == ACTION_RELOAD)
2956                 method = "Reload";
2957         else if (arg_action == ACTION_REEXEC)
2958                 method = "Reexecute";
2959         else {
2960                 assert(arg_action == ACTION_SYSTEMCTL);
2961
2962                 method =
2963                         streq(args[0], "clear-jobs")        ||
2964                         streq(args[0], "cancel")            ? "ClearJobs" :
2965                         streq(args[0], "daemon-reexec")     ? "Reexecute" :
2966                         streq(args[0], "reset-failed")      ? "ResetFailed" :
2967                         streq(args[0], "daemon-exit")       ? "Exit" :
2968                                                               "Reload";
2969         }
2970
2971         if (!(m = dbus_message_new_method_call(
2972                               "org.freedesktop.systemd1",
2973                               "/org/freedesktop/systemd1",
2974                               "org.freedesktop.systemd1.Manager",
2975                               method))) {
2976                 log_error("Could not allocate message.");
2977                 return -ENOMEM;
2978         }
2979
2980         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2981
2982                 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
2983                         /* There's always a fallback possible for
2984                          * legacy actions. */
2985                         r = -EADDRNOTAVAIL;
2986                         goto finish;
2987                 }
2988
2989                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2990                 r = -EIO;
2991                 goto finish;
2992         }
2993
2994         r = 0;
2995
2996 finish:
2997         if (m)
2998                 dbus_message_unref(m);
2999
3000         if (reply)
3001                 dbus_message_unref(reply);
3002
3003         dbus_error_free(&error);
3004
3005         return r;
3006 }
3007
3008 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3009         DBusMessage *m = NULL, *reply = NULL;
3010         unsigned i;
3011         int r;
3012         DBusError error;
3013
3014         assert(bus);
3015         dbus_error_init(&error);
3016
3017         if (n <= 1)
3018                 return daemon_reload(bus, args, n);
3019
3020         for (i = 1; i < n; i++) {
3021
3022                 if (!(m = dbus_message_new_method_call(
3023                                       "org.freedesktop.systemd1",
3024                                       "/org/freedesktop/systemd1",
3025                                       "org.freedesktop.systemd1.Manager",
3026                                       "ResetFailedUnit"))) {
3027                         log_error("Could not allocate message.");
3028                         r = -ENOMEM;
3029                         goto finish;
3030                 }
3031
3032                 if (!dbus_message_append_args(m,
3033                                               DBUS_TYPE_STRING, args + i,
3034                                               DBUS_TYPE_INVALID)) {
3035                         log_error("Could not append arguments to message.");
3036                         r = -ENOMEM;
3037                         goto finish;
3038                 }
3039
3040                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3041                         log_error("Failed to issue method call: %s", bus_error_message(&error));
3042                         r = -EIO;
3043                         goto finish;
3044                 }
3045
3046                 dbus_message_unref(m);
3047                 dbus_message_unref(reply);
3048                 m = reply = NULL;
3049         }
3050
3051         r = 0;
3052
3053 finish:
3054         if (m)
3055                 dbus_message_unref(m);
3056
3057         if (reply)
3058                 dbus_message_unref(reply);
3059
3060         dbus_error_free(&error);
3061
3062         return r;
3063 }
3064
3065 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3066         DBusMessage *m = NULL, *reply = NULL;
3067         DBusError error;
3068         DBusMessageIter iter, sub, sub2;
3069         int r;
3070         const char
3071                 *interface = "org.freedesktop.systemd1.Manager",
3072                 *property = "Environment";
3073
3074         dbus_error_init(&error);
3075
3076         if (!(m = dbus_message_new_method_call(
3077                               "org.freedesktop.systemd1",
3078                               "/org/freedesktop/systemd1",
3079                               "org.freedesktop.DBus.Properties",
3080                               "Get"))) {
3081                 log_error("Could not allocate message.");
3082                 return -ENOMEM;
3083         }
3084
3085         if (!dbus_message_append_args(m,
3086                                       DBUS_TYPE_STRING, &interface,
3087                                       DBUS_TYPE_STRING, &property,
3088                                       DBUS_TYPE_INVALID)) {
3089                 log_error("Could not append arguments to message.");
3090                 r = -ENOMEM;
3091                 goto finish;
3092         }
3093
3094         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3095                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3096                 r = -EIO;
3097                 goto finish;
3098         }
3099
3100         if (!dbus_message_iter_init(reply, &iter) ||
3101             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
3102                 log_error("Failed to parse reply.");
3103                 r = -EIO;
3104                 goto finish;
3105         }
3106
3107         dbus_message_iter_recurse(&iter, &sub);
3108
3109         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3110             dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING)  {
3111                 log_error("Failed to parse reply.");
3112                 r = -EIO;
3113                 goto finish;
3114         }
3115
3116         dbus_message_iter_recurse(&sub, &sub2);
3117
3118         while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3119                 const char *text;
3120
3121                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3122                         log_error("Failed to parse reply.");
3123                         r = -EIO;
3124                         goto finish;
3125                 }
3126
3127                 dbus_message_iter_get_basic(&sub2, &text);
3128                 printf("%s\n", text);
3129
3130                 dbus_message_iter_next(&sub2);
3131         }
3132
3133         r = 0;
3134
3135 finish:
3136         if (m)
3137                 dbus_message_unref(m);
3138
3139         if (reply)
3140                 dbus_message_unref(reply);
3141
3142         dbus_error_free(&error);
3143
3144         return r;
3145 }
3146
3147 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3148         DBusMessage *m = NULL, *reply = NULL;
3149         DBusError error;
3150         int r;
3151         const char *method;
3152         DBusMessageIter iter, sub;
3153         unsigned i;
3154
3155         dbus_error_init(&error);
3156
3157         method = streq(args[0], "set-environment")
3158                 ? "SetEnvironment"
3159                 : "UnsetEnvironment";
3160
3161         if (!(m = dbus_message_new_method_call(
3162                               "org.freedesktop.systemd1",
3163                               "/org/freedesktop/systemd1",
3164                               "org.freedesktop.systemd1.Manager",
3165                               method))) {
3166
3167                 log_error("Could not allocate message.");
3168                 return -ENOMEM;
3169         }
3170
3171         dbus_message_iter_init_append(m, &iter);
3172
3173         if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3174                 log_error("Could not append arguments to message.");
3175                 r = -ENOMEM;
3176                 goto finish;
3177         }
3178
3179         for (i = 1; i < n; i++)
3180                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3181                         log_error("Could not append arguments to message.");
3182                         r = -ENOMEM;
3183                         goto finish;
3184                 }
3185
3186         if (!dbus_message_iter_close_container(&iter, &sub)) {
3187                 log_error("Could not append arguments to message.");
3188                 r = -ENOMEM;
3189                 goto finish;
3190         }
3191
3192         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3193                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3194                 r = -EIO;
3195                 goto finish;
3196         }
3197
3198         r = 0;
3199
3200 finish:
3201         if (m)
3202                 dbus_message_unref(m);
3203
3204         if (reply)
3205                 dbus_message_unref(reply);
3206
3207         dbus_error_free(&error);
3208
3209         return r;
3210 }
3211
3212 typedef struct {
3213         char *name;
3214         char *path;
3215
3216         char **aliases;
3217         char **wanted_by;
3218 } InstallInfo;
3219
3220 static Hashmap *will_install = NULL, *have_installed = NULL;
3221 static Set *remove_symlinks_to = NULL;
3222
3223 static void install_info_free(InstallInfo *i) {
3224         assert(i);
3225
3226         free(i->name);
3227         free(i->path);
3228         strv_free(i->aliases);
3229         strv_free(i->wanted_by);
3230         free(i);
3231 }
3232
3233 static void install_info_hashmap_free(Hashmap *m) {
3234         InstallInfo *i;
3235
3236         while ((i = hashmap_steal_first(m)))
3237                 install_info_free(i);
3238
3239         hashmap_free(m);
3240 }
3241
3242 static int install_info_add(const char *name) {
3243         InstallInfo *i;
3244         int r;
3245
3246         assert(will_install);
3247
3248         if (!unit_name_is_valid_no_type(name)) {
3249                 log_warning("Unit name %s is not a valid unit name.", name);
3250                 return -EINVAL;
3251         }
3252
3253         if (hashmap_get(have_installed, name) ||
3254             hashmap_get(will_install, name))
3255                 return 0;
3256
3257         if (!(i = new0(InstallInfo, 1))) {
3258                 r = -ENOMEM;
3259                 goto fail;
3260         }
3261
3262         if (!(i->name = strdup(name))) {
3263                 r = -ENOMEM;
3264                 goto fail;
3265         }
3266
3267         if ((r = hashmap_put(will_install, i->name, i)) < 0)
3268                 goto fail;
3269
3270         return 0;
3271
3272 fail:
3273         if (i)
3274                 install_info_free(i);
3275
3276         return r;
3277 }
3278
3279 static int config_parse_also(
3280                 const char *filename,
3281                 unsigned line,
3282                 const char *section,
3283                 const char *lvalue,
3284                 const char *rvalue,
3285                 void *data,
3286                 void *userdata) {
3287
3288         char *w;
3289         size_t l;
3290         char *state;
3291
3292         assert(filename);
3293         assert(lvalue);
3294         assert(rvalue);
3295
3296         FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3297                 char *n;
3298                 int r;
3299
3300                 if (!(n = strndup(w, l)))
3301                         return -ENOMEM;
3302
3303                 if ((r = install_info_add(n)) < 0) {
3304                         log_warning("Cannot install unit %s: %s", n, strerror(-r));
3305                         free(n);
3306                         return r;
3307                 }
3308
3309                 free(n);
3310         }
3311
3312         return 0;
3313 }
3314
3315 static int mark_symlink_for_removal(const char *p) {
3316         char *n;
3317         int r;
3318
3319         assert(p);
3320         assert(path_is_absolute(p));
3321
3322         if (!remove_symlinks_to)
3323                 return 0;
3324
3325         if (!(n = strdup(p)))
3326                 return -ENOMEM;
3327
3328         path_kill_slashes(n);
3329
3330         if ((r = set_put(remove_symlinks_to, n)) < 0) {
3331                 free(n);
3332                 return r == -EEXIST ? 0 : r;
3333         }
3334
3335         return 0;
3336 }
3337
3338 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3339         int r = 0;
3340         DIR *d;
3341         struct dirent *de;
3342
3343         assert(fd >= 0);
3344         assert(root);
3345         assert(deleted);
3346
3347         if (!(d = fdopendir(fd))) {
3348                 close_nointr_nofail(fd);
3349                 return -errno;
3350         }
3351
3352         rewinddir(d);
3353
3354         while ((de = readdir(d))) {
3355                 bool is_dir = false, is_link = false;
3356
3357                 if (ignore_file(de->d_name))
3358                         continue;
3359
3360                 if (de->d_type == DT_LNK)
3361                         is_link = true;
3362                 else if (de->d_type == DT_DIR)
3363                         is_dir = true;
3364                 else if (de->d_type == DT_UNKNOWN) {
3365                         struct stat st;
3366
3367                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3368                                 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3369
3370                                 if (r == 0)
3371                                         r = -errno;
3372                                 continue;
3373                         }
3374
3375                         is_link = S_ISLNK(st.st_mode);
3376                         is_dir = S_ISDIR(st.st_mode);
3377                 } else
3378                         continue;
3379
3380                 if (is_dir) {
3381                         int nfd, q;
3382                         char *p;
3383
3384                         if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3385                                 log_error("Failed to open %s/%s: %m", root, de->d_name);
3386
3387                                 if (r == 0)
3388                                         r = -errno;
3389                                 continue;
3390                         }
3391
3392                         if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3393                                 log_error("Failed to allocate directory string.");
3394                                 close_nointr_nofail(nfd);
3395                                 r = -ENOMEM;
3396                                 break;
3397                         }
3398
3399                         /* This will close nfd, regardless whether it succeeds or not */
3400                         q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3401                         free(p);
3402
3403                         if (r == 0)
3404                                 r = q;
3405
3406                 } else if (is_link) {
3407                         char *p, *dest, *c;
3408                         int q;
3409
3410                         if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3411                                 log_error("Failed to allocate symlink string.");
3412                                 r = -ENOMEM;
3413                                 break;
3414                         }
3415
3416                         if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3417                                 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3418                                 free(p);
3419
3420                                 if (r == 0)
3421                                         r = q;
3422                                 continue;
3423                         }
3424
3425                         if ((c = canonicalize_file_name(dest))) {
3426                                 /* This might fail if the destination
3427                                  * is already removed */
3428
3429                                 free(dest);
3430                                 dest = c;
3431                         }
3432
3433                         path_kill_slashes(dest);
3434                         if (set_get(remove_symlinks_to, dest)) {
3435
3436                                 if (!arg_quiet)
3437                                         log_info("rm '%s'", p);
3438
3439                                 if (unlink(p) < 0) {
3440                                         log_error("Cannot unlink symlink %s: %m", p);
3441
3442                                         if (r == 0)
3443                                                 r = -errno;
3444                                 } else {
3445                                         rmdir_parents(p, config_path);
3446                                         path_kill_slashes(p);
3447
3448                                         if (!set_get(remove_symlinks_to, p)) {
3449
3450                                                 if ((r = mark_symlink_for_removal(p)) < 0) {
3451                                                         if (r == 0)
3452                                                                 r = q;
3453                                                 } else
3454                                                         *deleted = true;
3455                                         }
3456                                 }
3457                         }
3458
3459                         free(p);
3460                         free(dest);
3461                 }
3462         }
3463
3464         closedir(d);
3465
3466         return r;
3467 }
3468
3469 static int remove_marked_symlinks(const char *config_path) {
3470         int fd, r = 0;
3471         bool deleted;
3472
3473         assert(config_path);
3474
3475         if (set_size(remove_symlinks_to) <= 0)
3476                 return 0;
3477
3478         if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3479                 return -errno;
3480
3481         do {
3482                 int q, cfd;
3483                 deleted = false;
3484
3485                 if ((cfd = dup(fd)) < 0) {
3486                         r = -errno;
3487                         break;
3488                 }
3489
3490                 /* This takes possession of cfd and closes it */
3491                 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3492                         if (r == 0)
3493                                 r = q;
3494                 }
3495         } while (deleted);
3496
3497         close_nointr_nofail(fd);
3498
3499         return r;
3500 }
3501
3502 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3503         int r;
3504
3505         assert(old_path);
3506         assert(new_path);
3507         assert(verb);
3508
3509         if (streq(verb, "enable")) {
3510                 char *dest;
3511
3512                 mkdir_parents(new_path, 0755);
3513
3514                 if (symlink(old_path, new_path) >= 0) {
3515
3516                         if (!arg_quiet)
3517                                 log_info("ln -s '%s' '%s'", old_path, new_path);
3518
3519                         return 0;
3520                 }
3521
3522                 if (errno != EEXIST) {
3523                         log_error("Cannot link %s to %s: %m", old_path, new_path);
3524                         return -errno;
3525                 }
3526
3527                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3528
3529                         if (errno == EINVAL) {
3530                                 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3531                                 return -EEXIST;
3532                         }
3533
3534                         log_error("readlink() failed: %s", strerror(-r));
3535                         return r;
3536                 }
3537
3538                 if (streq(dest, old_path)) {
3539                         free(dest);
3540                         return 0;
3541                 }
3542
3543                 if (!arg_force) {
3544                         log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3545                         free(dest);
3546                         return -EEXIST;
3547                 }
3548
3549                 free(dest);
3550                 unlink(new_path);
3551
3552                 if (!arg_quiet)
3553                         log_info("ln -s '%s' '%s'", old_path, new_path);
3554
3555                 if (symlink(old_path, new_path) >= 0)
3556                         return 0;
3557
3558                 log_error("Cannot link %s to %s: %m", old_path, new_path);
3559                 return -errno;
3560
3561         } else if (streq(verb, "disable")) {
3562                 char *dest;
3563
3564                 if ((r = mark_symlink_for_removal(old_path)) < 0)
3565                         return r;
3566
3567                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3568                         if (errno == ENOENT)
3569                                 return 0;
3570
3571                         if (errno == EINVAL) {
3572                                 log_warning("File %s not a symlink, ignoring.", old_path);
3573                                 return 0;
3574                         }
3575
3576                         log_error("readlink() failed: %s", strerror(-r));
3577                         return r;
3578                 }
3579
3580                 if (!streq(dest, old_path)) {
3581                         log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3582                         free(dest);
3583                         return 0;
3584                 }
3585
3586                 free(dest);
3587
3588                 if ((r = mark_symlink_for_removal(new_path)) < 0)
3589                         return r;
3590
3591                 if (!arg_quiet)
3592                         log_info("rm '%s'", new_path);
3593
3594                 if (unlink(new_path) >= 0)
3595                         return 0;
3596
3597                 log_error("Cannot unlink %s: %m", new_path);
3598                 return -errno;
3599
3600         } else if (streq(verb, "is-enabled")) {
3601                 char *dest;
3602
3603                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3604
3605                         if (errno == ENOENT || errno == EINVAL)
3606                                 return 0;
3607
3608                         log_error("readlink() failed: %s", strerror(-r));
3609                         return r;
3610                 }
3611
3612                 if (streq(dest, old_path)) {
3613                         free(dest);
3614                         return 1;
3615                 }
3616
3617                 return 0;
3618         }
3619
3620         assert_not_reached("Unknown action.");
3621 }
3622
3623 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3624         char **s;
3625         char *alias_path = NULL;
3626         int r;
3627
3628         assert(verb);
3629         assert(i);
3630         assert(config_path);
3631
3632         STRV_FOREACH(s, i->aliases) {
3633
3634                 if (!unit_name_is_valid_no_type(*s)) {
3635                         log_error("Invalid name %s.", *s);
3636                         r = -EINVAL;
3637                         goto finish;
3638                 }
3639
3640                 free(alias_path);
3641                 if (!(alias_path = path_make_absolute(*s, config_path))) {
3642                         log_error("Out of memory");
3643                         r = -ENOMEM;
3644                         goto finish;
3645                 }
3646
3647                 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3648                         goto finish;
3649
3650                 if (streq(verb, "disable"))
3651                         rmdir_parents(alias_path, config_path);
3652         }
3653         r = 0;
3654
3655 finish:
3656         free(alias_path);
3657
3658         return r;
3659 }
3660
3661 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3662         char **s;
3663         char *alias_path = NULL;
3664         int r;
3665
3666         assert(verb);
3667         assert(i);
3668         assert(config_path);
3669
3670         STRV_FOREACH(s, i->wanted_by) {
3671                 if (!unit_name_is_valid_no_type(*s)) {
3672                         log_error("Invalid name %s.", *s);
3673                         r = -EINVAL;
3674                         goto finish;
3675                 }
3676
3677                 free(alias_path);
3678                 alias_path = NULL;
3679
3680                 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3681                         log_error("Out of memory");
3682                         r = -ENOMEM;
3683                         goto finish;
3684                 }
3685
3686                 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3687                         goto finish;
3688
3689                 if (streq(verb, "disable"))
3690                         rmdir_parents(alias_path, config_path);
3691         }
3692
3693         r = 0;
3694
3695 finish:
3696         free(alias_path);
3697
3698         return r;
3699 }
3700
3701 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3702
3703         const ConfigItem items[] = {
3704                 { "Alias",    config_parse_strv, &i->aliases,   "Install" },
3705                 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3706                 { "Also",     config_parse_also, NULL,          "Install" },
3707
3708                 { NULL, NULL, NULL, NULL }
3709         };
3710
3711         char **p;
3712         char *filename = NULL;
3713         FILE *f = NULL;
3714         int r;
3715
3716         assert(paths);
3717         assert(i);
3718
3719         STRV_FOREACH(p, paths->unit_path) {
3720                 int fd;
3721
3722                 if (!(filename = path_make_absolute(i->name, *p))) {
3723                         log_error("Out of memory");
3724                         return -ENOMEM;
3725                 }
3726
3727                 /* Ensure that we don't follow symlinks */
3728                 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3729                         if ((f = fdopen(fd, "re")))
3730                                 break;
3731
3732                 if (errno == ELOOP) {
3733                         log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3734                         free(filename);
3735                         return -errno;
3736                 }
3737
3738                 if (errno != ENOENT) {
3739                         log_error("Failed to open %s: %m", filename);
3740                         free(filename);
3741                         return -errno;
3742                 }
3743
3744                 free(filename);
3745                 filename = NULL;
3746         }
3747
3748         if (!f) {
3749                 log_error("Couldn't find %s.", i->name);
3750                 return -ENOENT;
3751         }
3752
3753         i->path = filename;
3754
3755         if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3756                 fclose(f);
3757                 return r;
3758         }
3759
3760         fclose(f);
3761
3762         if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3763                 return r;
3764
3765         if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3766                 return r;
3767
3768         if ((r = mark_symlink_for_removal(filename)) < 0)
3769                 return r;
3770
3771         if ((r = remove_marked_symlinks(config_path)) < 0)
3772                 return r;
3773
3774         return 0;
3775 }
3776
3777 static char *get_config_path(void) {
3778
3779         if (arg_session && arg_global)
3780                 return strdup(SESSION_CONFIG_UNIT_PATH);
3781
3782         if (arg_session) {
3783                 char *p;
3784
3785                 if (session_config_home(&p) < 0)
3786                         return NULL;
3787
3788                 return p;
3789         }
3790
3791         return strdup(SYSTEM_CONFIG_UNIT_PATH);
3792 }
3793
3794 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3795         DBusError error;
3796         int r;
3797         LookupPaths paths;
3798         char *config_path = NULL;
3799         unsigned j;
3800         InstallInfo *i;
3801         const char *verb = args[0];
3802
3803         dbus_error_init(&error);
3804
3805         zero(paths);
3806         if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3807                 log_error("Failed to determine lookup paths: %s", strerror(-r));
3808                 goto finish;
3809         }
3810
3811         if (!(config_path = get_config_path())) {
3812                 log_error("Failed to determine config path");
3813                 r = -ENOMEM;
3814                 goto finish;
3815         }
3816
3817         will_install = hashmap_new(string_hash_func, string_compare_func);
3818         have_installed = hashmap_new(string_hash_func, string_compare_func);
3819
3820         if (!will_install || !have_installed) {
3821                 log_error("Failed to allocate unit sets.");
3822                 r = -ENOMEM;
3823                 goto finish;
3824         }
3825
3826         if (!arg_defaults && streq(verb, "disable"))
3827                 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3828                         log_error("Failed to allocate symlink sets.");
3829                         r = -ENOMEM;
3830                         goto finish;
3831                 }
3832
3833         for (j = 1; j < n; j++)
3834                 if ((r = install_info_add(args[j])) < 0) {
3835                         log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
3836                         goto finish;
3837                 }
3838
3839         while ((i = hashmap_first(will_install))) {
3840                 int q;
3841
3842                 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3843
3844                 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3845
3846                         if (q < 0) {
3847                                 if (r == 0)
3848                                         r = q;
3849                                 goto finish;
3850                         }
3851
3852                         /* In test mode and found something */
3853                         r = 1;
3854                         break;
3855                 }
3856         }
3857
3858         if (streq(verb, "is-enabled"))
3859                 r = r > 0 ? 0 : -ENOENT;
3860         else if (bus &&
3861                  /* Don't try to reload anything if the user asked us to not do this */
3862                  !arg_no_reload &&
3863                  /* Don't try to reload anything when updating a unit globally */
3864                  !arg_global &&
3865                  /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3866                  (arg_session || sd_booted() > 0) &&
3867                  /* Don't try to reload anything if we are running in a chroot environment */
3868                  (arg_session || running_in_chroot() <= 0) ) {
3869                 int q;
3870
3871                 if ((q = daemon_reload(bus, args, n)) < 0)
3872                         r = q;
3873         }
3874
3875 finish:
3876         install_info_hashmap_free(will_install);
3877         install_info_hashmap_free(have_installed);
3878
3879         set_free_free(remove_symlinks_to);
3880
3881         lookup_paths_free(&paths);
3882
3883         free(config_path);
3884
3885         return r;
3886 }
3887
3888 static int systemctl_help(void) {
3889
3890         printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3891                "Send control commands to or query the systemd manager.\n\n"
3892                "  -h --help          Show this help\n"
3893                "     --version       Show package version\n"
3894                "  -t --type=TYPE     List only units of a particular type\n"
3895                "  -p --property=NAME Show only properties by this name\n"
3896                "  -a --all           Show all units/properties, including dead/empty ones\n"
3897                "     --full          Don't ellipsize unit names on output\n"
3898                "     --fail          When queueing a new job, fail if conflicting jobs are\n"
3899                "                     pending\n"
3900                "  -q --quiet         Suppress output\n"
3901                "     --no-block      Do not wait until operation finished\n"
3902                "     --system        Connect to system bus\n"
3903                "     --session       Connect to session bus\n"
3904                "     --order         When generating graph for dot, show only order\n"
3905                "     --require       When generating graph for dot, show only requirement\n"
3906                "     --no-wall       Don't send wall message before halt/power-off/reboot\n"
3907                "     --global        Enable/disable unit files globally\n"
3908                "     --no-reload     When enabling/disabling unit files, don't reload daemon\n"
3909                "                     configuration\n"
3910                "     --force         When enabling unit files, override existing symlinks\n"
3911                "     --defaults      When disabling unit files, remove default symlinks only\n\n"
3912                "Commands:\n"
3913                "  list-units                      List units\n"
3914                "  start [NAME...]                 Start (activate) one or more units\n"
3915                "  stop [NAME...]                  Stop (deactivate) one or more units\n"
3916                "  reload [NAME...]                Reload one or more units\n"
3917                "  restart [NAME...]               Start or restart one or more units\n"
3918                "  try-restart [NAME...]           Restart one or more units if active\n"
3919                "  reload-or-restart [NAME...]     Reload one or more units is possible,\n"
3920                "                                  otherwise start or restart\n"
3921                "  reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3922                "                                  otherwise restart if active\n"
3923                "  isolate [NAME]                  Start one unit and stop all others\n"
3924                "  is-active [NAME...]             Check whether units are active\n"
3925                "  status [NAME...|PID...]         Show runtime status of one or more units\n"
3926                "  show [NAME...|JOB...]           Show properties of one or more\n"
3927                "                                  units/jobs or the manager\n"
3928                "  reset-failed [NAME...]          Reset failed state for all, one, or more\n"
3929                "                                  units\n"
3930                "  enable [NAME...]                Enable one or more unit files\n"
3931                "  disable [NAME...]               Disable one or more unit files\n"
3932                "  is-enabled [NAME...]            Check whether unit files are enabled\n"
3933                "  load [NAME...]                  Load one or more units\n"
3934                "  list-jobs                       List jobs\n"
3935                "  cancel [JOB...]                 Cancel all, one, or more jobs\n"
3936                "  monitor                         Monitor unit/job changes\n"
3937                "  dump                            Dump server status\n"
3938                "  dot                             Dump dependency graph for dot(1)\n"
3939                "  snapshot [NAME]                 Create a snapshot\n"
3940                "  delete [NAME...]                Remove one or more snapshots\n"
3941                "  daemon-reload                   Reload systemd manager configuration\n"
3942                "  daemon-reexec                   Reexecute systemd manager\n"
3943                "  daemon-exit                     Ask the systemd manager to quit\n"
3944                "  show-environment                Dump environment\n"
3945                "  set-environment [NAME=VALUE...] Set one or more environment variables\n"
3946                "  unset-environment [NAME...]     Unset one or more environment variables\n"
3947                "  halt                            Shut down and halt the system\n"
3948                "  poweroff                        Shut down and power-off the system\n"
3949                "  reboot                          Shut down and reboot the system\n"
3950                "  rescue                          Enter system rescue mode\n"
3951                "  emergency                       Enter system emergency mode\n"
3952                "  default                         Enter system default mode\n",
3953                program_invocation_short_name);
3954
3955         return 0;
3956 }
3957
3958 static int halt_help(void) {
3959
3960         printf("%s [OPTIONS...]\n\n"
3961                "%s the system.\n\n"
3962                "     --help      Show this help\n"
3963                "     --halt      Halt the machine\n"
3964                "  -p --poweroff  Switch off the machine\n"
3965                "     --reboot    Reboot the machine\n"
3966                "  -f --force     Force immediate halt/power-off/reboot\n"
3967                "  -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3968                "  -d --no-wtmp   Don't write wtmp record\n"
3969                "  -n --no-sync   Don't sync before halt/power-off/reboot\n"
3970                "     --no-wall   Don't send wall message before halt/power-off/reboot\n",
3971                program_invocation_short_name,
3972                arg_action == ACTION_REBOOT   ? "Reboot" :
3973                arg_action == ACTION_POWEROFF ? "Power off" :
3974                                                "Halt");
3975
3976         return 0;
3977 }
3978
3979 static int shutdown_help(void) {
3980
3981         printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3982                "Shut down the system.\n\n"
3983                "     --help      Show this help\n"
3984                "  -H --halt      Halt the machine\n"
3985                "  -P --poweroff  Power-off the machine\n"
3986                "  -r --reboot    Reboot the machine\n"
3987                "  -h             Equivalent to --poweroff, overriden by --halt\n"
3988                "  -k             Don't halt/power-off/reboot, just send warnings\n"
3989                "     --no-wall   Don't send wall message before halt/power-off/reboot\n"
3990                "  -c             Cancel a pending shutdown\n",
3991                program_invocation_short_name);
3992
3993         return 0;
3994 }
3995
3996 static int telinit_help(void) {
3997
3998         printf("%s [OPTIONS...] {COMMAND}\n\n"
3999                "Send control commands to the init daemon.\n\n"
4000                "     --help      Show this help\n"
4001                "     --no-wall   Don't send wall message before halt/power-off/reboot\n\n"
4002                "Commands:\n"
4003                "  0              Power-off the machine\n"
4004                "  6              Reboot the machine\n"
4005                "  2, 3, 4, 5     Start runlevelX.target unit\n"
4006                "  1, s, S        Enter rescue mode\n"
4007                "  q, Q           Reload init daemon configuration\n"
4008                "  u, U           Reexecute init daemon\n",
4009                program_invocation_short_name);
4010
4011         return 0;
4012 }
4013
4014 static int runlevel_help(void) {
4015
4016         printf("%s [OPTIONS...]\n\n"
4017                "Prints the previous and current runlevel of the init system.\n\n"
4018                "     --help      Show this help\n",
4019                program_invocation_short_name);
4020
4021         return 0;
4022 }
4023
4024 static int systemctl_parse_argv(int argc, char *argv[]) {
4025
4026         enum {
4027                 ARG_FAIL = 0x100,
4028                 ARG_VERSION,
4029                 ARG_SESSION,
4030                 ARG_SYSTEM,
4031                 ARG_GLOBAL,
4032                 ARG_NO_BLOCK,
4033                 ARG_NO_WALL,
4034                 ARG_ORDER,
4035                 ARG_REQUIRE,
4036                 ARG_FULL,
4037                 ARG_FORCE,
4038                 ARG_NO_RELOAD,
4039                 ARG_DEFAULTS
4040         };
4041
4042         static const struct option options[] = {
4043                 { "help",      no_argument,       NULL, 'h'           },
4044                 { "version",   no_argument,       NULL, ARG_VERSION   },
4045                 { "type",      required_argument, NULL, 't'           },
4046                 { "property",  required_argument, NULL, 'p'           },
4047                 { "all",       no_argument,       NULL, 'a'           },
4048                 { "full",      no_argument,       NULL, ARG_FULL      },
4049                 { "fail",      no_argument,       NULL, ARG_FAIL      },
4050                 { "session",   no_argument,       NULL, ARG_SESSION   },
4051                 { "system",    no_argument,       NULL, ARG_SYSTEM    },
4052                 { "global",    no_argument,       NULL, ARG_GLOBAL    },
4053                 { "no-block",  no_argument,       NULL, ARG_NO_BLOCK  },
4054                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL   },
4055                 { "quiet",     no_argument,       NULL, 'q'           },
4056                 { "order",     no_argument,       NULL, ARG_ORDER     },
4057                 { "require",   no_argument,       NULL, ARG_REQUIRE   },
4058                 { "force",     no_argument,       NULL, ARG_FORCE     },
4059                 { "no-reload", no_argument,       NULL, ARG_NO_RELOAD },
4060                 { "defaults",  no_argument,       NULL, ARG_DEFAULTS  },
4061                 { NULL,        0,                 NULL, 0             }
4062         };
4063
4064         int c;
4065
4066         assert(argc >= 0);
4067         assert(argv);
4068
4069         while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
4070
4071                 switch (c) {
4072
4073                 case 'h':
4074                         systemctl_help();
4075                         return 0;
4076
4077                 case ARG_VERSION:
4078                         puts(PACKAGE_STRING);
4079                         puts(DISTRIBUTION);
4080                         puts(SYSTEMD_FEATURES);
4081                         return 0;
4082
4083                 case 't':
4084                         arg_type = optarg;
4085                         break;
4086
4087                 case 'p': {
4088                         char **l;
4089
4090                         if (!(l = strv_append(arg_property, optarg)))
4091                                 return -ENOMEM;
4092
4093                         strv_free(arg_property);
4094                         arg_property = l;
4095
4096                         /* If the user asked for a particular
4097                          * property, show it to him, even if it is
4098                          * empty. */
4099                         arg_all = true;
4100                         break;
4101                 }
4102
4103                 case 'a':
4104                         arg_all = true;
4105                         break;
4106
4107                 case ARG_FAIL:
4108                         arg_fail = true;
4109                         break;
4110
4111                 case ARG_SESSION:
4112                         arg_session = true;
4113                         break;
4114
4115                 case ARG_SYSTEM:
4116                         arg_session = false;
4117                         break;
4118
4119                 case ARG_NO_BLOCK:
4120                         arg_no_block = true;
4121                         break;
4122
4123                 case ARG_NO_WALL:
4124                         arg_no_wall = true;
4125                         break;
4126
4127                 case ARG_ORDER:
4128                         arg_dot = DOT_ORDER;
4129                         break;
4130
4131                 case ARG_REQUIRE:
4132                         arg_dot = DOT_REQUIRE;
4133                         break;
4134
4135                 case ARG_FULL:
4136                         arg_full = true;
4137                         break;
4138
4139                 case 'q':
4140                         arg_quiet = true;
4141                         break;
4142
4143                 case ARG_FORCE:
4144                         arg_force = true;
4145                         break;
4146
4147                 case ARG_NO_RELOAD:
4148                         arg_no_reload = true;
4149                         break;
4150
4151                 case ARG_GLOBAL:
4152                         arg_global = true;
4153                         arg_session = true;
4154                         break;
4155
4156                 case ARG_DEFAULTS:
4157                         arg_defaults = true;
4158                         break;
4159
4160                 case '?':
4161                         return -EINVAL;
4162
4163                 default:
4164                         log_error("Unknown option code %c", c);
4165                         return -EINVAL;
4166                 }
4167         }
4168
4169         return 1;
4170 }
4171
4172 static int halt_parse_argv(int argc, char *argv[]) {
4173
4174         enum {
4175                 ARG_HELP = 0x100,
4176                 ARG_HALT,
4177                 ARG_REBOOT,
4178                 ARG_NO_WALL
4179         };
4180
4181         static const struct option options[] = {
4182                 { "help",      no_argument,       NULL, ARG_HELP    },
4183                 { "halt",      no_argument,       NULL, ARG_HALT    },
4184                 { "poweroff",  no_argument,       NULL, 'p'         },
4185                 { "reboot",    no_argument,       NULL, ARG_REBOOT  },
4186                 { "force",     no_argument,       NULL, 'f'         },
4187                 { "wtmp-only", no_argument,       NULL, 'w'         },
4188                 { "no-wtmp",   no_argument,       NULL, 'd'         },
4189                 { "no-sync",   no_argument,       NULL, 'n'         },
4190                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4191                 { NULL,        0,                 NULL, 0           }
4192         };
4193
4194         int c, runlevel;
4195
4196         assert(argc >= 0);
4197         assert(argv);
4198
4199         if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4200                 if (runlevel == '0' || runlevel == '6')
4201                         arg_immediate = true;
4202
4203         while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4204                 switch (c) {
4205
4206                 case ARG_HELP:
4207                         halt_help();
4208                         return 0;
4209
4210                 case ARG_HALT:
4211                         arg_action = ACTION_HALT;
4212                         break;
4213
4214                 case 'p':
4215                         if (arg_action != ACTION_REBOOT)
4216                                 arg_action = ACTION_POWEROFF;
4217                         break;
4218
4219                 case ARG_REBOOT:
4220                         arg_action = ACTION_REBOOT;
4221                         break;
4222
4223                 case 'f':
4224                         arg_immediate = true;
4225                         break;
4226
4227                 case 'w':
4228                         arg_dry = true;
4229                         break;
4230
4231                 case 'd':
4232                         arg_no_wtmp = true;
4233                         break;
4234
4235                 case 'n':
4236                         arg_no_sync = true;
4237                         break;
4238
4239                 case ARG_NO_WALL:
4240                         arg_no_wall = true;
4241                         break;
4242
4243                 case 'i':
4244                 case 'h':
4245                         /* Compatibility nops */
4246                         break;
4247
4248                 case '?':
4249                         return -EINVAL;
4250
4251                 default:
4252                         log_error("Unknown option code %c", c);
4253                         return -EINVAL;
4254                 }
4255         }
4256
4257         if (optind < argc) {
4258                 log_error("Too many arguments.");
4259                 return -EINVAL;
4260         }
4261
4262         return 1;
4263 }
4264
4265 static int parse_time_spec(const char *t, usec_t *_u) {
4266         assert(t);
4267         assert(_u);
4268
4269         if (streq(t, "now"))
4270                 *_u = 0;
4271         else if (t[0] == '+') {
4272                 uint64_t u;
4273
4274                 if (safe_atou64(t + 1, &u) < 0)
4275                         return -EINVAL;
4276
4277                 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4278         } else {
4279                 char *e = NULL;
4280                 long hour, minute;
4281                 struct tm tm;
4282                 time_t s;
4283                 usec_t n;
4284
4285                 errno = 0;
4286                 hour = strtol(t, &e, 10);
4287                 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4288                         return -EINVAL;
4289
4290                 minute = strtol(e+1, &e, 10);
4291                 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4292                         return -EINVAL;
4293
4294                 n = now(CLOCK_REALTIME);
4295                 s = (time_t) (n / USEC_PER_SEC);
4296
4297                 zero(tm);
4298                 assert_se(localtime_r(&s, &tm));
4299
4300                 tm.tm_hour = (int) hour;
4301                 tm.tm_min = (int) minute;
4302                 tm.tm_sec = 0;
4303
4304                 assert_se(s = mktime(&tm));
4305
4306                 *_u = (usec_t) s * USEC_PER_SEC;
4307
4308                 while (*_u <= n)
4309                         *_u += USEC_PER_DAY;
4310         }
4311
4312         return 0;
4313 }
4314
4315 static int shutdown_parse_argv(int argc, char *argv[]) {
4316
4317         enum {
4318                 ARG_HELP = 0x100,
4319                 ARG_NO_WALL
4320         };
4321
4322         static const struct option options[] = {
4323                 { "help",      no_argument,       NULL, ARG_HELP    },
4324                 { "halt",      no_argument,       NULL, 'H'         },
4325                 { "poweroff",  no_argument,       NULL, 'P'         },
4326                 { "reboot",    no_argument,       NULL, 'r'         },
4327                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4328                 { NULL,        0,                 NULL, 0           }
4329         };
4330
4331         int c, r;
4332
4333         assert(argc >= 0);
4334         assert(argv);
4335
4336         while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4337                 switch (c) {
4338
4339                 case ARG_HELP:
4340                         shutdown_help();
4341                         return 0;
4342
4343                 case 'H':
4344                         arg_action = ACTION_HALT;
4345                         break;
4346
4347                 case 'P':
4348                         arg_action = ACTION_POWEROFF;
4349                         break;
4350
4351                 case 'r':
4352                         arg_action = ACTION_REBOOT;
4353                         break;
4354
4355                 case 'h':
4356                         if (arg_action != ACTION_HALT)
4357                                 arg_action = ACTION_POWEROFF;
4358                         break;
4359
4360                 case 'k':
4361                         arg_dry = true;
4362                         break;
4363
4364                 case ARG_NO_WALL:
4365                         arg_no_wall = true;
4366                         break;
4367
4368                 case 't':
4369                 case 'a':
4370                         /* Compatibility nops */
4371                         break;
4372
4373                 case 'c':
4374                         arg_action = ACTION_CANCEL_SHUTDOWN;
4375                         break;
4376
4377                 case '?':
4378                         return -EINVAL;
4379
4380                 default:
4381                         log_error("Unknown option code %c", c);
4382                         return -EINVAL;
4383                 }
4384         }
4385
4386         if (argc > optind) {
4387                 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4388                         log_error("Failed to parse time specification: %s", argv[optind]);
4389                         return r;
4390                 }
4391         } else
4392                 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4393
4394         /* We skip the time argument */
4395         if (argc > optind + 1)
4396                 arg_wall = argv + optind + 1;
4397
4398         optind = argc;
4399
4400         return 1;
4401 }
4402
4403 static int telinit_parse_argv(int argc, char *argv[]) {
4404
4405         enum {
4406                 ARG_HELP = 0x100,
4407                 ARG_NO_WALL
4408         };
4409
4410         static const struct option options[] = {
4411                 { "help",      no_argument,       NULL, ARG_HELP    },
4412                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4413                 { NULL,        0,                 NULL, 0           }
4414         };
4415
4416         static const struct {
4417                 char from;
4418                 enum action to;
4419         } table[] = {
4420                 { '0', ACTION_POWEROFF },
4421                 { '6', ACTION_REBOOT },
4422                 { '1', ACTION_RESCUE },
4423                 { '2', ACTION_RUNLEVEL2 },
4424                 { '3', ACTION_RUNLEVEL3 },
4425                 { '4', ACTION_RUNLEVEL4 },
4426                 { '5', ACTION_RUNLEVEL5 },
4427                 { 's', ACTION_RESCUE },
4428                 { 'S', ACTION_RESCUE },
4429                 { 'q', ACTION_RELOAD },
4430                 { 'Q', ACTION_RELOAD },
4431                 { 'u', ACTION_REEXEC },
4432                 { 'U', ACTION_REEXEC }
4433         };
4434
4435         unsigned i;
4436         int c;
4437
4438         assert(argc >= 0);
4439         assert(argv);
4440
4441         while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4442                 switch (c) {
4443
4444                 case ARG_HELP:
4445                         telinit_help();
4446                         return 0;
4447
4448                 case ARG_NO_WALL:
4449                         arg_no_wall = true;
4450                         break;
4451
4452                 case '?':
4453                         return -EINVAL;
4454
4455                 default:
4456                         log_error("Unknown option code %c", c);
4457                         return -EINVAL;
4458                 }
4459         }
4460
4461         if (optind >= argc) {
4462                 telinit_help();
4463                 return -EINVAL;
4464         }
4465
4466         if (optind + 1 < argc) {
4467                 log_error("Too many arguments.");
4468                 return -EINVAL;
4469         }
4470
4471         if (strlen(argv[optind]) != 1) {
4472                 log_error("Expected single character argument.");
4473                 return -EINVAL;
4474         }
4475
4476         for (i = 0; i < ELEMENTSOF(table); i++)
4477                 if (table[i].from == argv[optind][0])
4478                         break;
4479
4480         if (i >= ELEMENTSOF(table)) {
4481                 log_error("Unknown command %s.", argv[optind]);
4482                 return -EINVAL;
4483         }
4484
4485         arg_action = table[i].to;
4486
4487         optind ++;
4488
4489         return 1;
4490 }
4491
4492 static int runlevel_parse_argv(int argc, char *argv[]) {
4493
4494         enum {
4495                 ARG_HELP = 0x100,
4496         };
4497
4498         static const struct option options[] = {
4499                 { "help",      no_argument,       NULL, ARG_HELP    },
4500                 { NULL,        0,                 NULL, 0           }
4501         };
4502
4503         int c;
4504
4505         assert(argc >= 0);
4506         assert(argv);
4507
4508         while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4509                 switch (c) {
4510
4511                 case ARG_HELP:
4512                         runlevel_help();
4513                         return 0;
4514
4515                 case '?':
4516                         return -EINVAL;
4517
4518                 default:
4519                         log_error("Unknown option code %c", c);
4520                         return -EINVAL;
4521                 }
4522         }
4523
4524         if (optind < argc) {
4525                 log_error("Too many arguments.");
4526                 return -EINVAL;
4527         }
4528
4529         return 1;
4530 }
4531
4532 static int parse_argv(int argc, char *argv[]) {
4533         assert(argc >= 0);
4534         assert(argv);
4535
4536         if (program_invocation_short_name) {
4537
4538                 if (strstr(program_invocation_short_name, "halt")) {
4539                         arg_action = ACTION_HALT;
4540                         return halt_parse_argv(argc, argv);
4541                 } else if (strstr(program_invocation_short_name, "poweroff")) {
4542                         arg_action = ACTION_POWEROFF;
4543                         return halt_parse_argv(argc, argv);
4544                 } else if (strstr(program_invocation_short_name, "reboot")) {
4545                         arg_action = ACTION_REBOOT;
4546                         return halt_parse_argv(argc, argv);
4547                 } else if (strstr(program_invocation_short_name, "shutdown")) {
4548                         arg_action = ACTION_POWEROFF;
4549                         return shutdown_parse_argv(argc, argv);
4550                 } else if (strstr(program_invocation_short_name, "init")) {
4551
4552                         if (sd_booted() > 0) {
4553                                 arg_action = ACTION_INVALID;
4554                                 return telinit_parse_argv(argc, argv);
4555                         } else {
4556                                 /* Hmm, so some other init system is
4557                                  * running, we need to forward this
4558                                  * request to it. For now we simply
4559                                  * guess that it is Upstart. */
4560
4561                                 execv("/lib/upstart/telinit", argv);
4562
4563                                 log_error("Couldn't find an alternative telinit implementation to spawn.");
4564                                 return -EIO;
4565                         }
4566
4567                 } else if (strstr(program_invocation_short_name, "runlevel")) {
4568                         arg_action = ACTION_RUNLEVEL;
4569                         return runlevel_parse_argv(argc, argv);
4570                 }
4571         }
4572
4573         arg_action = ACTION_SYSTEMCTL;
4574         return systemctl_parse_argv(argc, argv);
4575 }
4576
4577 static int action_to_runlevel(void) {
4578
4579         static const char table[_ACTION_MAX] = {
4580                 [ACTION_HALT] =      '0',
4581                 [ACTION_POWEROFF] =  '0',
4582                 [ACTION_REBOOT] =    '6',
4583                 [ACTION_RUNLEVEL2] = '2',
4584                 [ACTION_RUNLEVEL3] = '3',
4585                 [ACTION_RUNLEVEL4] = '4',
4586                 [ACTION_RUNLEVEL5] = '5',
4587                 [ACTION_RESCUE] =    '1'
4588         };
4589
4590         assert(arg_action < _ACTION_MAX);
4591
4592         return table[arg_action];
4593 }
4594
4595 static int talk_upstart(void) {
4596         DBusMessage *m = NULL, *reply = NULL;
4597         DBusError error;
4598         int previous, rl, r;
4599         char
4600                 env1_buf[] = "RUNLEVEL=X",
4601                 env2_buf[] = "PREVLEVEL=X";
4602         char *env1 = env1_buf, *env2 = env2_buf;
4603         const char *emit = "runlevel";
4604         dbus_bool_t b_false = FALSE;
4605         DBusMessageIter iter, sub;
4606         DBusConnection *bus;
4607
4608         dbus_error_init(&error);
4609
4610         if (!(rl = action_to_runlevel()))
4611                 return 0;
4612
4613         if (utmp_get_runlevel(&previous, NULL) < 0)
4614                 previous = 'N';
4615
4616         if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4617                 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4618                         r = 0;
4619                         goto finish;
4620                 }
4621
4622                 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4623                 r = -EIO;
4624                 goto finish;
4625         }
4626
4627         if ((r = bus_check_peercred(bus)) < 0) {
4628                 log_error("Failed to verify owner of bus.");
4629                 goto finish;
4630         }
4631
4632         if (!(m = dbus_message_new_method_call(
4633                               "com.ubuntu.Upstart",
4634                               "/com/ubuntu/Upstart",
4635                               "com.ubuntu.Upstart0_6",
4636                               "EmitEvent"))) {
4637
4638                 log_error("Could not allocate message.");
4639                 r = -ENOMEM;
4640                 goto finish;
4641         }
4642
4643         dbus_message_iter_init_append(m, &iter);
4644
4645         env1_buf[sizeof(env1_buf)-2] = rl;
4646         env2_buf[sizeof(env2_buf)-2] = previous;
4647
4648         if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4649             !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4650             !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4651             !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4652             !dbus_message_iter_close_container(&iter, &sub) ||
4653             !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4654                 log_error("Could not append arguments to message.");
4655                 r = -ENOMEM;
4656                 goto finish;
4657         }
4658
4659         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4660
4661                 if (error_is_no_service(&error)) {
4662                         r = -EADDRNOTAVAIL;
4663                         goto finish;
4664                 }
4665
4666                 log_error("Failed to issue method call: %s", bus_error_message(&error));
4667                 r = -EIO;
4668                 goto finish;
4669         }
4670
4671         r = 0;
4672
4673 finish:
4674         if (m)
4675                 dbus_message_unref(m);
4676
4677         if (reply)
4678                 dbus_message_unref(reply);
4679
4680         if (bus) {
4681                 dbus_connection_flush(bus);
4682                 dbus_connection_close(bus);
4683                 dbus_connection_unref(bus);
4684         }
4685
4686         dbus_error_free(&error);
4687
4688         return r;
4689 }
4690
4691 static int talk_initctl(void) {
4692         struct init_request request;
4693         int r, fd;
4694         char rl;
4695
4696         if (!(rl = action_to_runlevel()))
4697                 return 0;
4698
4699         zero(request);
4700         request.magic = INIT_MAGIC;
4701         request.sleeptime = 0;
4702         request.cmd = INIT_CMD_RUNLVL;
4703         request.runlevel = rl;
4704
4705         if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4706
4707                 if (errno == ENOENT)
4708                         return 0;
4709
4710                 log_error("Failed to open "INIT_FIFO": %m");
4711                 return -errno;
4712         }
4713
4714         errno = 0;
4715         r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4716         close_nointr_nofail(fd);
4717
4718         if (r < 0) {
4719                 log_error("Failed to write to "INIT_FIFO": %m");
4720                 return errno ? -errno : -EIO;
4721         }
4722
4723         return 1;
4724 }
4725
4726 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4727
4728         static const struct {
4729                 const char* verb;
4730                 const enum {
4731                         MORE,
4732                         LESS,
4733                         EQUAL
4734                 } argc_cmp;
4735                 const int argc;
4736                 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4737         } verbs[] = {
4738                 { "list-units",            LESS,  1, list_units        },
4739                 { "list-jobs",             EQUAL, 1, list_jobs         },
4740                 { "clear-jobs",            EQUAL, 1, daemon_reload     },
4741                 { "load",                  MORE,  2, load_unit         },
4742                 { "cancel",                MORE,  2, cancel_job        },
4743                 { "start",                 MORE,  2, start_unit        },
4744                 { "stop",                  MORE,  2, start_unit        },
4745                 { "reload",                MORE,  2, start_unit        },
4746                 { "restart",               MORE,  2, start_unit        },
4747                 { "try-restart",           MORE,  2, start_unit        },
4748                 { "reload-or-restart",     MORE,  2, start_unit        },
4749                 { "reload-or-try-restart", MORE,  2, start_unit        },
4750                 { "force-reload",          MORE,  2, start_unit        }, /* For compatibility with SysV */
4751                 { "condrestart",           MORE,  2, start_unit        }, /* For compatibility with RH */
4752                 { "isolate",               EQUAL, 2, start_unit        },
4753                 { "is-active",             MORE,  2, check_unit        },
4754                 { "check",                 MORE,  2, check_unit        },
4755                 { "show",                  MORE,  1, show              },
4756                 { "status",                MORE,  2, show              },
4757                 { "monitor",               EQUAL, 1, monitor           },
4758                 { "dump",                  EQUAL, 1, dump              },
4759                 { "dot",                   EQUAL, 1, dot               },
4760                 { "snapshot",              LESS,  2, snapshot          },
4761                 { "delete",                MORE,  2, delete_snapshot   },
4762                 { "daemon-reload",         EQUAL, 1, daemon_reload     },
4763                 { "daemon-reexec",         EQUAL, 1, daemon_reload     },
4764                 { "daemon-exit",           EQUAL, 1, daemon_reload     },
4765                 { "show-environment",      EQUAL, 1, show_enviroment   },
4766                 { "set-environment",       MORE,  2, set_environment   },
4767                 { "unset-environment",     MORE,  2, set_environment   },
4768                 { "halt",                  EQUAL, 1, start_special     },
4769                 { "poweroff",              EQUAL, 1, start_special     },
4770                 { "reboot",                EQUAL, 1, start_special     },
4771                 { "default",               EQUAL, 1, start_special     },
4772                 { "rescue",                EQUAL, 1, start_special     },
4773                 { "emergency",             EQUAL, 1, start_special     },
4774                 { "reset-failed",          MORE,  1, reset_failed      },
4775                 { "enable",                MORE,  2, enable_unit       },
4776                 { "disable",               MORE,  2, enable_unit       },
4777                 { "is-enabled",            MORE,  2, enable_unit       }
4778         };
4779
4780         int left;
4781         unsigned i;
4782
4783         assert(argc >= 0);
4784         assert(argv);
4785         assert(error);
4786
4787         left = argc - optind;
4788
4789         if (left <= 0)
4790                 /* Special rule: no arguments means "list-units" */
4791                 i = 0;
4792         else {
4793                 if (streq(argv[optind], "help")) {
4794                         systemctl_help();
4795                         return 0;
4796                 }
4797
4798                 for (i = 0; i < ELEMENTSOF(verbs); i++)
4799                         if (streq(argv[optind], verbs[i].verb))
4800                                 break;
4801
4802                 if (i >= ELEMENTSOF(verbs)) {
4803                         log_error("Unknown operation %s", argv[optind]);
4804                         return -EINVAL;
4805                 }
4806         }
4807
4808         switch (verbs[i].argc_cmp) {
4809
4810         case EQUAL:
4811                 if (left != verbs[i].argc) {
4812                         log_error("Invalid number of arguments.");
4813                         return -EINVAL;
4814                 }
4815
4816                 break;
4817
4818         case MORE:
4819                 if (left < verbs[i].argc) {
4820                         log_error("Too few arguments.");
4821                         return -EINVAL;
4822                 }
4823
4824                 break;
4825
4826         case LESS:
4827                 if (left > verbs[i].argc) {
4828                         log_error("Too many arguments.");
4829                         return -EINVAL;
4830                 }
4831
4832                 break;
4833
4834         default:
4835                 assert_not_reached("Unknown comparison operator.");
4836         }
4837
4838         /* Require a bus connection for all operations but
4839          * enable/disable */
4840         if (!streq(verbs[i].verb, "enable") &&
4841             !streq(verbs[i].verb, "disable") &&
4842             !bus) {
4843                 log_error("Failed to get D-Bus connection: %s", error->message);
4844                 return -EIO;
4845         }
4846
4847         return verbs[i].dispatch(bus, argv + optind, left);
4848 }
4849
4850 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
4851         int fd = -1;
4852         struct msghdr msghdr;
4853         struct iovec iovec;
4854         union sockaddr_union sockaddr;
4855         struct shutdownd_command c;
4856
4857         zero(c);
4858         c.elapse = t;
4859         c.mode = mode;
4860         c.warn_wall = warn;
4861
4862         if (message)
4863                 strncpy(c.wall_message, message, sizeof(c.wall_message));
4864
4865         if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4866                 return -errno;
4867
4868         zero(sockaddr);
4869         sockaddr.sa.sa_family = AF_UNIX;
4870         sockaddr.un.sun_path[0] = 0;
4871         strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
4872
4873         zero(iovec);
4874         iovec.iov_base = (char*) &c;
4875         iovec.iov_len = sizeof(c);
4876
4877         zero(msghdr);
4878         msghdr.msg_name = &sockaddr;
4879         msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
4880
4881         msghdr.msg_iov = &iovec;
4882         msghdr.msg_iovlen = 1;
4883
4884         if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
4885                 close_nointr_nofail(fd);
4886                 return -errno;
4887         }
4888
4889         close_nointr_nofail(fd);
4890         return 0;
4891 }
4892
4893 static int reload_with_fallback(DBusConnection *bus) {
4894
4895         if (bus) {
4896                 /* First, try systemd via D-Bus. */
4897                 if (daemon_reload(bus, NULL, 0) > 0)
4898                         return 0;
4899         }
4900
4901         /* Nothing else worked, so let's try signals */
4902         assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
4903
4904         if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
4905                 log_error("kill() failed: %m");
4906                 return -errno;
4907         }
4908
4909         return 0;
4910 }
4911
4912 static int start_with_fallback(DBusConnection *bus) {
4913
4914         if (bus) {
4915                 /* First, try systemd via D-Bus. */
4916                 if (start_unit(bus, NULL, 0) >= 0)
4917                         goto done;
4918         }
4919
4920         /* Hmm, talking to systemd via D-Bus didn't work. Then
4921          * let's try to talk to Upstart via D-Bus. */
4922         if (talk_upstart() > 0)
4923                 goto done;
4924
4925         /* Nothing else worked, so let's try
4926          * /dev/initctl */
4927         if (talk_initctl() > 0)
4928                 goto done;
4929
4930         log_error("Failed to talk to init daemon.");
4931         return -EIO;
4932
4933 done:
4934         warn_wall(arg_action);
4935         return 0;
4936 }
4937
4938 static int halt_main(DBusConnection *bus) {
4939         int r;
4940
4941         if (geteuid() != 0) {
4942                 log_error("Must be root.");
4943                 return -EPERM;
4944         }
4945
4946         if (arg_when > 0) {
4947                 char *m;
4948                 char date[FORMAT_TIMESTAMP_MAX];
4949
4950                 m = strv_join(arg_wall, " ");
4951                 r = send_shutdownd(arg_when,
4952                                    arg_action == ACTION_HALT     ? 'H' :
4953                                    arg_action == ACTION_POWEROFF ? 'P' :
4954                                                                    'r',
4955                                    !arg_no_wall,
4956                                    m);
4957                 free(m);
4958
4959                 if (r < 0)
4960                         log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
4961                 else {
4962                         log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
4963                                  format_timestamp(date, sizeof(date), arg_when));
4964                         return 0;
4965                 }
4966         }
4967
4968         if (!arg_dry && !arg_immediate)
4969                 return start_with_fallback(bus);
4970
4971         if (!arg_no_wtmp) {
4972                 if (sd_booted() > 0)
4973                         log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
4974                 else if ((r = utmp_put_shutdown(0)) < 0)
4975                         log_warning("Failed to write utmp record: %s", strerror(-r));
4976         }
4977
4978         if (!arg_no_sync)
4979                 sync();
4980
4981         if (arg_dry)
4982                 return 0;
4983
4984         /* Make sure C-A-D is handled by the kernel from this
4985          * point on... */
4986         reboot(RB_ENABLE_CAD);
4987
4988         switch (arg_action) {
4989
4990         case ACTION_HALT:
4991                 log_info("Halting.");
4992                 reboot(RB_HALT_SYSTEM);
4993                 break;
4994
4995         case ACTION_POWEROFF:
4996                 log_info("Powering off.");
4997                 reboot(RB_POWER_OFF);
4998                 break;
4999
5000         case ACTION_REBOOT:
5001                 log_info("Rebooting.");
5002                 reboot(RB_AUTOBOOT);
5003                 break;
5004
5005         default:
5006                 assert_not_reached("Unknown halt action.");
5007         }
5008
5009         /* We should never reach this. */
5010         return -ENOSYS;
5011 }
5012
5013 static int runlevel_main(void) {
5014         int r, runlevel, previous;
5015
5016         if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5017                 printf("unknown\n");
5018                 return r;
5019         }
5020
5021         printf("%c %c\n",
5022                previous <= 0 ? 'N' : previous,
5023                runlevel <= 0 ? 'N' : runlevel);
5024
5025         return 0;
5026 }
5027
5028 int main(int argc, char*argv[]) {
5029         int r, retval = EXIT_FAILURE;
5030         DBusConnection *bus = NULL;
5031         DBusError error;
5032
5033         dbus_error_init(&error);
5034
5035         log_parse_environment();
5036         log_open();
5037
5038         if ((r = parse_argv(argc, argv)) < 0)
5039                 goto finish;
5040         else if (r == 0) {
5041                 retval = EXIT_SUCCESS;
5042                 goto finish;
5043         }
5044
5045         /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5046          * let's shortcut this */
5047         if (arg_action == ACTION_RUNLEVEL) {
5048                 r = runlevel_main();
5049                 retval = r < 0 ? EXIT_FAILURE : r;
5050                 goto finish;
5051         }
5052
5053         bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5054
5055         switch (arg_action) {
5056
5057         case ACTION_SYSTEMCTL:
5058                 r = systemctl_main(bus, argc, argv, &error);
5059                 break;
5060
5061         case ACTION_HALT:
5062         case ACTION_POWEROFF:
5063         case ACTION_REBOOT:
5064                 r = halt_main(bus);
5065                 break;
5066
5067         case ACTION_RUNLEVEL2:
5068         case ACTION_RUNLEVEL3:
5069         case ACTION_RUNLEVEL4:
5070         case ACTION_RUNLEVEL5:
5071         case ACTION_RESCUE:
5072         case ACTION_EMERGENCY:
5073         case ACTION_DEFAULT:
5074                 r = start_with_fallback(bus);
5075                 break;
5076
5077         case ACTION_RELOAD:
5078         case ACTION_REEXEC:
5079                 r = reload_with_fallback(bus);
5080                 break;
5081
5082         case ACTION_CANCEL_SHUTDOWN:
5083                 r = send_shutdownd(0, 0, false, NULL);
5084                 break;
5085
5086         case ACTION_INVALID:
5087         case ACTION_RUNLEVEL:
5088         default:
5089                 assert_not_reached("Unknown action");
5090         }
5091
5092         retval = r < 0 ? EXIT_FAILURE : r;
5093
5094 finish:
5095
5096         if (bus) {
5097                 dbus_connection_flush(bus);
5098                 dbus_connection_close(bus);
5099                 dbus_connection_unref(bus);
5100         }
5101
5102         dbus_error_free(&error);
5103
5104         dbus_shutdown();
5105
5106         strv_free(arg_property);
5107
5108         return retval;
5109 }