chiark / gitweb /
ask-password. Initializing socket_fd inside ask_agent.
[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_STRUCT: {
2007                 DBusMessageIter sub;
2008                 dbus_message_iter_recurse(iter, &sub);
2009
2010                 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2011                         uint32_t u;
2012
2013                         dbus_message_iter_get_basic(&sub, &u);
2014
2015                         if (u)
2016                                 printf("%s=%u\n", name, (unsigned) u);
2017                         else if (arg_all)
2018                                 printf("%s=\n", name);
2019
2020                         return 0;
2021                 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2022                         const char *s;
2023
2024                         dbus_message_iter_get_basic(&sub, &s);
2025
2026                         if (arg_all || s[0])
2027                                 printf("%s=%s\n", name, s);
2028
2029                         return 0;
2030                 }
2031
2032                 break;
2033         }
2034
2035         case DBUS_TYPE_ARRAY:
2036
2037                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2038                         DBusMessageIter sub;
2039                         bool space = false;
2040
2041                         dbus_message_iter_recurse(iter, &sub);
2042                         if (arg_all ||
2043                             dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2044                                 printf("%s=", name);
2045
2046                                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2047                                         const char *s;
2048
2049                                         assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2050                                         dbus_message_iter_get_basic(&sub, &s);
2051                                         printf("%s%s", space ? " " : "", s);
2052
2053                                         space = true;
2054                                         dbus_message_iter_next(&sub);
2055                                 }
2056
2057                                 puts("");
2058                         }
2059
2060                         return 0;
2061
2062                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2063                         DBusMessageIter sub;
2064
2065                         dbus_message_iter_recurse(iter, &sub);
2066                         if (arg_all ||
2067                             dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2068                                 printf("%s=", name);
2069
2070                                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2071                                         uint8_t u;
2072
2073                                         assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2074                                         dbus_message_iter_get_basic(&sub, &u);
2075                                         printf("%02x", u);
2076
2077                                         dbus_message_iter_next(&sub);
2078                                 }
2079
2080                                 puts("");
2081                         }
2082
2083                         return 0;
2084
2085                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2086                         DBusMessageIter sub, sub2;
2087
2088                         dbus_message_iter_recurse(iter, &sub);
2089                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2090                                 const char *type, *path;
2091
2092                                 dbus_message_iter_recurse(&sub, &sub2);
2093
2094                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2095                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2096                                         printf("%s=%s\n", type, path);
2097
2098                                 dbus_message_iter_next(&sub);
2099                         }
2100
2101                         return 0;
2102
2103                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2104                         DBusMessageIter sub, sub2;
2105
2106                         dbus_message_iter_recurse(iter, &sub);
2107                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2108                                 const char *base;
2109                                 uint64_t value, next_elapse;
2110
2111                                 dbus_message_iter_recurse(&sub, &sub2);
2112
2113                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2114                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2115                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2116                                         char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2117
2118                                         printf("%s={ value=%s ; next_elapse=%s }\n",
2119                                                base,
2120                                                format_timespan(timespan1, sizeof(timespan1), value),
2121                                                format_timespan(timespan2, sizeof(timespan2), next_elapse));
2122                                 }
2123
2124                                 dbus_message_iter_next(&sub);
2125                         }
2126
2127                         return 0;
2128
2129                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2130                         DBusMessageIter sub;
2131
2132                         dbus_message_iter_recurse(iter, &sub);
2133                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2134                                 ExecStatusInfo info;
2135
2136                                 zero(info);
2137                                 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2138                                         char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2139                                         char *t;
2140
2141                                         t = strv_join(info.argv, " ");
2142
2143                                         printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2144                                                name,
2145                                                strna(info.path),
2146                                                strna(t),
2147                                                yes_no(info.ignore),
2148                                                strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2149                                                strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2150                                                (unsigned) info. pid,
2151                                                sigchld_code_to_string(info.code),
2152                                                info.status,
2153                                                info.code == CLD_EXITED ? "" : "/",
2154                                                strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2155
2156                                         free(t);
2157                                 }
2158
2159                                 free(info.path);
2160                                 strv_free(info.argv);
2161
2162                                 dbus_message_iter_next(&sub);
2163                         }
2164
2165                         return 0;
2166                 }
2167
2168                 break;
2169         }
2170
2171         if (arg_all)
2172                 printf("%s=[unprintable]\n", name);
2173
2174         return 0;
2175 }
2176
2177 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2178         DBusMessage *m = NULL, *reply = NULL;
2179         const char *interface = "";
2180         int r;
2181         DBusError error;
2182         DBusMessageIter iter, sub, sub2, sub3;
2183         UnitStatusInfo info;
2184         ExecStatusInfo *p;
2185
2186         assert(bus);
2187         assert(path);
2188         assert(new_line);
2189
2190         zero(info);
2191         dbus_error_init(&error);
2192
2193         if (!(m = dbus_message_new_method_call(
2194                               "org.freedesktop.systemd1",
2195                               path,
2196                               "org.freedesktop.DBus.Properties",
2197                               "GetAll"))) {
2198                 log_error("Could not allocate message.");
2199                 r = -ENOMEM;
2200                 goto finish;
2201         }
2202
2203         if (!dbus_message_append_args(m,
2204                                       DBUS_TYPE_STRING, &interface,
2205                                       DBUS_TYPE_INVALID)) {
2206                 log_error("Could not append arguments to message.");
2207                 r = -ENOMEM;
2208                 goto finish;
2209         }
2210
2211         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2212                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2213                 r = -EIO;
2214                 goto finish;
2215         }
2216
2217         if (!dbus_message_iter_init(reply, &iter) ||
2218             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2219             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY)  {
2220                 log_error("Failed to parse reply.");
2221                 r = -EIO;
2222                 goto finish;
2223         }
2224
2225         dbus_message_iter_recurse(&iter, &sub);
2226
2227         if (*new_line)
2228                 printf("\n");
2229
2230         *new_line = true;
2231
2232         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2233                 const char *name;
2234
2235                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2236                         log_error("Failed to parse reply.");
2237                         r = -EIO;
2238                         goto finish;
2239                 }
2240
2241                 dbus_message_iter_recurse(&sub, &sub2);
2242
2243                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2244                         log_error("Failed to parse reply.");
2245                         r = -EIO;
2246                         goto finish;
2247                 }
2248
2249                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT)  {
2250                         log_error("Failed to parse reply.");
2251                         r = -EIO;
2252                         goto finish;
2253                 }
2254
2255                 dbus_message_iter_recurse(&sub2, &sub3);
2256
2257                 if (show_properties)
2258                         r = print_property(name, &sub3);
2259                 else
2260                         r = status_property(name, &sub3, &info);
2261
2262                 if (r < 0) {
2263                         log_error("Failed to parse reply.");
2264                         r = -EIO;
2265                         goto finish;
2266                 }
2267
2268                 dbus_message_iter_next(&sub);
2269         }
2270
2271         r = 0;
2272
2273         if (!show_properties)
2274                 print_status_info(&info);
2275
2276         if (!streq_ptr(info.active_state, "active") &&
2277             !streq_ptr(info.active_state, "reloading"))
2278                 /* According to LSB: "program not running" */
2279                 r = 3;
2280
2281         while ((p = info.exec)) {
2282                 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2283                 exec_status_info_free(p);
2284         }
2285
2286 finish:
2287         if (m)
2288                 dbus_message_unref(m);
2289
2290         if (reply)
2291                 dbus_message_unref(reply);
2292
2293         dbus_error_free(&error);
2294
2295         return r;
2296 }
2297
2298 static int show(DBusConnection *bus, char **args, unsigned n) {
2299         DBusMessage *m = NULL, *reply = NULL;
2300         int r, ret = 0;
2301         DBusError error;
2302         unsigned i;
2303         bool show_properties, new_line = false;
2304
2305         assert(bus);
2306         assert(args);
2307
2308         dbus_error_init(&error);
2309
2310         show_properties = !streq(args[0], "status");
2311
2312         if (show_properties && n <= 1) {
2313                 /* If not argument is specified inspect the manager
2314                  * itself */
2315
2316                 ret = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2317                 goto finish;
2318         }
2319
2320         for (i = 1; i < n; i++) {
2321                 const char *path = NULL;
2322                 uint32_t id;
2323
2324                 if (safe_atou32(args[i], &id) < 0) {
2325
2326                         /* Interpret as unit name */
2327
2328                         if (!(m = dbus_message_new_method_call(
2329                                               "org.freedesktop.systemd1",
2330                                               "/org/freedesktop/systemd1",
2331                                               "org.freedesktop.systemd1.Manager",
2332                                               "LoadUnit"))) {
2333                                 log_error("Could not allocate message.");
2334                                 ret = -ENOMEM;
2335                                 goto finish;
2336                         }
2337
2338                         if (!dbus_message_append_args(m,
2339                                                       DBUS_TYPE_STRING, &args[i],
2340                                                       DBUS_TYPE_INVALID)) {
2341                                 log_error("Could not append arguments to message.");
2342                                 ret = -ENOMEM;
2343                                 goto finish;
2344                         }
2345
2346                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2347
2348                                 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2349                                         log_error("Failed to issue method call: %s", bus_error_message(&error));
2350                                         ret = -EIO;
2351                                         goto finish;
2352                                 }
2353
2354                                 dbus_error_free(&error);
2355
2356                                 dbus_message_unref(m);
2357                                 if (!(m = dbus_message_new_method_call(
2358                                                       "org.freedesktop.systemd1",
2359                                                       "/org/freedesktop/systemd1",
2360                                                       "org.freedesktop.systemd1.Manager",
2361                                                       "GetUnit"))) {
2362                                         log_error("Could not allocate message.");
2363                                         ret = -ENOMEM;
2364                                         goto finish;
2365                                 }
2366
2367                                 if (!dbus_message_append_args(m,
2368                                                               DBUS_TYPE_STRING, &args[i],
2369                                                               DBUS_TYPE_INVALID)) {
2370                                         log_error("Could not append arguments to message.");
2371                                         ret = -ENOMEM;
2372                                         goto finish;
2373                                 }
2374
2375                                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2376                                         log_error("Failed to issue method call: %s", bus_error_message(&error));
2377
2378                                         if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2379                                                 ret = 4; /* According to LSB: "program or service status is unknown" */
2380                                         else
2381                                                 ret = -EIO;
2382                                         goto finish;
2383                                 }
2384                         }
2385
2386                 } else if (show_properties) {
2387
2388                         /* Interpret as job id */
2389
2390                         if (!(m = dbus_message_new_method_call(
2391                                               "org.freedesktop.systemd1",
2392                                               "/org/freedesktop/systemd1",
2393                                               "org.freedesktop.systemd1.Manager",
2394                                               "GetJob"))) {
2395                                 log_error("Could not allocate message.");
2396                                 ret = -ENOMEM;
2397                                 goto finish;
2398                         }
2399
2400                         if (!dbus_message_append_args(m,
2401                                                       DBUS_TYPE_UINT32, &id,
2402                                                       DBUS_TYPE_INVALID)) {
2403                                 log_error("Could not append arguments to message.");
2404                                 ret = -ENOMEM;
2405                                 goto finish;
2406                         }
2407
2408                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2409                                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2410                                 ret = -EIO;
2411                                 goto finish;
2412                         }
2413                 } else {
2414
2415                         /* Interpret as PID */
2416
2417                         if (!(m = dbus_message_new_method_call(
2418                                               "org.freedesktop.systemd1",
2419                                               "/org/freedesktop/systemd1",
2420                                               "org.freedesktop.systemd1.Manager",
2421                                               "GetUnitByPID"))) {
2422                                 log_error("Could not allocate message.");
2423                                 ret = -ENOMEM;
2424                                 goto finish;
2425                         }
2426
2427                         if (!dbus_message_append_args(m,
2428                                                       DBUS_TYPE_UINT32, &id,
2429                                                       DBUS_TYPE_INVALID)) {
2430                                 log_error("Could not append arguments to message.");
2431                                 ret = -ENOMEM;
2432                                 goto finish;
2433                         }
2434
2435                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2436                                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2437                                 ret = -EIO;
2438                                 goto finish;
2439                         }
2440                 }
2441
2442                 if (!dbus_message_get_args(reply, &error,
2443                                            DBUS_TYPE_OBJECT_PATH, &path,
2444                                            DBUS_TYPE_INVALID)) {
2445                         log_error("Failed to parse reply: %s", bus_error_message(&error));
2446                         ret = -EIO;
2447                         goto finish;
2448                 }
2449
2450                 if ((r = show_one(bus, path, show_properties, &new_line)) != 0)
2451                         ret = r;
2452
2453                 dbus_message_unref(m);
2454                 dbus_message_unref(reply);
2455                 m = reply = NULL;
2456         }
2457
2458 finish:
2459         if (m)
2460                 dbus_message_unref(m);
2461
2462         if (reply)
2463                 dbus_message_unref(reply);
2464
2465         dbus_error_free(&error);
2466
2467         return ret;
2468 }
2469
2470 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2471         DBusError error;
2472         DBusMessage *m = NULL, *reply = NULL;
2473
2474         assert(connection);
2475         assert(message);
2476
2477         dbus_error_init(&error);
2478
2479         log_debug("Got D-Bus request: %s.%s() on %s",
2480                   dbus_message_get_interface(message),
2481                   dbus_message_get_member(message),
2482                   dbus_message_get_path(message));
2483
2484         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2485                 log_error("Warning! D-Bus connection terminated.");
2486                 dbus_connection_close(connection);
2487
2488         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2489                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2490                 const char *id, *path;
2491
2492                 if (!dbus_message_get_args(message, &error,
2493                                            DBUS_TYPE_STRING, &id,
2494                                            DBUS_TYPE_OBJECT_PATH, &path,
2495                                            DBUS_TYPE_INVALID))
2496                         log_error("Failed to parse message: %s", bus_error_message(&error));
2497                 else if (streq(dbus_message_get_member(message), "UnitNew"))
2498                         printf("Unit %s added.\n", id);
2499                 else
2500                         printf("Unit %s removed.\n", id);
2501
2502         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2503                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2504                 uint32_t id;
2505                 const char *path;
2506
2507                 if (!dbus_message_get_args(message, &error,
2508                                            DBUS_TYPE_UINT32, &id,
2509                                            DBUS_TYPE_OBJECT_PATH, &path,
2510                                            DBUS_TYPE_INVALID))
2511                         log_error("Failed to parse message: %s", bus_error_message(&error));
2512                 else if (streq(dbus_message_get_member(message), "JobNew"))
2513                         printf("Job %u added.\n", id);
2514                 else
2515                         printf("Job %u removed.\n", id);
2516
2517
2518         } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2519
2520                 const char *path, *interface, *property = "Id";
2521                 DBusMessageIter iter, sub;
2522
2523                 path = dbus_message_get_path(message);
2524
2525                 if (!dbus_message_get_args(message, &error,
2526                                           DBUS_TYPE_STRING, &interface,
2527                                           DBUS_TYPE_INVALID)) {
2528                         log_error("Failed to parse message: %s", bus_error_message(&error));
2529                         goto finish;
2530                 }
2531
2532                 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2533                     !streq(interface, "org.freedesktop.systemd1.Unit"))
2534                         goto finish;
2535
2536                 if (!(m = dbus_message_new_method_call(
2537                               "org.freedesktop.systemd1",
2538                               path,
2539                               "org.freedesktop.DBus.Properties",
2540                               "Get"))) {
2541                         log_error("Could not allocate message.");
2542                         goto oom;
2543                 }
2544
2545                 if (!dbus_message_append_args(m,
2546                                               DBUS_TYPE_STRING, &interface,
2547                                               DBUS_TYPE_STRING, &property,
2548                                               DBUS_TYPE_INVALID)) {
2549                         log_error("Could not append arguments to message.");
2550                         goto finish;
2551                 }
2552
2553                 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2554                         log_error("Failed to issue method call: %s", bus_error_message(&error));
2555                         goto finish;
2556                 }
2557
2558                 if (!dbus_message_iter_init(reply, &iter) ||
2559                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
2560                         log_error("Failed to parse reply.");
2561                         goto finish;
2562                 }
2563
2564                 dbus_message_iter_recurse(&iter, &sub);
2565
2566                 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2567                         const char *id;
2568
2569                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
2570                                 log_error("Failed to parse reply.");
2571                                 goto finish;
2572                         }
2573
2574                         dbus_message_iter_get_basic(&sub, &id);
2575                         printf("Unit %s changed.\n", id);
2576                 } else {
2577                         uint32_t id;
2578
2579                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32)  {
2580                                 log_error("Failed to parse reply.");
2581                                 goto finish;
2582                         }
2583
2584                         dbus_message_iter_get_basic(&sub, &id);
2585                         printf("Job %u changed.\n", id);
2586                 }
2587         }
2588
2589 finish:
2590         if (m)
2591                 dbus_message_unref(m);
2592
2593         if (reply)
2594                 dbus_message_unref(reply);
2595
2596         dbus_error_free(&error);
2597         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2598
2599 oom:
2600         if (m)
2601                 dbus_message_unref(m);
2602
2603         if (reply)
2604                 dbus_message_unref(reply);
2605
2606         dbus_error_free(&error);
2607         return DBUS_HANDLER_RESULT_NEED_MEMORY;
2608 }
2609
2610 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2611         DBusMessage *m = NULL, *reply = NULL;
2612         DBusError error;
2613         int r;
2614
2615         dbus_error_init(&error);
2616
2617         if (!private_bus) {
2618                 dbus_bus_add_match(bus,
2619                                    "type='signal',"
2620                                    "sender='org.freedesktop.systemd1',"
2621                                    "interface='org.freedesktop.systemd1.Manager',"
2622                                    "path='/org/freedesktop/systemd1'",
2623                                    &error);
2624
2625                 if (dbus_error_is_set(&error)) {
2626                         log_error("Failed to add match: %s", bus_error_message(&error));
2627                         r = -EIO;
2628                         goto finish;
2629                 }
2630
2631                 dbus_bus_add_match(bus,
2632                                    "type='signal',"
2633                                    "sender='org.freedesktop.systemd1',"
2634                                    "interface='org.freedesktop.DBus.Properties',"
2635                                    "member='PropertiesChanged'",
2636                                    &error);
2637
2638                 if (dbus_error_is_set(&error)) {
2639                         log_error("Failed to add match: %s", bus_error_message(&error));
2640                         r = -EIO;
2641                         goto finish;
2642                 }
2643         }
2644
2645         if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2646                 log_error("Failed to add filter.");
2647                 r = -ENOMEM;
2648                 goto finish;
2649         }
2650
2651         if (!(m = dbus_message_new_method_call(
2652                               "org.freedesktop.systemd1",
2653                               "/org/freedesktop/systemd1",
2654                               "org.freedesktop.systemd1.Manager",
2655                               "Subscribe"))) {
2656                 log_error("Could not allocate message.");
2657                 r = -ENOMEM;
2658                 goto finish;
2659         }
2660
2661         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2662                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2663                 r = -EIO;
2664                 goto finish;
2665         }
2666
2667         while (dbus_connection_read_write_dispatch(bus, -1))
2668                 ;
2669
2670         r = 0;
2671
2672 finish:
2673
2674         /* This is slightly dirty, since we don't undo the filter or the matches. */
2675
2676         if (m)
2677                 dbus_message_unref(m);
2678
2679         if (reply)
2680                 dbus_message_unref(reply);
2681
2682         dbus_error_free(&error);
2683
2684         return r;
2685 }
2686
2687 static int dump(DBusConnection *bus, char **args, unsigned n) {
2688         DBusMessage *m = NULL, *reply = NULL;
2689         DBusError error;
2690         int r;
2691         const char *text;
2692
2693         dbus_error_init(&error);
2694
2695         if (!(m = dbus_message_new_method_call(
2696                               "org.freedesktop.systemd1",
2697                               "/org/freedesktop/systemd1",
2698                               "org.freedesktop.systemd1.Manager",
2699                               "Dump"))) {
2700                 log_error("Could not allocate message.");
2701                 return -ENOMEM;
2702         }
2703
2704         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2705                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2706                 r = -EIO;
2707                 goto finish;
2708         }
2709
2710         if (!dbus_message_get_args(reply, &error,
2711                                    DBUS_TYPE_STRING, &text,
2712                                    DBUS_TYPE_INVALID)) {
2713                 log_error("Failed to parse reply: %s", bus_error_message(&error));
2714                 r = -EIO;
2715                 goto finish;
2716         }
2717
2718         fputs(text, stdout);
2719
2720         r = 0;
2721
2722 finish:
2723         if (m)
2724                 dbus_message_unref(m);
2725
2726         if (reply)
2727                 dbus_message_unref(reply);
2728
2729         dbus_error_free(&error);
2730
2731         return r;
2732 }
2733
2734 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2735         DBusMessage *m = NULL, *reply = NULL;
2736         DBusError error;
2737         int r;
2738         const char *name = "", *path, *id;
2739         dbus_bool_t cleanup = FALSE;
2740         DBusMessageIter iter, sub;
2741         const char
2742                 *interface = "org.freedesktop.systemd1.Unit",
2743                 *property = "Id";
2744
2745         dbus_error_init(&error);
2746
2747         if (!(m = dbus_message_new_method_call(
2748                               "org.freedesktop.systemd1",
2749                               "/org/freedesktop/systemd1",
2750                               "org.freedesktop.systemd1.Manager",
2751                               "CreateSnapshot"))) {
2752                 log_error("Could not allocate message.");
2753                 return -ENOMEM;
2754         }
2755
2756         if (n > 1)
2757                 name = args[1];
2758
2759         if (!dbus_message_append_args(m,
2760                                       DBUS_TYPE_STRING, &name,
2761                                       DBUS_TYPE_BOOLEAN, &cleanup,
2762                                       DBUS_TYPE_INVALID)) {
2763                 log_error("Could not append arguments to message.");
2764                 r = -ENOMEM;
2765                 goto finish;
2766         }
2767
2768         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2769                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2770                 r = -EIO;
2771                 goto finish;
2772         }
2773
2774         if (!dbus_message_get_args(reply, &error,
2775                                    DBUS_TYPE_OBJECT_PATH, &path,
2776                                    DBUS_TYPE_INVALID)) {
2777                 log_error("Failed to parse reply: %s", bus_error_message(&error));
2778                 r = -EIO;
2779                 goto finish;
2780         }
2781
2782         dbus_message_unref(m);
2783         if (!(m = dbus_message_new_method_call(
2784                               "org.freedesktop.systemd1",
2785                               path,
2786                               "org.freedesktop.DBus.Properties",
2787                               "Get"))) {
2788                 log_error("Could not allocate message.");
2789                 return -ENOMEM;
2790         }
2791
2792         if (!dbus_message_append_args(m,
2793                                       DBUS_TYPE_STRING, &interface,
2794                                       DBUS_TYPE_STRING, &property,
2795                                       DBUS_TYPE_INVALID)) {
2796                 log_error("Could not append arguments to message.");
2797                 r = -ENOMEM;
2798                 goto finish;
2799         }
2800
2801         dbus_message_unref(reply);
2802         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2803                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2804                 r = -EIO;
2805                 goto finish;
2806         }
2807
2808         if (!dbus_message_iter_init(reply, &iter) ||
2809             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
2810                 log_error("Failed to parse reply.");
2811                 r = -EIO;
2812                 goto finish;
2813         }
2814
2815         dbus_message_iter_recurse(&iter, &sub);
2816
2817         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
2818                 log_error("Failed to parse reply.");
2819                 r = -EIO;
2820                 goto finish;
2821         }
2822
2823         dbus_message_iter_get_basic(&sub, &id);
2824
2825         if (!arg_quiet)
2826                 puts(id);
2827         r = 0;
2828
2829 finish:
2830         if (m)
2831                 dbus_message_unref(m);
2832
2833         if (reply)
2834                 dbus_message_unref(reply);
2835
2836         dbus_error_free(&error);
2837
2838         return r;
2839 }
2840
2841 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2842         DBusMessage *m = NULL, *reply = NULL;
2843         int r;
2844         DBusError error;
2845         unsigned i;
2846
2847         assert(bus);
2848         assert(args);
2849
2850         dbus_error_init(&error);
2851
2852         for (i = 1; i < n; i++) {
2853                 const char *path = NULL;
2854
2855                 if (!(m = dbus_message_new_method_call(
2856                                       "org.freedesktop.systemd1",
2857                                       "/org/freedesktop/systemd1",
2858                                       "org.freedesktop.systemd1.Manager",
2859                                       "GetUnit"))) {
2860                         log_error("Could not allocate message.");
2861                         r = -ENOMEM;
2862                         goto finish;
2863                 }
2864
2865                 if (!dbus_message_append_args(m,
2866                                               DBUS_TYPE_STRING, &args[i],
2867                                               DBUS_TYPE_INVALID)) {
2868                         log_error("Could not append arguments to message.");
2869                         r = -ENOMEM;
2870                         goto finish;
2871                 }
2872
2873                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2874                         log_error("Failed to issue method call: %s", bus_error_message(&error));
2875                         r = -EIO;
2876                         goto finish;
2877                 }
2878
2879                 if (!dbus_message_get_args(reply, &error,
2880                                            DBUS_TYPE_OBJECT_PATH, &path,
2881                                            DBUS_TYPE_INVALID)) {
2882                         log_error("Failed to parse reply: %s", bus_error_message(&error));
2883                         r = -EIO;
2884                         goto finish;
2885                 }
2886
2887                 dbus_message_unref(m);
2888                 if (!(m = dbus_message_new_method_call(
2889                                       "org.freedesktop.systemd1",
2890                                       path,
2891                                       "org.freedesktop.systemd1.Snapshot",
2892                                       "Remove"))) {
2893                         log_error("Could not allocate message.");
2894                         r = -ENOMEM;
2895                         goto finish;
2896                 }
2897
2898                 dbus_message_unref(reply);
2899                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2900                         log_error("Failed to issue method call: %s", bus_error_message(&error));
2901                         r = -EIO;
2902                         goto finish;
2903                 }
2904
2905                 dbus_message_unref(m);
2906                 dbus_message_unref(reply);
2907                 m = reply = NULL;
2908         }
2909
2910         r = 0;
2911
2912 finish:
2913         if (m)
2914                 dbus_message_unref(m);
2915
2916         if (reply)
2917                 dbus_message_unref(reply);
2918
2919         dbus_error_free(&error);
2920
2921         return r;
2922 }
2923
2924 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2925         DBusMessage *m = NULL, *reply = NULL;
2926         DBusError error;
2927         int r;
2928         const char *method;
2929
2930         dbus_error_init(&error);
2931
2932         if (arg_action == ACTION_RELOAD)
2933                 method = "Reload";
2934         else if (arg_action == ACTION_REEXEC)
2935                 method = "Reexecute";
2936         else {
2937                 assert(arg_action == ACTION_SYSTEMCTL);
2938
2939                 method =
2940                         streq(args[0], "clear-jobs")        ||
2941                         streq(args[0], "cancel")            ? "ClearJobs" :
2942                         streq(args[0], "daemon-reexec")     ? "Reexecute" :
2943                         streq(args[0], "reset-failed")      ? "ResetFailed" :
2944                         streq(args[0], "daemon-exit")       ? "Exit" :
2945                                                               "Reload";
2946         }
2947
2948         if (!(m = dbus_message_new_method_call(
2949                               "org.freedesktop.systemd1",
2950                               "/org/freedesktop/systemd1",
2951                               "org.freedesktop.systemd1.Manager",
2952                               method))) {
2953                 log_error("Could not allocate message.");
2954                 return -ENOMEM;
2955         }
2956
2957         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2958
2959                 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
2960                         /* There's always a fallback possible for
2961                          * legacy actions. */
2962                         r = -EADDRNOTAVAIL;
2963                         goto finish;
2964                 }
2965
2966                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2967                 r = -EIO;
2968                 goto finish;
2969         }
2970
2971         r = 0;
2972
2973 finish:
2974         if (m)
2975                 dbus_message_unref(m);
2976
2977         if (reply)
2978                 dbus_message_unref(reply);
2979
2980         dbus_error_free(&error);
2981
2982         return r;
2983 }
2984
2985 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
2986         DBusMessage *m = NULL, *reply = NULL;
2987         unsigned i;
2988         int r;
2989         DBusError error;
2990
2991         assert(bus);
2992         dbus_error_init(&error);
2993
2994         if (n <= 1)
2995                 return daemon_reload(bus, args, n);
2996
2997         for (i = 1; i < n; i++) {
2998
2999                 if (!(m = dbus_message_new_method_call(
3000                                       "org.freedesktop.systemd1",
3001                                       "/org/freedesktop/systemd1",
3002                                       "org.freedesktop.systemd1.Manager",
3003                                       "ResetFailedUnit"))) {
3004                         log_error("Could not allocate message.");
3005                         r = -ENOMEM;
3006                         goto finish;
3007                 }
3008
3009                 if (!dbus_message_append_args(m,
3010                                               DBUS_TYPE_STRING, args + i,
3011                                               DBUS_TYPE_INVALID)) {
3012                         log_error("Could not append arguments to message.");
3013                         r = -ENOMEM;
3014                         goto finish;
3015                 }
3016
3017                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3018                         log_error("Failed to issue method call: %s", bus_error_message(&error));
3019                         r = -EIO;
3020                         goto finish;
3021                 }
3022
3023                 dbus_message_unref(m);
3024                 dbus_message_unref(reply);
3025                 m = reply = NULL;
3026         }
3027
3028         r = 0;
3029
3030 finish:
3031         if (m)
3032                 dbus_message_unref(m);
3033
3034         if (reply)
3035                 dbus_message_unref(reply);
3036
3037         dbus_error_free(&error);
3038
3039         return r;
3040 }
3041
3042 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3043         DBusMessage *m = NULL, *reply = NULL;
3044         DBusError error;
3045         DBusMessageIter iter, sub, sub2;
3046         int r;
3047         const char
3048                 *interface = "org.freedesktop.systemd1.Manager",
3049                 *property = "Environment";
3050
3051         dbus_error_init(&error);
3052
3053         if (!(m = dbus_message_new_method_call(
3054                               "org.freedesktop.systemd1",
3055                               "/org/freedesktop/systemd1",
3056                               "org.freedesktop.DBus.Properties",
3057                               "Get"))) {
3058                 log_error("Could not allocate message.");
3059                 return -ENOMEM;
3060         }
3061
3062         if (!dbus_message_append_args(m,
3063                                       DBUS_TYPE_STRING, &interface,
3064                                       DBUS_TYPE_STRING, &property,
3065                                       DBUS_TYPE_INVALID)) {
3066                 log_error("Could not append arguments to message.");
3067                 r = -ENOMEM;
3068                 goto finish;
3069         }
3070
3071         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3072                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3073                 r = -EIO;
3074                 goto finish;
3075         }
3076
3077         if (!dbus_message_iter_init(reply, &iter) ||
3078             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
3079                 log_error("Failed to parse reply.");
3080                 r = -EIO;
3081                 goto finish;
3082         }
3083
3084         dbus_message_iter_recurse(&iter, &sub);
3085
3086         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3087             dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING)  {
3088                 log_error("Failed to parse reply.");
3089                 r = -EIO;
3090                 goto finish;
3091         }
3092
3093         dbus_message_iter_recurse(&sub, &sub2);
3094
3095         while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3096                 const char *text;
3097
3098                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3099                         log_error("Failed to parse reply.");
3100                         r = -EIO;
3101                         goto finish;
3102                 }
3103
3104                 dbus_message_iter_get_basic(&sub2, &text);
3105                 printf("%s\n", text);
3106
3107                 dbus_message_iter_next(&sub2);
3108         }
3109
3110         r = 0;
3111
3112 finish:
3113         if (m)
3114                 dbus_message_unref(m);
3115
3116         if (reply)
3117                 dbus_message_unref(reply);
3118
3119         dbus_error_free(&error);
3120
3121         return r;
3122 }
3123
3124 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3125         DBusMessage *m = NULL, *reply = NULL;
3126         DBusError error;
3127         int r;
3128         const char *method;
3129         DBusMessageIter iter, sub;
3130         unsigned i;
3131
3132         dbus_error_init(&error);
3133
3134         method = streq(args[0], "set-environment")
3135                 ? "SetEnvironment"
3136                 : "UnsetEnvironment";
3137
3138         if (!(m = dbus_message_new_method_call(
3139                               "org.freedesktop.systemd1",
3140                               "/org/freedesktop/systemd1",
3141                               "org.freedesktop.systemd1.Manager",
3142                               method))) {
3143
3144                 log_error("Could not allocate message.");
3145                 return -ENOMEM;
3146         }
3147
3148         dbus_message_iter_init_append(m, &iter);
3149
3150         if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3151                 log_error("Could not append arguments to message.");
3152                 r = -ENOMEM;
3153                 goto finish;
3154         }
3155
3156         for (i = 1; i < n; i++)
3157                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3158                         log_error("Could not append arguments to message.");
3159                         r = -ENOMEM;
3160                         goto finish;
3161                 }
3162
3163         if (!dbus_message_iter_close_container(&iter, &sub)) {
3164                 log_error("Could not append arguments to message.");
3165                 r = -ENOMEM;
3166                 goto finish;
3167         }
3168
3169         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3170                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3171                 r = -EIO;
3172                 goto finish;
3173         }
3174
3175         r = 0;
3176
3177 finish:
3178         if (m)
3179                 dbus_message_unref(m);
3180
3181         if (reply)
3182                 dbus_message_unref(reply);
3183
3184         dbus_error_free(&error);
3185
3186         return r;
3187 }
3188
3189 typedef struct {
3190         char *name;
3191         char *path;
3192
3193         char **aliases;
3194         char **wanted_by;
3195 } InstallInfo;
3196
3197 static Hashmap *will_install = NULL, *have_installed = NULL;
3198 static Set *remove_symlinks_to = NULL;
3199
3200 static void install_info_free(InstallInfo *i) {
3201         assert(i);
3202
3203         free(i->name);
3204         free(i->path);
3205         strv_free(i->aliases);
3206         strv_free(i->wanted_by);
3207         free(i);
3208 }
3209
3210 static void install_info_hashmap_free(Hashmap *m) {
3211         InstallInfo *i;
3212
3213         while ((i = hashmap_steal_first(m)))
3214                 install_info_free(i);
3215
3216         hashmap_free(m);
3217 }
3218
3219 static bool unit_name_valid(const char *name) {
3220
3221         /* This is a minimal version of unit_name_valid() from
3222          * unit-name.c */
3223
3224         if (!*name)
3225                 return false;
3226
3227         if (ignore_file(name))
3228                 return false;
3229
3230         return true;
3231 }
3232
3233 static int install_info_add(const char *name) {
3234         InstallInfo *i;
3235         int r;
3236
3237         assert(will_install);
3238
3239         if (!unit_name_valid(name))
3240                 return -EINVAL;
3241
3242         if (hashmap_get(have_installed, name) ||
3243             hashmap_get(will_install, name))
3244                 return 0;
3245
3246         if (!(i = new0(InstallInfo, 1))) {
3247                 r = -ENOMEM;
3248                 goto fail;
3249         }
3250
3251         if (!(i->name = strdup(name))) {
3252                 r = -ENOMEM;
3253                 goto fail;
3254         }
3255
3256         if ((r = hashmap_put(will_install, i->name, i)) < 0)
3257                 goto fail;
3258
3259         return 0;
3260
3261 fail:
3262         if (i)
3263                 install_info_free(i);
3264
3265         return r;
3266 }
3267
3268 static int config_parse_also(
3269                 const char *filename,
3270                 unsigned line,
3271                 const char *section,
3272                 const char *lvalue,
3273                 const char *rvalue,
3274                 void *data,
3275                 void *userdata) {
3276
3277         char *w;
3278         size_t l;
3279         char *state;
3280
3281         assert(filename);
3282         assert(lvalue);
3283         assert(rvalue);
3284
3285         FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3286                 char *n;
3287                 int r;
3288
3289                 if (!(n = strndup(w, l)))
3290                         return -ENOMEM;
3291
3292                 r = install_info_add(n);
3293                 free(n);
3294
3295                 if (r < 0)
3296                         return r;
3297         }
3298
3299         return 0;
3300 }
3301
3302 static int mark_symlink_for_removal(const char *p) {
3303         char *n;
3304         int r;
3305
3306         assert(p);
3307         assert(path_is_absolute(p));
3308
3309         if (!remove_symlinks_to)
3310                 return 0;
3311
3312         if (!(n = strdup(p)))
3313                 return -ENOMEM;
3314
3315         path_kill_slashes(n);
3316
3317         if ((r = set_put(remove_symlinks_to, n)) < 0) {
3318                 free(n);
3319                 return r == -EEXIST ? 0 : r;
3320         }
3321
3322         return 0;
3323 }
3324
3325 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3326         int r = 0;
3327         DIR *d;
3328         struct dirent *de;
3329
3330         assert(fd >= 0);
3331         assert(root);
3332         assert(deleted);
3333
3334         if (!(d = fdopendir(fd))) {
3335                 close_nointr_nofail(fd);
3336                 return -errno;
3337         }
3338
3339         rewinddir(d);
3340
3341         while ((de = readdir(d))) {
3342                 bool is_dir = false, is_link = false;
3343
3344                 if (ignore_file(de->d_name))
3345                         continue;
3346
3347                 if (de->d_type == DT_LNK)
3348                         is_link = true;
3349                 else if (de->d_type == DT_DIR)
3350                         is_dir = true;
3351                 else if (de->d_type == DT_UNKNOWN) {
3352                         struct stat st;
3353
3354                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3355                                 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3356
3357                                 if (r == 0)
3358                                         r = -errno;
3359                                 continue;
3360                         }
3361
3362                         is_link = S_ISLNK(st.st_mode);
3363                         is_dir = S_ISDIR(st.st_mode);
3364                 } else
3365                         continue;
3366
3367                 if (is_dir) {
3368                         int nfd, q;
3369                         char *p;
3370
3371                         if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3372                                 log_error("Failed to open %s/%s: %m", root, de->d_name);
3373
3374                                 if (r == 0)
3375                                         r = -errno;
3376                                 continue;
3377                         }
3378
3379                         if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3380                                 log_error("Failed to allocate directory string.");
3381                                 close_nointr_nofail(nfd);
3382                                 r = -ENOMEM;
3383                                 break;
3384                         }
3385
3386                         /* This will close nfd, regardless whether it succeeds or not */
3387                         q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3388                         free(p);
3389
3390                         if (r == 0)
3391                                 r = q;
3392
3393                 } else if (is_link) {
3394                         char *p, *dest, *c;
3395                         int q;
3396
3397                         if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3398                                 log_error("Failed to allocate symlink string.");
3399                                 r = -ENOMEM;
3400                                 break;
3401                         }
3402
3403                         if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3404                                 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3405                                 free(p);
3406
3407                                 if (r == 0)
3408                                         r = q;
3409                                 continue;
3410                         }
3411
3412                         if ((c = canonicalize_file_name(dest))) {
3413                                 /* This might fail if the destination
3414                                  * is already removed */
3415
3416                                 free(dest);
3417                                 dest = c;
3418                         }
3419
3420                         path_kill_slashes(dest);
3421                         if (set_get(remove_symlinks_to, dest)) {
3422
3423                                 if (!arg_quiet)
3424                                         log_info("rm '%s'", p);
3425
3426                                 if (unlink(p) < 0) {
3427                                         log_error("Cannot unlink symlink %s: %m", p);
3428
3429                                         if (r == 0)
3430                                                 r = -errno;
3431                                 } else {
3432                                         rmdir_parents(p, config_path);
3433                                         path_kill_slashes(p);
3434
3435                                         if (!set_get(remove_symlinks_to, p)) {
3436
3437                                                 if ((r = mark_symlink_for_removal(p)) < 0) {
3438                                                         if (r == 0)
3439                                                                 r = q;
3440                                                 } else
3441                                                         *deleted = true;
3442                                         }
3443                                 }
3444                         }
3445
3446                         free(p);
3447                         free(dest);
3448                 }
3449         }
3450
3451         closedir(d);
3452
3453         return r;
3454 }
3455
3456 static int remove_marked_symlinks(const char *config_path) {
3457         int fd, r = 0;
3458         bool deleted;
3459
3460         assert(config_path);
3461
3462         if (set_size(remove_symlinks_to) <= 0)
3463                 return 0;
3464
3465         if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3466                 return -errno;
3467
3468         do {
3469                 int q, cfd;
3470                 deleted = false;
3471
3472                 if ((cfd = dup(fd)) < 0) {
3473                         r = -errno;
3474                         break;
3475                 }
3476
3477                 /* This takes possession of cfd and closes it */
3478                 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3479                         if (r == 0)
3480                                 r = q;
3481                 }
3482         } while (deleted);
3483
3484         close_nointr_nofail(fd);
3485
3486         return r;
3487 }
3488
3489 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3490         int r;
3491
3492         assert(old_path);
3493         assert(new_path);
3494         assert(verb);
3495
3496         if (streq(verb, "enable")) {
3497                 char *dest;
3498
3499                 mkdir_parents(new_path, 0755);
3500
3501                 if (symlink(old_path, new_path) >= 0) {
3502
3503                         if (!arg_quiet)
3504                                 log_info("ln -s '%s' '%s'", old_path, new_path);
3505
3506                         return 0;
3507                 }
3508
3509                 if (errno != EEXIST) {
3510                         log_error("Cannot link %s to %s: %m", old_path, new_path);
3511                         return -errno;
3512                 }
3513
3514                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3515
3516                         if (errno == EINVAL) {
3517                                 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3518                                 return -EEXIST;
3519                         }
3520
3521                         log_error("readlink() failed: %s", strerror(-r));
3522                         return r;
3523                 }
3524
3525                 if (streq(dest, old_path)) {
3526                         free(dest);
3527                         return 0;
3528                 }
3529
3530                 if (!arg_force) {
3531                         log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3532                         free(dest);
3533                         return -EEXIST;
3534                 }
3535
3536                 free(dest);
3537                 unlink(new_path);
3538
3539                 if (!arg_quiet)
3540                         log_info("ln -s '%s' '%s'", old_path, new_path);
3541
3542                 if (symlink(old_path, new_path) >= 0)
3543                         return 0;
3544
3545                 log_error("Cannot link %s to %s: %m", old_path, new_path);
3546                 return -errno;
3547
3548         } else if (streq(verb, "disable")) {
3549                 char *dest;
3550
3551                 if ((r = mark_symlink_for_removal(old_path)) < 0)
3552                         return r;
3553
3554                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3555                         if (errno == ENOENT)
3556                                 return 0;
3557
3558                         if (errno == EINVAL) {
3559                                 log_warning("File %s not a symlink, ignoring.", old_path);
3560                                 return 0;
3561                         }
3562
3563                         log_error("readlink() failed: %s", strerror(-r));
3564                         return r;
3565                 }
3566
3567                 if (!streq(dest, old_path)) {
3568                         log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3569                         free(dest);
3570                         return 0;
3571                 }
3572
3573                 free(dest);
3574
3575                 if ((r = mark_symlink_for_removal(new_path)) < 0)
3576                         return r;
3577
3578                 if (!arg_quiet)
3579                         log_info("rm '%s'", new_path);
3580
3581                 if (unlink(new_path) >= 0)
3582                         return 0;
3583
3584                 log_error("Cannot unlink %s: %m", new_path);
3585                 return -errno;
3586
3587         } else if (streq(verb, "is-enabled")) {
3588                 char *dest;
3589
3590                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3591
3592                         if (errno == ENOENT || errno == EINVAL)
3593                                 return 0;
3594
3595                         log_error("readlink() failed: %s", strerror(-r));
3596                         return r;
3597                 }
3598
3599                 if (streq(dest, old_path)) {
3600                         free(dest);
3601                         return 1;
3602                 }
3603
3604                 return 0;
3605         }
3606
3607         assert_not_reached("Unknown action.");
3608 }
3609
3610 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3611         char **s;
3612         char *alias_path = NULL;
3613         int r;
3614
3615         assert(verb);
3616         assert(i);
3617         assert(config_path);
3618
3619         STRV_FOREACH(s, i->aliases) {
3620
3621                 if (!unit_name_valid(*s)) {
3622                         log_error("Invalid name %s.", *s);
3623                         r = -EINVAL;
3624                         goto finish;
3625                 }
3626
3627                 free(alias_path);
3628                 if (!(alias_path = path_make_absolute(*s, config_path))) {
3629                         log_error("Out of memory");
3630                         r = -ENOMEM;
3631                         goto finish;
3632                 }
3633
3634                 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3635                         goto finish;
3636
3637                 if (streq(verb, "disable"))
3638                         rmdir_parents(alias_path, config_path);
3639         }
3640
3641         r = 0;
3642
3643 finish:
3644         free(alias_path);
3645
3646         return r;
3647 }
3648
3649 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3650         char **s;
3651         char *alias_path = NULL;
3652         int r;
3653
3654         assert(verb);
3655         assert(i);
3656         assert(config_path);
3657
3658         STRV_FOREACH(s, i->wanted_by) {
3659                 if (!unit_name_valid(*s)) {
3660                         log_error("Invalid name %s.", *s);
3661                         r = -EINVAL;
3662                         goto finish;
3663                 }
3664
3665                 free(alias_path);
3666                 alias_path = NULL;
3667
3668                 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3669                         log_error("Out of memory");
3670                         r = -ENOMEM;
3671                         goto finish;
3672                 }
3673
3674                 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3675                         goto finish;
3676
3677                 if (streq(verb, "disable"))
3678                         rmdir_parents(alias_path, config_path);
3679         }
3680
3681         r = 0;
3682
3683 finish:
3684         free(alias_path);
3685
3686         return r;
3687 }
3688
3689 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3690
3691         const ConfigItem items[] = {
3692                 { "Alias",    config_parse_strv, &i->aliases,   "Install" },
3693                 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3694                 { "Also",     config_parse_also, NULL,          "Install" },
3695
3696                 { NULL, NULL, NULL, NULL }
3697         };
3698
3699         char **p;
3700         char *filename = NULL;
3701         FILE *f = NULL;
3702         int r;
3703
3704         assert(paths);
3705         assert(i);
3706
3707         STRV_FOREACH(p, paths->unit_path) {
3708                 int fd;
3709
3710                 if (!(filename = path_make_absolute(i->name, *p))) {
3711                         log_error("Out of memory");
3712                         return -ENOMEM;
3713                 }
3714
3715                 /* Ensure that we don't follow symlinks */
3716                 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3717                         if ((f = fdopen(fd, "re")))
3718                                 break;
3719
3720                 if (errno == ELOOP) {
3721                         log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3722                         free(filename);
3723                         return -errno;
3724                 }
3725
3726                 if (errno != ENOENT) {
3727                         log_error("Failed to open %s: %m", filename);
3728                         free(filename);
3729                         return -errno;
3730                 }
3731
3732                 free(filename);
3733                 filename = NULL;
3734         }
3735
3736         if (!f) {
3737                 log_error("Couldn't find %s.", i->name);
3738                 return -ENOENT;
3739         }
3740
3741         i->path = filename;
3742
3743         if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3744                 fclose(f);
3745                 return r;
3746         }
3747
3748         fclose(f);
3749
3750         if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3751                 return r;
3752
3753         if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3754                 return r;
3755
3756         if ((r = mark_symlink_for_removal(filename)) < 0)
3757                 return r;
3758
3759         if ((r = remove_marked_symlinks(config_path)) < 0)
3760                 return r;
3761
3762         return 0;
3763 }
3764
3765 static char *get_config_path(void) {
3766
3767         if (arg_session && arg_global)
3768                 return strdup(SESSION_CONFIG_UNIT_PATH);
3769
3770         if (arg_session) {
3771                 char *p;
3772
3773                 if (session_config_home(&p) < 0)
3774                         return NULL;
3775
3776                 return p;
3777         }
3778
3779         return strdup(SYSTEM_CONFIG_UNIT_PATH);
3780 }
3781
3782 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3783         DBusError error;
3784         int r;
3785         LookupPaths paths;
3786         char *config_path = NULL;
3787         unsigned j;
3788         InstallInfo *i;
3789         const char *verb = args[0];
3790
3791         dbus_error_init(&error);
3792
3793         zero(paths);
3794         if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3795                 log_error("Failed to determine lookup paths: %s", strerror(-r));
3796                 goto finish;
3797         }
3798
3799         if (!(config_path = get_config_path())) {
3800                 log_error("Failed to determine config path");
3801                 r = -ENOMEM;
3802                 goto finish;
3803         }
3804
3805         will_install = hashmap_new(string_hash_func, string_compare_func);
3806         have_installed = hashmap_new(string_hash_func, string_compare_func);
3807
3808         if (!will_install || !have_installed) {
3809                 log_error("Failed to allocate unit sets.");
3810                 r = -ENOMEM;
3811                 goto finish;
3812         }
3813
3814         if (!arg_defaults && streq(verb, "disable"))
3815                 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3816                         log_error("Failed to allocate symlink sets.");
3817                         r = -ENOMEM;
3818                         goto finish;
3819                 }
3820
3821         for (j = 1; j < n; j++)
3822                 if ((r = install_info_add(args[j])) < 0)
3823                         goto finish;
3824
3825         while ((i = hashmap_first(will_install))) {
3826                 int q;
3827
3828                 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3829
3830                 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3831
3832                         if (q < 0) {
3833                                 if (r == 0)
3834                                         r = q;
3835                                 goto finish;
3836                         }
3837
3838                         /* In test mode and found something */
3839                         r = 1;
3840                         break;
3841                 }
3842         }
3843
3844         if (streq(verb, "is-enabled"))
3845                 r = r > 0 ? 0 : -ENOENT;
3846         else if (bus &&
3847                  /* Don't try to reload anything if the user asked us to not do this */
3848                  !arg_no_reload &&
3849                  /* Don't try to reload anything when updating a unit globally */
3850                  !arg_global &&
3851                  /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3852                  (arg_session || sd_booted() > 0) &&
3853                  /* Don't try to reload anything if we are running in a chroot environment */
3854                  (arg_session || running_in_chroot() <= 0) ) {
3855                 int q;
3856
3857                 if ((q = daemon_reload(bus, args, n)) < 0)
3858                         r = q;
3859         }
3860
3861 finish:
3862         install_info_hashmap_free(will_install);
3863         install_info_hashmap_free(have_installed);
3864
3865         set_free_free(remove_symlinks_to);
3866
3867         lookup_paths_free(&paths);
3868
3869         free(config_path);
3870
3871         return r;
3872 }
3873
3874 static int systemctl_help(void) {
3875
3876         printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3877                "Send control commands to or query the systemd manager.\n\n"
3878                "  -h --help          Show this help\n"
3879                "     --version       Show package version\n"
3880                "  -t --type=TYPE     List only units of a particular type\n"
3881                "  -p --property=NAME Show only properties by this name\n"
3882                "  -a --all           Show all units/properties, including dead/empty ones\n"
3883                "     --full          Don't ellipsize unit names on output\n"
3884                "     --fail          When queueing a new job, fail if conflicting jobs are\n"
3885                "                     pending\n"
3886                "  -q --quiet         Suppress output\n"
3887                "     --no-block      Do not wait until operation finished\n"
3888                "     --system        Connect to system bus\n"
3889                "     --session       Connect to session bus\n"
3890                "     --order         When generating graph for dot, show only order\n"
3891                "     --require       When generating graph for dot, show only requirement\n"
3892                "     --no-wall       Don't send wall message before halt/power-off/reboot\n"
3893                "     --global        Enable/disable unit files globally\n"
3894                "     --no-reload     When enabling/disabling unit files, don't reload daemon\n"
3895                "                     configuration\n"
3896                "     --force         When enabling unit files, override existing symlinks\n"
3897                "     --defaults      When disabling unit files, remove default symlinks only\n\n"
3898                "Commands:\n"
3899                "  list-units                      List units\n"
3900                "  start [NAME...]                 Start (activate) one or more units\n"
3901                "  stop [NAME...]                  Stop (deactivate) one or more units\n"
3902                "  reload [NAME...]                Reload one or more units\n"
3903                "  restart [NAME...]               Start or restart one or more units\n"
3904                "  try-restart [NAME...]           Restart one or more units if active\n"
3905                "  reload-or-restart [NAME...]     Reload one or more units is possible,\n"
3906                "                                  otherwise start or restart\n"
3907                "  reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3908                "                                  otherwise restart if active\n"
3909                "  isolate [NAME]                  Start one unit and stop all others\n"
3910                "  is-active [NAME...]             Check whether units are active\n"
3911                "  status [NAME...|PID...]         Show runtime status of one or more units\n"
3912                "  show [NAME...|JOB...]           Show properties of one or more\n"
3913                "                                  units/jobs or the manager\n"
3914                "  reset-failed [NAME...]          Reset failed state for all, one, or more\n"
3915                "                                  units\n"
3916                "  enable [NAME...]                Enable one or more unit files\n"
3917                "  disable [NAME...]               Disable one or more unit files\n"
3918                "  is-enabled [NAME...]            Check whether unit files are enabled\n"
3919                "  load [NAME...]                  Load one or more units\n"
3920                "  list-jobs                       List jobs\n"
3921                "  cancel [JOB...]                 Cancel all, one, or more jobs\n"
3922                "  monitor                         Monitor unit/job changes\n"
3923                "  dump                            Dump server status\n"
3924                "  dot                             Dump dependency graph for dot(1)\n"
3925                "  snapshot [NAME]                 Create a snapshot\n"
3926                "  delete [NAME...]                Remove one or more snapshots\n"
3927                "  daemon-reload                   Reload systemd manager configuration\n"
3928                "  daemon-reexec                   Reexecute systemd manager\n"
3929                "  daemon-exit                     Ask the systemd manager to quit\n"
3930                "  show-environment                Dump environment\n"
3931                "  set-environment [NAME=VALUE...] Set one or more environment variables\n"
3932                "  unset-environment [NAME...]     Unset one or more environment variables\n"
3933                "  halt                            Shut down and halt the system\n"
3934                "  poweroff                        Shut down and power-off the system\n"
3935                "  reboot                          Shut down and reboot the system\n"
3936                "  rescue                          Enter system rescue mode\n"
3937                "  emergency                       Enter system emergency mode\n"
3938                "  default                         Enter system default mode\n",
3939                program_invocation_short_name);
3940
3941         return 0;
3942 }
3943
3944 static int halt_help(void) {
3945
3946         printf("%s [OPTIONS...]\n\n"
3947                "%s the system.\n\n"
3948                "     --help      Show this help\n"
3949                "     --halt      Halt the machine\n"
3950                "  -p --poweroff  Switch off the machine\n"
3951                "     --reboot    Reboot the machine\n"
3952                "  -f --force     Force immediate halt/power-off/reboot\n"
3953                "  -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3954                "  -d --no-wtmp   Don't write wtmp record\n"
3955                "  -n --no-sync   Don't sync before halt/power-off/reboot\n"
3956                "     --no-wall   Don't send wall message before halt/power-off/reboot\n",
3957                program_invocation_short_name,
3958                arg_action == ACTION_REBOOT   ? "Reboot" :
3959                arg_action == ACTION_POWEROFF ? "Power off" :
3960                                                "Halt");
3961
3962         return 0;
3963 }
3964
3965 static int shutdown_help(void) {
3966
3967         printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3968                "Shut down the system.\n\n"
3969                "     --help      Show this help\n"
3970                "  -H --halt      Halt the machine\n"
3971                "  -P --poweroff  Power-off the machine\n"
3972                "  -r --reboot    Reboot the machine\n"
3973                "  -h             Equivalent to --poweroff, overriden by --halt\n"
3974                "  -k             Don't halt/power-off/reboot, just send warnings\n"
3975                "     --no-wall   Don't send wall message before halt/power-off/reboot\n"
3976                "  -c             Cancel a pending shutdown\n",
3977                program_invocation_short_name);
3978
3979         return 0;
3980 }
3981
3982 static int telinit_help(void) {
3983
3984         printf("%s [OPTIONS...] {COMMAND}\n\n"
3985                "Send control commands to the init daemon.\n\n"
3986                "     --help      Show this help\n"
3987                "     --no-wall   Don't send wall message before halt/power-off/reboot\n\n"
3988                "Commands:\n"
3989                "  0              Power-off the machine\n"
3990                "  6              Reboot the machine\n"
3991                "  2, 3, 4, 5     Start runlevelX.target unit\n"
3992                "  1, s, S        Enter rescue mode\n"
3993                "  q, Q           Reload init daemon configuration\n"
3994                "  u, U           Reexecute init daemon\n",
3995                program_invocation_short_name);
3996
3997         return 0;
3998 }
3999
4000 static int runlevel_help(void) {
4001
4002         printf("%s [OPTIONS...]\n\n"
4003                "Prints the previous and current runlevel of the init system.\n\n"
4004                "     --help      Show this help\n",
4005                program_invocation_short_name);
4006
4007         return 0;
4008 }
4009
4010 static int systemctl_parse_argv(int argc, char *argv[]) {
4011
4012         enum {
4013                 ARG_FAIL = 0x100,
4014                 ARG_VERSION,
4015                 ARG_SESSION,
4016                 ARG_SYSTEM,
4017                 ARG_GLOBAL,
4018                 ARG_NO_BLOCK,
4019                 ARG_NO_WALL,
4020                 ARG_ORDER,
4021                 ARG_REQUIRE,
4022                 ARG_FULL,
4023                 ARG_FORCE,
4024                 ARG_NO_RELOAD,
4025                 ARG_DEFAULTS
4026         };
4027
4028         static const struct option options[] = {
4029                 { "help",      no_argument,       NULL, 'h'           },
4030                 { "version",   no_argument,       NULL, ARG_VERSION   },
4031                 { "type",      required_argument, NULL, 't'           },
4032                 { "property",  required_argument, NULL, 'p'           },
4033                 { "all",       no_argument,       NULL, 'a'           },
4034                 { "full",      no_argument,       NULL, ARG_FULL      },
4035                 { "fail",      no_argument,       NULL, ARG_FAIL      },
4036                 { "session",   no_argument,       NULL, ARG_SESSION   },
4037                 { "system",    no_argument,       NULL, ARG_SYSTEM    },
4038                 { "global",    no_argument,       NULL, ARG_GLOBAL    },
4039                 { "no-block",  no_argument,       NULL, ARG_NO_BLOCK  },
4040                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL   },
4041                 { "quiet",     no_argument,       NULL, 'q'           },
4042                 { "order",     no_argument,       NULL, ARG_ORDER     },
4043                 { "require",   no_argument,       NULL, ARG_REQUIRE   },
4044                 { "force",     no_argument,       NULL, ARG_FORCE     },
4045                 { "no-reload", no_argument,       NULL, ARG_NO_RELOAD },
4046                 { "defaults",  no_argument,       NULL, ARG_DEFAULTS  },
4047                 { NULL,        0,                 NULL, 0             }
4048         };
4049
4050         int c;
4051
4052         assert(argc >= 0);
4053         assert(argv);
4054
4055         while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
4056
4057                 switch (c) {
4058
4059                 case 'h':
4060                         systemctl_help();
4061                         return 0;
4062
4063                 case ARG_VERSION:
4064                         puts(PACKAGE_STRING);
4065                         puts(DISTRIBUTION);
4066                         puts(SYSTEMD_FEATURES);
4067                         return 0;
4068
4069                 case 't':
4070                         arg_type = optarg;
4071                         break;
4072
4073                 case 'p': {
4074                         char **l;
4075
4076                         if (!(l = strv_append(arg_property, optarg)))
4077                                 return -ENOMEM;
4078
4079                         strv_free(arg_property);
4080                         arg_property = l;
4081
4082                         /* If the user asked for a particular
4083                          * property, show it to him, even if it is
4084                          * empty. */
4085                         arg_all = true;
4086                         break;
4087                 }
4088
4089                 case 'a':
4090                         arg_all = true;
4091                         break;
4092
4093                 case ARG_FAIL:
4094                         arg_fail = true;
4095                         break;
4096
4097                 case ARG_SESSION:
4098                         arg_session = true;
4099                         break;
4100
4101                 case ARG_SYSTEM:
4102                         arg_session = false;
4103                         break;
4104
4105                 case ARG_NO_BLOCK:
4106                         arg_no_block = true;
4107                         break;
4108
4109                 case ARG_NO_WALL:
4110                         arg_no_wall = true;
4111                         break;
4112
4113                 case ARG_ORDER:
4114                         arg_dot = DOT_ORDER;
4115                         break;
4116
4117                 case ARG_REQUIRE:
4118                         arg_dot = DOT_REQUIRE;
4119                         break;
4120
4121                 case ARG_FULL:
4122                         arg_full = true;
4123                         break;
4124
4125                 case 'q':
4126                         arg_quiet = true;
4127                         break;
4128
4129                 case ARG_FORCE:
4130                         arg_force = true;
4131                         break;
4132
4133                 case ARG_NO_RELOAD:
4134                         arg_no_reload = true;
4135                         break;
4136
4137                 case ARG_GLOBAL:
4138                         arg_global = true;
4139                         arg_session = true;
4140                         break;
4141
4142                 case ARG_DEFAULTS:
4143                         arg_defaults = true;
4144                         break;
4145
4146                 case '?':
4147                         return -EINVAL;
4148
4149                 default:
4150                         log_error("Unknown option code %c", c);
4151                         return -EINVAL;
4152                 }
4153         }
4154
4155         return 1;
4156 }
4157
4158 static int halt_parse_argv(int argc, char *argv[]) {
4159
4160         enum {
4161                 ARG_HELP = 0x100,
4162                 ARG_HALT,
4163                 ARG_REBOOT,
4164                 ARG_NO_WALL
4165         };
4166
4167         static const struct option options[] = {
4168                 { "help",      no_argument,       NULL, ARG_HELP    },
4169                 { "halt",      no_argument,       NULL, ARG_HALT    },
4170                 { "poweroff",  no_argument,       NULL, 'p'         },
4171                 { "reboot",    no_argument,       NULL, ARG_REBOOT  },
4172                 { "force",     no_argument,       NULL, 'f'         },
4173                 { "wtmp-only", no_argument,       NULL, 'w'         },
4174                 { "no-wtmp",   no_argument,       NULL, 'd'         },
4175                 { "no-sync",   no_argument,       NULL, 'n'         },
4176                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4177                 { NULL,        0,                 NULL, 0           }
4178         };
4179
4180         int c, runlevel;
4181
4182         assert(argc >= 0);
4183         assert(argv);
4184
4185         if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4186                 if (runlevel == '0' || runlevel == '6')
4187                         arg_immediate = true;
4188
4189         while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4190                 switch (c) {
4191
4192                 case ARG_HELP:
4193                         halt_help();
4194                         return 0;
4195
4196                 case ARG_HALT:
4197                         arg_action = ACTION_HALT;
4198                         break;
4199
4200                 case 'p':
4201                         if (arg_action != ACTION_REBOOT)
4202                                 arg_action = ACTION_POWEROFF;
4203                         break;
4204
4205                 case ARG_REBOOT:
4206                         arg_action = ACTION_REBOOT;
4207                         break;
4208
4209                 case 'f':
4210                         arg_immediate = true;
4211                         break;
4212
4213                 case 'w':
4214                         arg_dry = true;
4215                         break;
4216
4217                 case 'd':
4218                         arg_no_wtmp = true;
4219                         break;
4220
4221                 case 'n':
4222                         arg_no_sync = true;
4223                         break;
4224
4225                 case ARG_NO_WALL:
4226                         arg_no_wall = true;
4227                         break;
4228
4229                 case 'i':
4230                 case 'h':
4231                         /* Compatibility nops */
4232                         break;
4233
4234                 case '?':
4235                         return -EINVAL;
4236
4237                 default:
4238                         log_error("Unknown option code %c", c);
4239                         return -EINVAL;
4240                 }
4241         }
4242
4243         if (optind < argc) {
4244                 log_error("Too many arguments.");
4245                 return -EINVAL;
4246         }
4247
4248         return 1;
4249 }
4250
4251 static int parse_time_spec(const char *t, usec_t *_u) {
4252         assert(t);
4253         assert(_u);
4254
4255         if (streq(t, "now"))
4256                 *_u = 0;
4257         else if (t[0] == '+') {
4258                 uint64_t u;
4259
4260                 if (safe_atou64(t + 1, &u) < 0)
4261                         return -EINVAL;
4262
4263                 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4264         } else {
4265                 char *e = NULL;
4266                 long hour, minute;
4267                 struct tm tm;
4268                 time_t s;
4269                 usec_t n;
4270
4271                 errno = 0;
4272                 hour = strtol(t, &e, 10);
4273                 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4274                         return -EINVAL;
4275
4276                 minute = strtol(e+1, &e, 10);
4277                 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4278                         return -EINVAL;
4279
4280                 n = now(CLOCK_REALTIME);
4281                 s = (time_t) (n / USEC_PER_SEC);
4282
4283                 zero(tm);
4284                 assert_se(localtime_r(&s, &tm));
4285
4286                 tm.tm_hour = (int) hour;
4287                 tm.tm_min = (int) minute;
4288                 tm.tm_sec = 0;
4289
4290                 assert_se(s = mktime(&tm));
4291
4292                 *_u = (usec_t) s * USEC_PER_SEC;
4293
4294                 while (*_u <= n)
4295                         *_u += USEC_PER_DAY;
4296         }
4297
4298         return 0;
4299 }
4300
4301 static int shutdown_parse_argv(int argc, char *argv[]) {
4302
4303         enum {
4304                 ARG_HELP = 0x100,
4305                 ARG_NO_WALL
4306         };
4307
4308         static const struct option options[] = {
4309                 { "help",      no_argument,       NULL, ARG_HELP    },
4310                 { "halt",      no_argument,       NULL, 'H'         },
4311                 { "poweroff",  no_argument,       NULL, 'P'         },
4312                 { "reboot",    no_argument,       NULL, 'r'         },
4313                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4314                 { NULL,        0,                 NULL, 0           }
4315         };
4316
4317         int c, r;
4318
4319         assert(argc >= 0);
4320         assert(argv);
4321
4322         while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4323                 switch (c) {
4324
4325                 case ARG_HELP:
4326                         shutdown_help();
4327                         return 0;
4328
4329                 case 'H':
4330                         arg_action = ACTION_HALT;
4331                         break;
4332
4333                 case 'P':
4334                         arg_action = ACTION_POWEROFF;
4335                         break;
4336
4337                 case 'r':
4338                         arg_action = ACTION_REBOOT;
4339                         break;
4340
4341                 case 'h':
4342                         if (arg_action != ACTION_HALT)
4343                                 arg_action = ACTION_POWEROFF;
4344                         break;
4345
4346                 case 'k':
4347                         arg_dry = true;
4348                         break;
4349
4350                 case ARG_NO_WALL:
4351                         arg_no_wall = true;
4352                         break;
4353
4354                 case 't':
4355                 case 'a':
4356                         /* Compatibility nops */
4357                         break;
4358
4359                 case 'c':
4360                         arg_action = ACTION_CANCEL_SHUTDOWN;
4361                         break;
4362
4363                 case '?':
4364                         return -EINVAL;
4365
4366                 default:
4367                         log_error("Unknown option code %c", c);
4368                         return -EINVAL;
4369                 }
4370         }
4371
4372         if (argc > optind) {
4373                 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4374                         log_error("Failed to parse time specification: %s", argv[optind]);
4375                         return r;
4376                 }
4377         } else
4378                 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4379
4380         /* We skip the time argument */
4381         if (argc > optind + 1)
4382                 arg_wall = argv + optind + 1;
4383
4384         optind = argc;
4385
4386         return 1;
4387 }
4388
4389 static int telinit_parse_argv(int argc, char *argv[]) {
4390
4391         enum {
4392                 ARG_HELP = 0x100,
4393                 ARG_NO_WALL
4394         };
4395
4396         static const struct option options[] = {
4397                 { "help",      no_argument,       NULL, ARG_HELP    },
4398                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4399                 { NULL,        0,                 NULL, 0           }
4400         };
4401
4402         static const struct {
4403                 char from;
4404                 enum action to;
4405         } table[] = {
4406                 { '0', ACTION_POWEROFF },
4407                 { '6', ACTION_REBOOT },
4408                 { '1', ACTION_RESCUE },
4409                 { '2', ACTION_RUNLEVEL2 },
4410                 { '3', ACTION_RUNLEVEL3 },
4411                 { '4', ACTION_RUNLEVEL4 },
4412                 { '5', ACTION_RUNLEVEL5 },
4413                 { 's', ACTION_RESCUE },
4414                 { 'S', ACTION_RESCUE },
4415                 { 'q', ACTION_RELOAD },
4416                 { 'Q', ACTION_RELOAD },
4417                 { 'u', ACTION_REEXEC },
4418                 { 'U', ACTION_REEXEC }
4419         };
4420
4421         unsigned i;
4422         int c;
4423
4424         assert(argc >= 0);
4425         assert(argv);
4426
4427         while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4428                 switch (c) {
4429
4430                 case ARG_HELP:
4431                         telinit_help();
4432                         return 0;
4433
4434                 case ARG_NO_WALL:
4435                         arg_no_wall = true;
4436                         break;
4437
4438                 case '?':
4439                         return -EINVAL;
4440
4441                 default:
4442                         log_error("Unknown option code %c", c);
4443                         return -EINVAL;
4444                 }
4445         }
4446
4447         if (optind >= argc) {
4448                 telinit_help();
4449                 return -EINVAL;
4450         }
4451
4452         if (optind + 1 < argc) {
4453                 log_error("Too many arguments.");
4454                 return -EINVAL;
4455         }
4456
4457         if (strlen(argv[optind]) != 1) {
4458                 log_error("Expected single character argument.");
4459                 return -EINVAL;
4460         }
4461
4462         for (i = 0; i < ELEMENTSOF(table); i++)
4463                 if (table[i].from == argv[optind][0])
4464                         break;
4465
4466         if (i >= ELEMENTSOF(table)) {
4467                 log_error("Unknown command %s.", argv[optind]);
4468                 return -EINVAL;
4469         }
4470
4471         arg_action = table[i].to;
4472
4473         optind ++;
4474
4475         return 1;
4476 }
4477
4478 static int runlevel_parse_argv(int argc, char *argv[]) {
4479
4480         enum {
4481                 ARG_HELP = 0x100,
4482         };
4483
4484         static const struct option options[] = {
4485                 { "help",      no_argument,       NULL, ARG_HELP    },
4486                 { NULL,        0,                 NULL, 0           }
4487         };
4488
4489         int c;
4490
4491         assert(argc >= 0);
4492         assert(argv);
4493
4494         while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4495                 switch (c) {
4496
4497                 case ARG_HELP:
4498                         runlevel_help();
4499                         return 0;
4500
4501                 case '?':
4502                         return -EINVAL;
4503
4504                 default:
4505                         log_error("Unknown option code %c", c);
4506                         return -EINVAL;
4507                 }
4508         }
4509
4510         if (optind < argc) {
4511                 log_error("Too many arguments.");
4512                 return -EINVAL;
4513         }
4514
4515         return 1;
4516 }
4517
4518 static int parse_argv(int argc, char *argv[]) {
4519         assert(argc >= 0);
4520         assert(argv);
4521
4522         if (program_invocation_short_name) {
4523
4524                 if (strstr(program_invocation_short_name, "halt")) {
4525                         arg_action = ACTION_HALT;
4526                         return halt_parse_argv(argc, argv);
4527                 } else if (strstr(program_invocation_short_name, "poweroff")) {
4528                         arg_action = ACTION_POWEROFF;
4529                         return halt_parse_argv(argc, argv);
4530                 } else if (strstr(program_invocation_short_name, "reboot")) {
4531                         arg_action = ACTION_REBOOT;
4532                         return halt_parse_argv(argc, argv);
4533                 } else if (strstr(program_invocation_short_name, "shutdown")) {
4534                         arg_action = ACTION_POWEROFF;
4535                         return shutdown_parse_argv(argc, argv);
4536                 } else if (strstr(program_invocation_short_name, "init")) {
4537
4538                         if (sd_booted() > 0) {
4539                                 arg_action = ACTION_INVALID;
4540                                 return telinit_parse_argv(argc, argv);
4541                         } else {
4542                                 /* Hmm, so some other init system is
4543                                  * running, we need to forward this
4544                                  * request to it. For now we simply
4545                                  * guess that it is Upstart. */
4546
4547                                 execv("/lib/upstart/telinit", argv);
4548
4549                                 log_error("Couldn't find an alternative telinit implementation to spawn.");
4550                                 return -EIO;
4551                         }
4552
4553                 } else if (strstr(program_invocation_short_name, "runlevel")) {
4554                         arg_action = ACTION_RUNLEVEL;
4555                         return runlevel_parse_argv(argc, argv);
4556                 }
4557         }
4558
4559         arg_action = ACTION_SYSTEMCTL;
4560         return systemctl_parse_argv(argc, argv);
4561 }
4562
4563 static int action_to_runlevel(void) {
4564
4565         static const char table[_ACTION_MAX] = {
4566                 [ACTION_HALT] =      '0',
4567                 [ACTION_POWEROFF] =  '0',
4568                 [ACTION_REBOOT] =    '6',
4569                 [ACTION_RUNLEVEL2] = '2',
4570                 [ACTION_RUNLEVEL3] = '3',
4571                 [ACTION_RUNLEVEL4] = '4',
4572                 [ACTION_RUNLEVEL5] = '5',
4573                 [ACTION_RESCUE] =    '1'
4574         };
4575
4576         assert(arg_action < _ACTION_MAX);
4577
4578         return table[arg_action];
4579 }
4580
4581 static int talk_upstart(void) {
4582         DBusMessage *m = NULL, *reply = NULL;
4583         DBusError error;
4584         int previous, rl, r;
4585         char
4586                 env1_buf[] = "RUNLEVEL=X",
4587                 env2_buf[] = "PREVLEVEL=X";
4588         char *env1 = env1_buf, *env2 = env2_buf;
4589         const char *emit = "runlevel";
4590         dbus_bool_t b_false = FALSE;
4591         DBusMessageIter iter, sub;
4592         DBusConnection *bus;
4593
4594         dbus_error_init(&error);
4595
4596         if (!(rl = action_to_runlevel()))
4597                 return 0;
4598
4599         if (utmp_get_runlevel(&previous, NULL) < 0)
4600                 previous = 'N';
4601
4602         if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4603                 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4604                         r = 0;
4605                         goto finish;
4606                 }
4607
4608                 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4609                 r = -EIO;
4610                 goto finish;
4611         }
4612
4613         if ((r = bus_check_peercred(bus)) < 0) {
4614                 log_error("Failed to verify owner of bus.");
4615                 goto finish;
4616         }
4617
4618         if (!(m = dbus_message_new_method_call(
4619                               "com.ubuntu.Upstart",
4620                               "/com/ubuntu/Upstart",
4621                               "com.ubuntu.Upstart0_6",
4622                               "EmitEvent"))) {
4623
4624                 log_error("Could not allocate message.");
4625                 r = -ENOMEM;
4626                 goto finish;
4627         }
4628
4629         dbus_message_iter_init_append(m, &iter);
4630
4631         env1_buf[sizeof(env1_buf)-2] = rl;
4632         env2_buf[sizeof(env2_buf)-2] = previous;
4633
4634         if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4635             !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4636             !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4637             !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4638             !dbus_message_iter_close_container(&iter, &sub) ||
4639             !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4640                 log_error("Could not append arguments to message.");
4641                 r = -ENOMEM;
4642                 goto finish;
4643         }
4644
4645         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4646
4647                 if (error_is_no_service(&error)) {
4648                         r = -EADDRNOTAVAIL;
4649                         goto finish;
4650                 }
4651
4652                 log_error("Failed to issue method call: %s", bus_error_message(&error));
4653                 r = -EIO;
4654                 goto finish;
4655         }
4656
4657         r = 0;
4658
4659 finish:
4660         if (m)
4661                 dbus_message_unref(m);
4662
4663         if (reply)
4664                 dbus_message_unref(reply);
4665
4666         if (bus) {
4667                 dbus_connection_flush(bus);
4668                 dbus_connection_close(bus);
4669                 dbus_connection_unref(bus);
4670         }
4671
4672         dbus_error_free(&error);
4673
4674         return r;
4675 }
4676
4677 static int talk_initctl(void) {
4678         struct init_request request;
4679         int r, fd;
4680         char rl;
4681
4682         if (!(rl = action_to_runlevel()))
4683                 return 0;
4684
4685         zero(request);
4686         request.magic = INIT_MAGIC;
4687         request.sleeptime = 0;
4688         request.cmd = INIT_CMD_RUNLVL;
4689         request.runlevel = rl;
4690
4691         if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4692
4693                 if (errno == ENOENT)
4694                         return 0;
4695
4696                 log_error("Failed to open "INIT_FIFO": %m");
4697                 return -errno;
4698         }
4699
4700         errno = 0;
4701         r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4702         close_nointr_nofail(fd);
4703
4704         if (r < 0) {
4705                 log_error("Failed to write to "INIT_FIFO": %m");
4706                 return errno ? -errno : -EIO;
4707         }
4708
4709         return 1;
4710 }
4711
4712 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4713
4714         static const struct {
4715                 const char* verb;
4716                 const enum {
4717                         MORE,
4718                         LESS,
4719                         EQUAL
4720                 } argc_cmp;
4721                 const int argc;
4722                 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4723         } verbs[] = {
4724                 { "list-units",            LESS,  1, list_units        },
4725                 { "list-jobs",             EQUAL, 1, list_jobs         },
4726                 { "clear-jobs",            EQUAL, 1, daemon_reload     },
4727                 { "load",                  MORE,  2, load_unit         },
4728                 { "cancel",                MORE,  2, cancel_job        },
4729                 { "start",                 MORE,  2, start_unit        },
4730                 { "stop",                  MORE,  2, start_unit        },
4731                 { "reload",                MORE,  2, start_unit        },
4732                 { "restart",               MORE,  2, start_unit        },
4733                 { "try-restart",           MORE,  2, start_unit        },
4734                 { "reload-or-restart",     MORE,  2, start_unit        },
4735                 { "reload-or-try-restart", MORE,  2, start_unit        },
4736                 { "force-reload",          MORE,  2, start_unit        }, /* For compatibility with SysV */
4737                 { "condrestart",           MORE,  2, start_unit        }, /* For compatibility with RH */
4738                 { "isolate",               EQUAL, 2, start_unit        },
4739                 { "is-active",             MORE,  2, check_unit        },
4740                 { "check",                 MORE,  2, check_unit        },
4741                 { "show",                  MORE,  1, show              },
4742                 { "status",                MORE,  2, show              },
4743                 { "monitor",               EQUAL, 1, monitor           },
4744                 { "dump",                  EQUAL, 1, dump              },
4745                 { "dot",                   EQUAL, 1, dot               },
4746                 { "snapshot",              LESS,  2, snapshot          },
4747                 { "delete",                MORE,  2, delete_snapshot   },
4748                 { "daemon-reload",         EQUAL, 1, daemon_reload     },
4749                 { "daemon-reexec",         EQUAL, 1, daemon_reload     },
4750                 { "daemon-exit",           EQUAL, 1, daemon_reload     },
4751                 { "show-environment",      EQUAL, 1, show_enviroment   },
4752                 { "set-environment",       MORE,  2, set_environment   },
4753                 { "unset-environment",     MORE,  2, set_environment   },
4754                 { "halt",                  EQUAL, 1, start_special     },
4755                 { "poweroff",              EQUAL, 1, start_special     },
4756                 { "reboot",                EQUAL, 1, start_special     },
4757                 { "default",               EQUAL, 1, start_special     },
4758                 { "rescue",                EQUAL, 1, start_special     },
4759                 { "emergency",             EQUAL, 1, start_special     },
4760                 { "reset-failed",          MORE,  1, reset_failed      },
4761                 { "enable",                MORE,  2, enable_unit       },
4762                 { "disable",               MORE,  2, enable_unit       },
4763                 { "is-enabled",            MORE,  2, enable_unit       }
4764         };
4765
4766         int left;
4767         unsigned i;
4768
4769         assert(argc >= 0);
4770         assert(argv);
4771         assert(error);
4772
4773         left = argc - optind;
4774
4775         if (left <= 0)
4776                 /* Special rule: no arguments means "list-units" */
4777                 i = 0;
4778         else {
4779                 if (streq(argv[optind], "help")) {
4780                         systemctl_help();
4781                         return 0;
4782                 }
4783
4784                 for (i = 0; i < ELEMENTSOF(verbs); i++)
4785                         if (streq(argv[optind], verbs[i].verb))
4786                                 break;
4787
4788                 if (i >= ELEMENTSOF(verbs)) {
4789                         log_error("Unknown operation %s", argv[optind]);
4790                         return -EINVAL;
4791                 }
4792         }
4793
4794         switch (verbs[i].argc_cmp) {
4795
4796         case EQUAL:
4797                 if (left != verbs[i].argc) {
4798                         log_error("Invalid number of arguments.");
4799                         return -EINVAL;
4800                 }
4801
4802                 break;
4803
4804         case MORE:
4805                 if (left < verbs[i].argc) {
4806                         log_error("Too few arguments.");
4807                         return -EINVAL;
4808                 }
4809
4810                 break;
4811
4812         case LESS:
4813                 if (left > verbs[i].argc) {
4814                         log_error("Too many arguments.");
4815                         return -EINVAL;
4816                 }
4817
4818                 break;
4819
4820         default:
4821                 assert_not_reached("Unknown comparison operator.");
4822         }
4823
4824         /* Require a bus connection for all operations but
4825          * enable/disable */
4826         if (!streq(verbs[i].verb, "enable") &&
4827             !streq(verbs[i].verb, "disable") &&
4828             !bus) {
4829                 log_error("Failed to get D-Bus connection: %s", error->message);
4830                 return -EIO;
4831         }
4832
4833         return verbs[i].dispatch(bus, argv + optind, left);
4834 }
4835
4836 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
4837         int fd = -1;
4838         struct msghdr msghdr;
4839         struct iovec iovec;
4840         union sockaddr_union sockaddr;
4841         struct shutdownd_command c;
4842
4843         zero(c);
4844         c.elapse = t;
4845         c.mode = mode;
4846         c.warn_wall = warn;
4847
4848         if (message)
4849                 strncpy(c.wall_message, message, sizeof(c.wall_message));
4850
4851         if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4852                 return -errno;
4853
4854         zero(sockaddr);
4855         sockaddr.sa.sa_family = AF_UNIX;
4856         sockaddr.un.sun_path[0] = 0;
4857         strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
4858
4859         zero(iovec);
4860         iovec.iov_base = (char*) &c;
4861         iovec.iov_len = sizeof(c);
4862
4863         zero(msghdr);
4864         msghdr.msg_name = &sockaddr;
4865         msghdr.msg_namelen = sizeof(sa_family_t) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
4866
4867         msghdr.msg_iov = &iovec;
4868         msghdr.msg_iovlen = 1;
4869
4870         if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
4871                 close_nointr_nofail(fd);
4872                 return -errno;
4873         }
4874
4875         close_nointr_nofail(fd);
4876         return 0;
4877 }
4878
4879 static int reload_with_fallback(DBusConnection *bus) {
4880
4881         if (bus) {
4882                 /* First, try systemd via D-Bus. */
4883                 if (daemon_reload(bus, NULL, 0) > 0)
4884                         return 0;
4885         }
4886
4887         /* Nothing else worked, so let's try signals */
4888         assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
4889
4890         if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
4891                 log_error("kill() failed: %m");
4892                 return -errno;
4893         }
4894
4895         return 0;
4896 }
4897
4898 static int start_with_fallback(DBusConnection *bus) {
4899
4900         if (bus) {
4901                 /* First, try systemd via D-Bus. */
4902                 if (start_unit(bus, NULL, 0) >= 0)
4903                         goto done;
4904         }
4905
4906         /* Hmm, talking to systemd via D-Bus didn't work. Then
4907          * let's try to talk to Upstart via D-Bus. */
4908         if (talk_upstart() > 0)
4909                 goto done;
4910
4911         /* Nothing else worked, so let's try
4912          * /dev/initctl */
4913         if (talk_initctl() > 0)
4914                 goto done;
4915
4916         log_error("Failed to talk to init daemon.");
4917         return -EIO;
4918
4919 done:
4920         warn_wall(arg_action);
4921         return 0;
4922 }
4923
4924 static int halt_main(DBusConnection *bus) {
4925         int r;
4926
4927         if (geteuid() != 0) {
4928                 log_error("Must be root.");
4929                 return -EPERM;
4930         }
4931
4932         if (arg_when > 0) {
4933                 char *m;
4934                 char date[FORMAT_TIMESTAMP_MAX];
4935
4936                 m = strv_join(arg_wall, " ");
4937                 r = send_shutdownd(arg_when,
4938                                    arg_action == ACTION_HALT     ? 'H' :
4939                                    arg_action == ACTION_POWEROFF ? 'P' :
4940                                                                    'r',
4941                                    !arg_no_wall,
4942                                    m);
4943                 free(m);
4944
4945                 if (r < 0)
4946                         log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
4947                 else {
4948                         log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
4949                                  format_timestamp(date, sizeof(date), arg_when));
4950                         return 0;
4951                 }
4952         }
4953
4954         if (!arg_dry && !arg_immediate)
4955                 return start_with_fallback(bus);
4956
4957         if (!arg_no_wtmp) {
4958                 if (sd_booted() > 0)
4959                         log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
4960                 else if ((r = utmp_put_shutdown(0)) < 0)
4961                         log_warning("Failed to write utmp record: %s", strerror(-r));
4962         }
4963
4964         if (!arg_no_sync)
4965                 sync();
4966
4967         if (arg_dry)
4968                 return 0;
4969
4970         /* Make sure C-A-D is handled by the kernel from this
4971          * point on... */
4972         reboot(RB_ENABLE_CAD);
4973
4974         switch (arg_action) {
4975
4976         case ACTION_HALT:
4977                 log_info("Halting.");
4978                 reboot(RB_HALT_SYSTEM);
4979                 break;
4980
4981         case ACTION_POWEROFF:
4982                 log_info("Powering off.");
4983                 reboot(RB_POWER_OFF);
4984                 break;
4985
4986         case ACTION_REBOOT:
4987                 log_info("Rebooting.");
4988                 reboot(RB_AUTOBOOT);
4989                 break;
4990
4991         default:
4992                 assert_not_reached("Unknown halt action.");
4993         }
4994
4995         /* We should never reach this. */
4996         return -ENOSYS;
4997 }
4998
4999 static int runlevel_main(void) {
5000         int r, runlevel, previous;
5001
5002         if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5003                 printf("unknown\n");
5004                 return r;
5005         }
5006
5007         printf("%c %c\n",
5008                previous <= 0 ? 'N' : previous,
5009                runlevel <= 0 ? 'N' : runlevel);
5010
5011         return 0;
5012 }
5013
5014 int main(int argc, char*argv[]) {
5015         int r, retval = EXIT_FAILURE;
5016         DBusConnection *bus = NULL;
5017         DBusError error;
5018
5019         dbus_error_init(&error);
5020
5021         log_parse_environment();
5022         log_open();
5023
5024         if ((r = parse_argv(argc, argv)) < 0)
5025                 goto finish;
5026         else if (r == 0) {
5027                 retval = EXIT_SUCCESS;
5028                 goto finish;
5029         }
5030
5031         /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5032          * let's shortcut this */
5033         if (arg_action == ACTION_RUNLEVEL) {
5034                 r = runlevel_main();
5035                 retval = r < 0 ? EXIT_FAILURE : r;
5036                 goto finish;
5037         }
5038
5039         bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5040
5041         switch (arg_action) {
5042
5043         case ACTION_SYSTEMCTL:
5044                 r = systemctl_main(bus, argc, argv, &error);
5045                 break;
5046
5047         case ACTION_HALT:
5048         case ACTION_POWEROFF:
5049         case ACTION_REBOOT:
5050                 r = halt_main(bus);
5051                 break;
5052
5053         case ACTION_RUNLEVEL2:
5054         case ACTION_RUNLEVEL3:
5055         case ACTION_RUNLEVEL4:
5056         case ACTION_RUNLEVEL5:
5057         case ACTION_RESCUE:
5058         case ACTION_EMERGENCY:
5059         case ACTION_DEFAULT:
5060                 r = start_with_fallback(bus);
5061                 break;
5062
5063         case ACTION_RELOAD:
5064         case ACTION_REEXEC:
5065                 r = reload_with_fallback(bus);
5066                 break;
5067
5068         case ACTION_CANCEL_SHUTDOWN:
5069                 r = send_shutdownd(0, 0, false, NULL);
5070                 break;
5071
5072         case ACTION_INVALID:
5073         case ACTION_RUNLEVEL:
5074         default:
5075                 assert_not_reached("Unknown action");
5076         }
5077
5078         retval = r < 0 ? EXIT_FAILURE : r;
5079
5080 finish:
5081
5082         if (bus) {
5083                 dbus_connection_flush(bus);
5084                 dbus_connection_close(bus);
5085                 dbus_connection_unref(bus);
5086         }
5087
5088         dbus_error_free(&error);
5089
5090         dbus_shutdown();
5091
5092         strv_free(arg_property);
5093
5094         return retval;
5095 }