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