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