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