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