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