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