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