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