chiark / gitweb /
cmdline: we actually want to parse the kernel cmdline in VMs, just not in containers
[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;
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, &exit_timestamp, true) < 0 ||
1793             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1794             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1795             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1796                 return -EIO;
1797
1798         i->ignore = ignore;
1799         i->start_timestamp = (usec_t) start_timestamp;
1800         i->exit_timestamp = (usec_t) exit_timestamp;
1801         i->pid = (pid_t) pid;
1802         i->code = code;
1803         i->status = status;
1804
1805         return 0;
1806 }
1807
1808 typedef struct UnitStatusInfo {
1809         const char *id;
1810         const char *load_state;
1811         const char *active_state;
1812         const char *sub_state;
1813
1814         const char *description;
1815         const char *following;
1816
1817         const char *path;
1818         const char *default_control_group;
1819
1820         usec_t inactive_exit_timestamp;
1821         usec_t active_enter_timestamp;
1822         usec_t active_exit_timestamp;
1823         usec_t inactive_enter_timestamp;
1824
1825         bool need_daemon_reload;
1826
1827         /* Service */
1828         pid_t main_pid;
1829         pid_t control_pid;
1830         const char *status_text;
1831         bool running:1;
1832 #ifdef HAVE_SYSV_COMPAT
1833         bool is_sysv:1;
1834 #endif
1835
1836         usec_t start_timestamp;
1837         usec_t exit_timestamp;
1838
1839         int exit_code, exit_status;
1840
1841         usec_t condition_timestamp;
1842         bool condition_result;
1843
1844         /* Socket */
1845         unsigned n_accepted;
1846         unsigned n_connections;
1847         bool accept;
1848
1849         /* Device */
1850         const char *sysfs_path;
1851
1852         /* Mount, Automount */
1853         const char *where;
1854
1855         /* Swap */
1856         const char *what;
1857
1858         LIST_HEAD(ExecStatusInfo, exec);
1859 } UnitStatusInfo;
1860
1861 static void print_status_info(UnitStatusInfo *i) {
1862         ExecStatusInfo *p;
1863         const char *on, *off, *ss;
1864         usec_t timestamp;
1865         char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1866         char since2[FORMAT_TIMESTAMP_MAX], *s2;
1867
1868         assert(i);
1869
1870         /* This shows pretty information about a unit. See
1871          * print_property() for a low-level property printer */
1872
1873         printf("%s", strna(i->id));
1874
1875         if (i->description && !streq_ptr(i->id, i->description))
1876                 printf(" - %s", i->description);
1877
1878         printf("\n");
1879
1880         if (i->following)
1881                 printf("\t  Follow: unit currently follows state of %s\n", i->following);
1882
1883         if (streq_ptr(i->load_state, "failed") ||
1884             streq_ptr(i->load_state, "banned")) {
1885                 on = ansi_highlight(true);
1886                 off = ansi_highlight(false);
1887         } else
1888                 on = off = "";
1889
1890         if (i->path)
1891                 printf("\t  Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1892         else
1893                 printf("\t  Loaded: %s%s%s\n", on, strna(i->load_state), off);
1894
1895         ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1896
1897         if (streq_ptr(i->active_state, "failed")) {
1898                 on = ansi_highlight(true);
1899                 off = ansi_highlight(false);
1900         } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1901                 on = ansi_highlight_green(true);
1902                 off = ansi_highlight_green(false);
1903         } else
1904                 on = off = "";
1905
1906         if (ss)
1907                 printf("\t  Active: %s%s (%s)%s",
1908                        on,
1909                        strna(i->active_state),
1910                        ss,
1911                        off);
1912         else
1913                 printf("\t  Active: %s%s%s",
1914                        on,
1915                        strna(i->active_state),
1916                        off);
1917
1918         timestamp = (streq_ptr(i->active_state, "active")      ||
1919                      streq_ptr(i->active_state, "reloading"))   ? i->active_enter_timestamp :
1920                     (streq_ptr(i->active_state, "inactive")    ||
1921                      streq_ptr(i->active_state, "failed"))      ? i->inactive_enter_timestamp :
1922                     streq_ptr(i->active_state, "activating")    ? i->inactive_exit_timestamp :
1923                                                                   i->active_exit_timestamp;
1924
1925         s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1926         s2 = format_timestamp(since2, sizeof(since2), timestamp);
1927
1928         if (s1)
1929                 printf(" since %s; %s\n", s2, s1);
1930         else if (s2)
1931                 printf(" since %s\n", s2);
1932         else
1933                 printf("\n");
1934
1935         if (!i->condition_result && i->condition_timestamp > 0) {
1936                 s1 = format_timestamp_pretty(since1, sizeof(since1), i->condition_timestamp);
1937                 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
1938
1939                 if (s1)
1940                         printf("\t          start condition failed at %s; %s\n", s2, s1);
1941                 else if (s2)
1942                         printf("\t          start condition failed at %s\n", s2);
1943         }
1944
1945         if (i->sysfs_path)
1946                 printf("\t  Device: %s\n", i->sysfs_path);
1947         if (i->where)
1948                 printf("\t   Where: %s\n", i->where);
1949         if (i->what)
1950                 printf("\t    What: %s\n", i->what);
1951
1952         if (i->accept)
1953                 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1954
1955         LIST_FOREACH(exec, p, i->exec) {
1956                 char *t;
1957                 bool good;
1958
1959                 /* Only show exited processes here */
1960                 if (p->code == 0)
1961                         continue;
1962
1963                 t = strv_join(p->argv, " ");
1964                 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
1965                 free(t);
1966
1967 #ifdef HAVE_SYSV_COMPAT
1968                 if (i->is_sysv)
1969                         good = is_clean_exit_lsb(p->code, p->status);
1970                 else
1971 #endif
1972                         good = is_clean_exit(p->code, p->status);
1973
1974                 if (!good) {
1975                         on = ansi_highlight(true);
1976                         off = ansi_highlight(false);
1977                 } else
1978                         on = off = "";
1979
1980                 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
1981
1982                 if (p->code == CLD_EXITED) {
1983                         const char *c;
1984
1985                         printf("status=%i", p->status);
1986
1987 #ifdef HAVE_SYSV_COMPAT
1988                         if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1989 #else
1990                         if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1991 #endif
1992                                 printf("/%s", c);
1993
1994                 } else
1995                         printf("signal=%s", signal_to_string(p->status));
1996
1997                 printf(")%s\n", off);
1998
1999                 on = off = NULL;
2000
2001                 if (i->main_pid == p->pid &&
2002                     i->start_timestamp == p->start_timestamp &&
2003                     i->exit_timestamp == p->start_timestamp)
2004                         /* Let's not show this twice */
2005                         i->main_pid = 0;
2006
2007                 if (p->pid == i->control_pid)
2008                         i->control_pid = 0;
2009         }
2010
2011         if (i->main_pid > 0 || i->control_pid > 0) {
2012                 printf("\t");
2013
2014                 if (i->main_pid > 0) {
2015                         printf("Main PID: %u", (unsigned) i->main_pid);
2016
2017                         if (i->running) {
2018                                 char *t = NULL;
2019                                 get_process_name(i->main_pid, &t);
2020                                 if (t) {
2021                                         printf(" (%s)", t);
2022                                         free(t);
2023                                 }
2024                         } else if (i->exit_code > 0) {
2025                                 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2026
2027                                 if (i->exit_code == CLD_EXITED) {
2028                                         const char *c;
2029
2030                                         printf("status=%i", i->exit_status);
2031
2032 #ifdef HAVE_SYSV_COMPAT
2033                                         if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
2034 #else
2035                                         if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
2036 #endif
2037                                                 printf("/%s", c);
2038
2039                                 } else
2040                                         printf("signal=%s", signal_to_string(i->exit_status));
2041                                 printf(")");
2042                         }
2043                 }
2044
2045                 if (i->main_pid > 0 && i->control_pid > 0)
2046                         printf(";");
2047
2048                 if (i->control_pid > 0) {
2049                         char *t = NULL;
2050
2051                         printf(" Control: %u", (unsigned) i->control_pid);
2052
2053                         get_process_name(i->control_pid, &t);
2054                         if (t) {
2055                                 printf(" (%s)", t);
2056                                 free(t);
2057                         }
2058                 }
2059
2060                 printf("\n");
2061         }
2062
2063         if (i->status_text)
2064                 printf("\t  Status: \"%s\"\n", i->status_text);
2065
2066         if (i->default_control_group) {
2067                 unsigned c;
2068
2069                 printf("\t  CGroup: %s\n", i->default_control_group);
2070
2071                 if (arg_transport != TRANSPORT_SSH) {
2072                         if ((c = columns()) > 18)
2073                                 c -= 18;
2074                         else
2075                                 c = 0;
2076
2077                         show_cgroup_by_path(i->default_control_group, "\t\t  ", c);
2078                 }
2079         }
2080
2081         if (i->need_daemon_reload)
2082                 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2083                        ansi_highlight(true),
2084                        ansi_highlight(false),
2085                        arg_user ? "--user" : "--system");
2086 }
2087
2088 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2089
2090         switch (dbus_message_iter_get_arg_type(iter)) {
2091
2092         case DBUS_TYPE_STRING: {
2093                 const char *s;
2094
2095                 dbus_message_iter_get_basic(iter, &s);
2096
2097                 if (s[0]) {
2098                         if (streq(name, "Id"))
2099                                 i->id = s;
2100                         else if (streq(name, "LoadState"))
2101                                 i->load_state = s;
2102                         else if (streq(name, "ActiveState"))
2103                                 i->active_state = s;
2104                         else if (streq(name, "SubState"))
2105                                 i->sub_state = s;
2106                         else if (streq(name, "Description"))
2107                                 i->description = s;
2108                         else if (streq(name, "FragmentPath"))
2109                                 i->path = s;
2110 #ifdef HAVE_SYSV_COMPAT
2111                         else if (streq(name, "SysVPath")) {
2112                                 i->is_sysv = true;
2113                                 i->path = s;
2114                         }
2115 #endif
2116                         else if (streq(name, "DefaultControlGroup"))
2117                                 i->default_control_group = s;
2118                         else if (streq(name, "StatusText"))
2119                                 i->status_text = s;
2120                         else if (streq(name, "SysFSPath"))
2121                                 i->sysfs_path = s;
2122                         else if (streq(name, "Where"))
2123                                 i->where = s;
2124                         else if (streq(name, "What"))
2125                                 i->what = s;
2126                         else if (streq(name, "Following"))
2127                                 i->following = s;
2128                 }
2129
2130                 break;
2131         }
2132
2133         case DBUS_TYPE_BOOLEAN: {
2134                 dbus_bool_t b;
2135
2136                 dbus_message_iter_get_basic(iter, &b);
2137
2138                 if (streq(name, "Accept"))
2139                         i->accept = b;
2140                 else if (streq(name, "NeedDaemonReload"))
2141                         i->need_daemon_reload = b;
2142                 else if (streq(name, "ConditionResult"))
2143                         i->condition_result = b;
2144
2145                 break;
2146         }
2147
2148         case DBUS_TYPE_UINT32: {
2149                 uint32_t u;
2150
2151                 dbus_message_iter_get_basic(iter, &u);
2152
2153                 if (streq(name, "MainPID")) {
2154                         if (u > 0) {
2155                                 i->main_pid = (pid_t) u;
2156                                 i->running = true;
2157                         }
2158                 } else if (streq(name, "ControlPID"))
2159                         i->control_pid = (pid_t) u;
2160                 else if (streq(name, "ExecMainPID")) {
2161                         if (u > 0)
2162                                 i->main_pid = (pid_t) u;
2163                 } else if (streq(name, "NAccepted"))
2164                         i->n_accepted = u;
2165                 else if (streq(name, "NConnections"))
2166                         i->n_connections = u;
2167
2168                 break;
2169         }
2170
2171         case DBUS_TYPE_INT32: {
2172                 int32_t j;
2173
2174                 dbus_message_iter_get_basic(iter, &j);
2175
2176                 if (streq(name, "ExecMainCode"))
2177                         i->exit_code = (int) j;
2178                 else if (streq(name, "ExecMainStatus"))
2179                         i->exit_status = (int) j;
2180
2181                 break;
2182         }
2183
2184         case DBUS_TYPE_UINT64: {
2185                 uint64_t u;
2186
2187                 dbus_message_iter_get_basic(iter, &u);
2188
2189                 if (streq(name, "ExecMainStartTimestamp"))
2190                         i->start_timestamp = (usec_t) u;
2191                 else if (streq(name, "ExecMainExitTimestamp"))
2192                         i->exit_timestamp = (usec_t) u;
2193                 else if (streq(name, "ActiveEnterTimestamp"))
2194                         i->active_enter_timestamp = (usec_t) u;
2195                 else if (streq(name, "InactiveEnterTimestamp"))
2196                         i->inactive_enter_timestamp = (usec_t) u;
2197                 else if (streq(name, "InactiveExitTimestamp"))
2198                         i->inactive_exit_timestamp = (usec_t) u;
2199                 else if (streq(name, "ActiveExitTimestamp"))
2200                         i->active_exit_timestamp = (usec_t) u;
2201                 else if (streq(name, "ConditionTimestamp"))
2202                         i->condition_timestamp = (usec_t) u;
2203
2204                 break;
2205         }
2206
2207         case DBUS_TYPE_ARRAY: {
2208
2209                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2210                     startswith(name, "Exec")) {
2211                         DBusMessageIter sub;
2212
2213                         dbus_message_iter_recurse(iter, &sub);
2214                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2215                                 ExecStatusInfo *info;
2216                                 int r;
2217
2218                                 if (!(info = new0(ExecStatusInfo, 1)))
2219                                         return -ENOMEM;
2220
2221                                 if (!(info->name = strdup(name))) {
2222                                         free(info);
2223                                         return -ENOMEM;
2224                                 }
2225
2226                                 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2227                                         free(info);
2228                                         return r;
2229                                 }
2230
2231                                 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2232
2233                                 dbus_message_iter_next(&sub);
2234                         }
2235                 }
2236
2237                 break;
2238         }
2239         }
2240
2241         return 0;
2242 }
2243
2244 static int print_property(const char *name, DBusMessageIter *iter) {
2245         assert(name);
2246         assert(iter);
2247
2248         /* This is a low-level property printer, see
2249          * print_status_info() for the nicer output */
2250
2251         if (arg_property && !strv_find(arg_property, name))
2252                 return 0;
2253
2254         switch (dbus_message_iter_get_arg_type(iter)) {
2255
2256         case DBUS_TYPE_STRING: {
2257                 const char *s;
2258                 dbus_message_iter_get_basic(iter, &s);
2259
2260                 if (arg_all || s[0])
2261                         printf("%s=%s\n", name, s);
2262
2263                 return 0;
2264         }
2265
2266         case DBUS_TYPE_BOOLEAN: {
2267                 dbus_bool_t b;
2268                 dbus_message_iter_get_basic(iter, &b);
2269                 printf("%s=%s\n", name, yes_no(b));
2270
2271                 return 0;
2272         }
2273
2274         case DBUS_TYPE_UINT64: {
2275                 uint64_t u;
2276                 dbus_message_iter_get_basic(iter, &u);
2277
2278                 /* Yes, heuristics! But we can change this check
2279                  * should it turn out to not be sufficient */
2280
2281                 if (strstr(name, "Timestamp")) {
2282                         char timestamp[FORMAT_TIMESTAMP_MAX], *t;
2283
2284                         if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
2285                                 printf("%s=%s\n", name, strempty(t));
2286                 } else if (strstr(name, "USec")) {
2287                         char timespan[FORMAT_TIMESPAN_MAX];
2288
2289                         printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
2290                 } else
2291                         printf("%s=%llu\n", name, (unsigned long long) u);
2292
2293                 return 0;
2294         }
2295
2296         case DBUS_TYPE_UINT32: {
2297                 uint32_t u;
2298                 dbus_message_iter_get_basic(iter, &u);
2299
2300                 if (strstr(name, "UMask") || strstr(name, "Mode"))
2301                         printf("%s=%04o\n", name, u);
2302                 else
2303                         printf("%s=%u\n", name, (unsigned) u);
2304
2305                 return 0;
2306         }
2307
2308         case DBUS_TYPE_INT32: {
2309                 int32_t i;
2310                 dbus_message_iter_get_basic(iter, &i);
2311
2312                 printf("%s=%i\n", name, (int) i);
2313                 return 0;
2314         }
2315
2316         case DBUS_TYPE_DOUBLE: {
2317                 double d;
2318                 dbus_message_iter_get_basic(iter, &d);
2319
2320                 printf("%s=%g\n", name, d);
2321                 return 0;
2322         }
2323
2324         case DBUS_TYPE_STRUCT: {
2325                 DBusMessageIter sub;
2326                 dbus_message_iter_recurse(iter, &sub);
2327
2328                 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2329                         uint32_t u;
2330
2331                         dbus_message_iter_get_basic(&sub, &u);
2332
2333                         if (u)
2334                                 printf("%s=%u\n", name, (unsigned) u);
2335                         else if (arg_all)
2336                                 printf("%s=\n", name);
2337
2338                         return 0;
2339                 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2340                         const char *s;
2341
2342                         dbus_message_iter_get_basic(&sub, &s);
2343
2344                         if (arg_all || s[0])
2345                                 printf("%s=%s\n", name, s);
2346
2347                         return 0;
2348                 }
2349
2350                 break;
2351         }
2352
2353         case DBUS_TYPE_ARRAY:
2354
2355                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2356                         DBusMessageIter sub;
2357                         bool space = false;
2358
2359                         dbus_message_iter_recurse(iter, &sub);
2360                         if (arg_all ||
2361                             dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2362                                 printf("%s=", name);
2363
2364                                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2365                                         const char *s;
2366
2367                                         assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2368                                         dbus_message_iter_get_basic(&sub, &s);
2369                                         printf("%s%s", space ? " " : "", s);
2370
2371                                         space = true;
2372                                         dbus_message_iter_next(&sub);
2373                                 }
2374
2375                                 puts("");
2376                         }
2377
2378                         return 0;
2379
2380                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2381                         DBusMessageIter sub;
2382
2383                         dbus_message_iter_recurse(iter, &sub);
2384                         if (arg_all ||
2385                             dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2386                                 printf("%s=", name);
2387
2388                                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2389                                         uint8_t u;
2390
2391                                         assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2392                                         dbus_message_iter_get_basic(&sub, &u);
2393                                         printf("%02x", u);
2394
2395                                         dbus_message_iter_next(&sub);
2396                                 }
2397
2398                                 puts("");
2399                         }
2400
2401                         return 0;
2402
2403                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
2404                         DBusMessageIter sub, sub2;
2405
2406                         dbus_message_iter_recurse(iter, &sub);
2407                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2408                                 const char *path;
2409                                 dbus_bool_t ignore;
2410
2411                                 dbus_message_iter_recurse(&sub, &sub2);
2412
2413                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
2414                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
2415                                         printf("EnvironmentFile=%s (ignore=%s)\n", path, yes_no(ignore));
2416
2417                                 dbus_message_iter_next(&sub);
2418                         }
2419
2420                         return 0;
2421
2422                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2423                         DBusMessageIter sub, sub2;
2424
2425                         dbus_message_iter_recurse(iter, &sub);
2426                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2427                                 const char *type, *path;
2428
2429                                 dbus_message_iter_recurse(&sub, &sub2);
2430
2431                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2432                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2433                                         printf("%s=%s\n", type, path);
2434
2435                                 dbus_message_iter_next(&sub);
2436                         }
2437
2438                         return 0;
2439
2440                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2441                         DBusMessageIter sub, sub2;
2442
2443                         dbus_message_iter_recurse(iter, &sub);
2444                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2445                                 const char *base;
2446                                 uint64_t value, next_elapse;
2447
2448                                 dbus_message_iter_recurse(&sub, &sub2);
2449
2450                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2451                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2452                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2453                                         char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2454
2455                                         printf("%s={ value=%s ; next_elapse=%s }\n",
2456                                                base,
2457                                                format_timespan(timespan1, sizeof(timespan1), value),
2458                                                format_timespan(timespan2, sizeof(timespan2), next_elapse));
2459                                 }
2460
2461                                 dbus_message_iter_next(&sub);
2462                         }
2463
2464                         return 0;
2465
2466                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2467                         DBusMessageIter sub;
2468
2469                         dbus_message_iter_recurse(iter, &sub);
2470                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2471                                 ExecStatusInfo info;
2472
2473                                 zero(info);
2474                                 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2475                                         char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2476                                         char *t;
2477
2478                                         t = strv_join(info.argv, " ");
2479
2480                                         printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2481                                                name,
2482                                                strna(info.path),
2483                                                strna(t),
2484                                                yes_no(info.ignore),
2485                                                strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2486                                                strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2487                                                (unsigned) info. pid,
2488                                                sigchld_code_to_string(info.code),
2489                                                info.status,
2490                                                info.code == CLD_EXITED ? "" : "/",
2491                                                strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2492
2493                                         free(t);
2494                                 }
2495
2496                                 free(info.path);
2497                                 strv_free(info.argv);
2498
2499                                 dbus_message_iter_next(&sub);
2500                         }
2501
2502                         return 0;
2503                 }
2504
2505                 break;
2506         }
2507
2508         if (arg_all)
2509                 printf("%s=[unprintable]\n", name);
2510
2511         return 0;
2512 }
2513
2514 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2515         DBusMessage *m = NULL, *reply = NULL;
2516         const char *interface = "";
2517         int r;
2518         DBusError error;
2519         DBusMessageIter iter, sub, sub2, sub3;
2520         UnitStatusInfo info;
2521         ExecStatusInfo *p;
2522
2523         assert(bus);
2524         assert(path);
2525         assert(new_line);
2526
2527         zero(info);
2528         dbus_error_init(&error);
2529
2530         if (!(m = dbus_message_new_method_call(
2531                               "org.freedesktop.systemd1",
2532                               path,
2533                               "org.freedesktop.DBus.Properties",
2534                               "GetAll"))) {
2535                 log_error("Could not allocate message.");
2536                 r = -ENOMEM;
2537                 goto finish;
2538         }
2539
2540         if (!dbus_message_append_args(m,
2541                                       DBUS_TYPE_STRING, &interface,
2542                                       DBUS_TYPE_INVALID)) {
2543                 log_error("Could not append arguments to message.");
2544                 r = -ENOMEM;
2545                 goto finish;
2546         }
2547
2548         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2549                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2550                 r = -EIO;
2551                 goto finish;
2552         }
2553
2554         if (!dbus_message_iter_init(reply, &iter) ||
2555             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2556             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY)  {
2557                 log_error("Failed to parse reply.");
2558                 r = -EIO;
2559                 goto finish;
2560         }
2561
2562         dbus_message_iter_recurse(&iter, &sub);
2563
2564         if (*new_line)
2565                 printf("\n");
2566
2567         *new_line = true;
2568
2569         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2570                 const char *name;
2571
2572                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2573                         log_error("Failed to parse reply.");
2574                         r = -EIO;
2575                         goto finish;
2576                 }
2577
2578                 dbus_message_iter_recurse(&sub, &sub2);
2579
2580                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2581                         log_error("Failed to parse reply.");
2582                         r = -EIO;
2583                         goto finish;
2584                 }
2585
2586                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT)  {
2587                         log_error("Failed to parse reply.");
2588                         r = -EIO;
2589                         goto finish;
2590                 }
2591
2592                 dbus_message_iter_recurse(&sub2, &sub3);
2593
2594                 if (show_properties)
2595                         r = print_property(name, &sub3);
2596                 else
2597                         r = status_property(name, &sub3, &info);
2598
2599                 if (r < 0) {
2600                         log_error("Failed to parse reply.");
2601                         r = -EIO;
2602                         goto finish;
2603                 }
2604
2605                 dbus_message_iter_next(&sub);
2606         }
2607
2608         r = 0;
2609
2610         if (!show_properties)
2611                 print_status_info(&info);
2612
2613         if (!streq_ptr(info.active_state, "active") &&
2614             !streq_ptr(info.active_state, "reloading") &&
2615             streq(verb, "status"))
2616                 /* According to LSB: "program not running" */
2617                 r = 3;
2618
2619         while ((p = info.exec)) {
2620                 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2621                 exec_status_info_free(p);
2622         }
2623
2624 finish:
2625         if (m)
2626                 dbus_message_unref(m);
2627
2628         if (reply)
2629                 dbus_message_unref(reply);
2630
2631         dbus_error_free(&error);
2632
2633         return r;
2634 }
2635
2636 static int show(DBusConnection *bus, char **args, unsigned n) {
2637         DBusMessage *m = NULL, *reply = NULL;
2638         int r, ret = 0;
2639         DBusError error;
2640         unsigned i;
2641         bool show_properties, new_line = false;
2642
2643         assert(bus);
2644         assert(args);
2645
2646         dbus_error_init(&error);
2647
2648         show_properties = !streq(args[0], "status");
2649
2650         if (show_properties)
2651                 pager_open();
2652
2653         if (show_properties && n <= 1) {
2654                 /* If not argument is specified inspect the manager
2655                  * itself */
2656
2657                 ret = show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2658                 goto finish;
2659         }
2660
2661         for (i = 1; i < n; i++) {
2662                 const char *path = NULL;
2663                 uint32_t id;
2664
2665                 if (safe_atou32(args[i], &id) < 0) {
2666
2667                         /* Interpret as unit name */
2668
2669                         if (!(m = dbus_message_new_method_call(
2670                                               "org.freedesktop.systemd1",
2671                                               "/org/freedesktop/systemd1",
2672                                               "org.freedesktop.systemd1.Manager",
2673                                               "LoadUnit"))) {
2674                                 log_error("Could not allocate message.");
2675                                 ret = -ENOMEM;
2676                                 goto finish;
2677                         }
2678
2679                         if (!dbus_message_append_args(m,
2680                                                       DBUS_TYPE_STRING, &args[i],
2681                                                       DBUS_TYPE_INVALID)) {
2682                                 log_error("Could not append arguments to message.");
2683                                 ret = -ENOMEM;
2684                                 goto finish;
2685                         }
2686
2687                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2688
2689                                 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2690                                         log_error("Failed to issue method call: %s", bus_error_message(&error));
2691                                         ret = -EIO;
2692                                         goto finish;
2693                                 }
2694
2695                                 dbus_error_free(&error);
2696
2697                                 dbus_message_unref(m);
2698                                 if (!(m = dbus_message_new_method_call(
2699                                                       "org.freedesktop.systemd1",
2700                                                       "/org/freedesktop/systemd1",
2701                                                       "org.freedesktop.systemd1.Manager",
2702                                                       "GetUnit"))) {
2703                                         log_error("Could not allocate message.");
2704                                         ret = -ENOMEM;
2705                                         goto finish;
2706                                 }
2707
2708                                 if (!dbus_message_append_args(m,
2709                                                               DBUS_TYPE_STRING, &args[i],
2710                                                               DBUS_TYPE_INVALID)) {
2711                                         log_error("Could not append arguments to message.");
2712                                         ret = -ENOMEM;
2713                                         goto finish;
2714                                 }
2715
2716                                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2717                                         log_error("Failed to issue method call: %s", bus_error_message(&error));
2718
2719                                         if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2720                                                 ret = 4; /* According to LSB: "program or service status is unknown" */
2721                                         else
2722                                                 ret = -EIO;
2723                                         goto finish;
2724                                 }
2725                         }
2726
2727                 } else if (show_properties) {
2728
2729                         /* Interpret as job id */
2730
2731                         if (!(m = dbus_message_new_method_call(
2732                                               "org.freedesktop.systemd1",
2733                                               "/org/freedesktop/systemd1",
2734                                               "org.freedesktop.systemd1.Manager",
2735                                               "GetJob"))) {
2736                                 log_error("Could not allocate message.");
2737                                 ret = -ENOMEM;
2738                                 goto finish;
2739                         }
2740
2741                         if (!dbus_message_append_args(m,
2742                                                       DBUS_TYPE_UINT32, &id,
2743                                                       DBUS_TYPE_INVALID)) {
2744                                 log_error("Could not append arguments to message.");
2745                                 ret = -ENOMEM;
2746                                 goto finish;
2747                         }
2748
2749                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2750                                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2751                                 ret = -EIO;
2752                                 goto finish;
2753                         }
2754                 } else {
2755
2756                         /* Interpret as PID */
2757
2758                         if (!(m = dbus_message_new_method_call(
2759                                               "org.freedesktop.systemd1",
2760                                               "/org/freedesktop/systemd1",
2761                                               "org.freedesktop.systemd1.Manager",
2762                                               "GetUnitByPID"))) {
2763                                 log_error("Could not allocate message.");
2764                                 ret = -ENOMEM;
2765                                 goto finish;
2766                         }
2767
2768                         if (!dbus_message_append_args(m,
2769                                                       DBUS_TYPE_UINT32, &id,
2770                                                       DBUS_TYPE_INVALID)) {
2771                                 log_error("Could not append arguments to message.");
2772                                 ret = -ENOMEM;
2773                                 goto finish;
2774                         }
2775
2776                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2777                                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2778                                 ret = -EIO;
2779                                 goto finish;
2780                         }
2781                 }
2782
2783                 if (!dbus_message_get_args(reply, &error,
2784                                            DBUS_TYPE_OBJECT_PATH, &path,
2785                                            DBUS_TYPE_INVALID)) {
2786                         log_error("Failed to parse reply: %s", bus_error_message(&error));
2787                         ret = -EIO;
2788                         goto finish;
2789                 }
2790
2791                 if ((r = show_one(args[0], bus, path, show_properties, &new_line)) != 0)
2792                         ret = r;
2793
2794                 dbus_message_unref(m);
2795                 dbus_message_unref(reply);
2796                 m = reply = NULL;
2797         }
2798
2799 finish:
2800         if (m)
2801                 dbus_message_unref(m);
2802
2803         if (reply)
2804                 dbus_message_unref(reply);
2805
2806         dbus_error_free(&error);
2807
2808         return ret;
2809 }
2810
2811 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2812         DBusError error;
2813         DBusMessage *m = NULL, *reply = NULL;
2814
2815         assert(connection);
2816         assert(message);
2817
2818         dbus_error_init(&error);
2819
2820         log_debug("Got D-Bus request: %s.%s() on %s",
2821                   dbus_message_get_interface(message),
2822                   dbus_message_get_member(message),
2823                   dbus_message_get_path(message));
2824
2825         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2826                 log_error("Warning! D-Bus connection terminated.");
2827                 dbus_connection_close(connection);
2828
2829         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2830                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2831                 const char *id, *path;
2832
2833                 if (!dbus_message_get_args(message, &error,
2834                                            DBUS_TYPE_STRING, &id,
2835                                            DBUS_TYPE_OBJECT_PATH, &path,
2836                                            DBUS_TYPE_INVALID))
2837                         log_error("Failed to parse message: %s", bus_error_message(&error));
2838                 else if (streq(dbus_message_get_member(message), "UnitNew"))
2839                         printf("Unit %s added.\n", id);
2840                 else
2841                         printf("Unit %s removed.\n", id);
2842
2843         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew")) {
2844                 uint32_t id;
2845                 const char *path;
2846
2847                 if (!dbus_message_get_args(message, &error,
2848                                            DBUS_TYPE_UINT32, &id,
2849                                            DBUS_TYPE_OBJECT_PATH, &path,
2850                                            DBUS_TYPE_INVALID))
2851                         log_error("Failed to parse message: %s", bus_error_message(&error));
2852                 else
2853                         printf("Job %u added.\n", id);
2854
2855
2856         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2857                 uint32_t id;
2858                 const char *path, *result;
2859
2860                 if (!dbus_message_get_args(message, &error,
2861                                            DBUS_TYPE_UINT32, &id,
2862                                            DBUS_TYPE_OBJECT_PATH, &path,
2863                                            DBUS_TYPE_STRING, &result,
2864                                            DBUS_TYPE_INVALID))
2865                         log_error("Failed to parse message: %s", bus_error_message(&error));
2866                 else
2867                         printf("Job %u removed (result=%s).\n", id, result);
2868
2869
2870         } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2871
2872                 const char *path, *interface, *property = "Id";
2873                 DBusMessageIter iter, sub;
2874
2875                 path = dbus_message_get_path(message);
2876
2877                 if (!dbus_message_get_args(message, &error,
2878                                           DBUS_TYPE_STRING, &interface,
2879                                           DBUS_TYPE_INVALID)) {
2880                         log_error("Failed to parse message: %s", bus_error_message(&error));
2881                         goto finish;
2882                 }
2883
2884                 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2885                     !streq(interface, "org.freedesktop.systemd1.Unit"))
2886                         goto finish;
2887
2888                 if (!(m = dbus_message_new_method_call(
2889                               "org.freedesktop.systemd1",
2890                               path,
2891                               "org.freedesktop.DBus.Properties",
2892                               "Get"))) {
2893                         log_error("Could not allocate message.");
2894                         goto oom;
2895                 }
2896
2897                 if (!dbus_message_append_args(m,
2898                                               DBUS_TYPE_STRING, &interface,
2899                                               DBUS_TYPE_STRING, &property,
2900                                               DBUS_TYPE_INVALID)) {
2901                         log_error("Could not append arguments to message.");
2902                         goto finish;
2903                 }
2904
2905                 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2906                         log_error("Failed to issue method call: %s", bus_error_message(&error));
2907                         goto finish;
2908                 }
2909
2910                 if (!dbus_message_iter_init(reply, &iter) ||
2911                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
2912                         log_error("Failed to parse reply.");
2913                         goto finish;
2914                 }
2915
2916                 dbus_message_iter_recurse(&iter, &sub);
2917
2918                 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2919                         const char *id;
2920
2921                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
2922                                 log_error("Failed to parse reply.");
2923                                 goto finish;
2924                         }
2925
2926                         dbus_message_iter_get_basic(&sub, &id);
2927                         printf("Unit %s changed.\n", id);
2928                 } else {
2929                         uint32_t id;
2930
2931                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32)  {
2932                                 log_error("Failed to parse reply.");
2933                                 goto finish;
2934                         }
2935
2936                         dbus_message_iter_get_basic(&sub, &id);
2937                         printf("Job %u changed.\n", id);
2938                 }
2939         }
2940
2941 finish:
2942         if (m)
2943                 dbus_message_unref(m);
2944
2945         if (reply)
2946                 dbus_message_unref(reply);
2947
2948         dbus_error_free(&error);
2949         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2950
2951 oom:
2952         if (m)
2953                 dbus_message_unref(m);
2954
2955         if (reply)
2956                 dbus_message_unref(reply);
2957
2958         dbus_error_free(&error);
2959         return DBUS_HANDLER_RESULT_NEED_MEMORY;
2960 }
2961
2962 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2963         DBusMessage *m = NULL, *reply = NULL;
2964         DBusError error;
2965         int r;
2966
2967         dbus_error_init(&error);
2968
2969         if (!private_bus) {
2970                 dbus_bus_add_match(bus,
2971                                    "type='signal',"
2972                                    "sender='org.freedesktop.systemd1',"
2973                                    "interface='org.freedesktop.systemd1.Manager',"
2974                                    "path='/org/freedesktop/systemd1'",
2975                                    &error);
2976
2977                 if (dbus_error_is_set(&error)) {
2978                         log_error("Failed to add match: %s", bus_error_message(&error));
2979                         r = -EIO;
2980                         goto finish;
2981                 }
2982
2983                 dbus_bus_add_match(bus,
2984                                    "type='signal',"
2985                                    "sender='org.freedesktop.systemd1',"
2986                                    "interface='org.freedesktop.DBus.Properties',"
2987                                    "member='PropertiesChanged'",
2988                                    &error);
2989
2990                 if (dbus_error_is_set(&error)) {
2991                         log_error("Failed to add match: %s", bus_error_message(&error));
2992                         r = -EIO;
2993                         goto finish;
2994                 }
2995         }
2996
2997         if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2998                 log_error("Failed to add filter.");
2999                 r = -ENOMEM;
3000                 goto finish;
3001         }
3002
3003         if (!(m = dbus_message_new_method_call(
3004                               "org.freedesktop.systemd1",
3005                               "/org/freedesktop/systemd1",
3006                               "org.freedesktop.systemd1.Manager",
3007                               "Subscribe"))) {
3008                 log_error("Could not allocate message.");
3009                 r = -ENOMEM;
3010                 goto finish;
3011         }
3012
3013         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3014                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3015                 r = -EIO;
3016                 goto finish;
3017         }
3018
3019         while (dbus_connection_read_write_dispatch(bus, -1))
3020                 ;
3021
3022         r = 0;
3023
3024 finish:
3025
3026         /* This is slightly dirty, since we don't undo the filter or the matches. */
3027
3028         if (m)
3029                 dbus_message_unref(m);
3030
3031         if (reply)
3032                 dbus_message_unref(reply);
3033
3034         dbus_error_free(&error);
3035
3036         return r;
3037 }
3038
3039 static int dump(DBusConnection *bus, char **args, unsigned n) {
3040         DBusMessage *m = NULL, *reply = NULL;
3041         DBusError error;
3042         int r;
3043         const char *text;
3044
3045         dbus_error_init(&error);
3046
3047         pager_open();
3048
3049         if (!(m = dbus_message_new_method_call(
3050                               "org.freedesktop.systemd1",
3051                               "/org/freedesktop/systemd1",
3052                               "org.freedesktop.systemd1.Manager",
3053                               "Dump"))) {
3054                 log_error("Could not allocate message.");
3055                 return -ENOMEM;
3056         }
3057
3058         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3059                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3060                 r = -EIO;
3061                 goto finish;
3062         }
3063
3064         if (!dbus_message_get_args(reply, &error,
3065                                    DBUS_TYPE_STRING, &text,
3066                                    DBUS_TYPE_INVALID)) {
3067                 log_error("Failed to parse reply: %s", bus_error_message(&error));
3068                 r = -EIO;
3069                 goto finish;
3070         }
3071
3072         fputs(text, stdout);
3073
3074         r = 0;
3075
3076 finish:
3077         if (m)
3078                 dbus_message_unref(m);
3079
3080         if (reply)
3081                 dbus_message_unref(reply);
3082
3083         dbus_error_free(&error);
3084
3085         return r;
3086 }
3087
3088 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
3089         DBusMessage *m = NULL, *reply = NULL;
3090         DBusError error;
3091         int r;
3092         const char *name = "", *path, *id;
3093         dbus_bool_t cleanup = FALSE;
3094         DBusMessageIter iter, sub;
3095         const char
3096                 *interface = "org.freedesktop.systemd1.Unit",
3097                 *property = "Id";
3098
3099         dbus_error_init(&error);
3100
3101         if (!(m = dbus_message_new_method_call(
3102                               "org.freedesktop.systemd1",
3103                               "/org/freedesktop/systemd1",
3104                               "org.freedesktop.systemd1.Manager",
3105                               "CreateSnapshot"))) {
3106                 log_error("Could not allocate message.");
3107                 return -ENOMEM;
3108         }
3109
3110         if (n > 1)
3111                 name = args[1];
3112
3113         if (!dbus_message_append_args(m,
3114                                       DBUS_TYPE_STRING, &name,
3115                                       DBUS_TYPE_BOOLEAN, &cleanup,
3116                                       DBUS_TYPE_INVALID)) {
3117                 log_error("Could not append arguments to message.");
3118                 r = -ENOMEM;
3119                 goto finish;
3120         }
3121
3122         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3123                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3124                 r = -EIO;
3125                 goto finish;
3126         }
3127
3128         if (!dbus_message_get_args(reply, &error,
3129                                    DBUS_TYPE_OBJECT_PATH, &path,
3130                                    DBUS_TYPE_INVALID)) {
3131                 log_error("Failed to parse reply: %s", bus_error_message(&error));
3132                 r = -EIO;
3133                 goto finish;
3134         }
3135
3136         dbus_message_unref(m);
3137         if (!(m = dbus_message_new_method_call(
3138                               "org.freedesktop.systemd1",
3139                               path,
3140                               "org.freedesktop.DBus.Properties",
3141                               "Get"))) {
3142                 log_error("Could not allocate message.");
3143                 return -ENOMEM;
3144         }
3145
3146         if (!dbus_message_append_args(m,
3147                                       DBUS_TYPE_STRING, &interface,
3148                                       DBUS_TYPE_STRING, &property,
3149                                       DBUS_TYPE_INVALID)) {
3150                 log_error("Could not append arguments to message.");
3151                 r = -ENOMEM;
3152                 goto finish;
3153         }
3154
3155         dbus_message_unref(reply);
3156         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3157                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3158                 r = -EIO;
3159                 goto finish;
3160         }
3161
3162         if (!dbus_message_iter_init(reply, &iter) ||
3163             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
3164                 log_error("Failed to parse reply.");
3165                 r = -EIO;
3166                 goto finish;
3167         }
3168
3169         dbus_message_iter_recurse(&iter, &sub);
3170
3171         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
3172                 log_error("Failed to parse reply.");
3173                 r = -EIO;
3174                 goto finish;
3175         }
3176
3177         dbus_message_iter_get_basic(&sub, &id);
3178
3179         if (!arg_quiet)
3180                 puts(id);
3181         r = 0;
3182
3183 finish:
3184         if (m)
3185                 dbus_message_unref(m);
3186
3187         if (reply)
3188                 dbus_message_unref(reply);
3189
3190         dbus_error_free(&error);
3191
3192         return r;
3193 }
3194
3195 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
3196         DBusMessage *m = NULL, *reply = NULL;
3197         int r;
3198         DBusError error;
3199         unsigned i;
3200
3201         assert(bus);
3202         assert(args);
3203
3204         dbus_error_init(&error);
3205
3206         for (i = 1; i < n; i++) {
3207                 const char *path = NULL;
3208
3209                 if (!(m = dbus_message_new_method_call(
3210                                       "org.freedesktop.systemd1",
3211                                       "/org/freedesktop/systemd1",
3212                                       "org.freedesktop.systemd1.Manager",
3213                                       "GetUnit"))) {
3214                         log_error("Could not allocate message.");
3215                         r = -ENOMEM;
3216                         goto finish;
3217                 }
3218
3219                 if (!dbus_message_append_args(m,
3220                                               DBUS_TYPE_STRING, &args[i],
3221                                               DBUS_TYPE_INVALID)) {
3222                         log_error("Could not append arguments to message.");
3223                         r = -ENOMEM;
3224                         goto finish;
3225                 }
3226
3227                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3228                         log_error("Failed to issue method call: %s", bus_error_message(&error));
3229                         r = -EIO;
3230                         goto finish;
3231                 }
3232
3233                 if (!dbus_message_get_args(reply, &error,
3234                                            DBUS_TYPE_OBJECT_PATH, &path,
3235                                            DBUS_TYPE_INVALID)) {
3236                         log_error("Failed to parse reply: %s", bus_error_message(&error));
3237                         r = -EIO;
3238                         goto finish;
3239                 }
3240
3241                 dbus_message_unref(m);
3242                 if (!(m = dbus_message_new_method_call(
3243                                       "org.freedesktop.systemd1",
3244                                       path,
3245                                       "org.freedesktop.systemd1.Snapshot",
3246                                       "Remove"))) {
3247                         log_error("Could not allocate message.");
3248                         r = -ENOMEM;
3249                         goto finish;
3250                 }
3251
3252                 dbus_message_unref(reply);
3253                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3254                         log_error("Failed to issue method call: %s", bus_error_message(&error));
3255                         r = -EIO;
3256                         goto finish;
3257                 }
3258
3259                 dbus_message_unref(m);
3260                 dbus_message_unref(reply);
3261                 m = reply = NULL;
3262         }
3263
3264         r = 0;
3265
3266 finish:
3267         if (m)
3268                 dbus_message_unref(m);
3269
3270         if (reply)
3271                 dbus_message_unref(reply);
3272
3273         dbus_error_free(&error);
3274
3275         return r;
3276 }
3277
3278 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
3279         DBusMessage *m = NULL, *reply = NULL;
3280         DBusError error;
3281         int r;
3282         const char *method;
3283
3284         dbus_error_init(&error);
3285
3286         if (arg_action == ACTION_RELOAD)
3287                 method = "Reload";
3288         else if (arg_action == ACTION_REEXEC)
3289                 method = "Reexecute";
3290         else {
3291                 assert(arg_action == ACTION_SYSTEMCTL);
3292
3293                 method =
3294                         streq(args[0], "clear-jobs")    ||
3295                         streq(args[0], "cancel")        ? "ClearJobs" :
3296                         streq(args[0], "daemon-reexec") ? "Reexecute" :
3297                         streq(args[0], "reset-failed")  ? "ResetFailed" :
3298                         streq(args[0], "halt")          ? "Halt" :
3299                         streq(args[0], "poweroff")      ? "PowerOff" :
3300                         streq(args[0], "reboot")        ? "Reboot" :
3301                         streq(args[0], "kexec")         ? "KExec" :
3302                         streq(args[0], "exit")          ? "Exit" :
3303                                     /* "daemon-reload" */ "Reload";
3304         }
3305
3306         if (!(m = dbus_message_new_method_call(
3307                               "org.freedesktop.systemd1",
3308                               "/org/freedesktop/systemd1",
3309                               "org.freedesktop.systemd1.Manager",
3310                               method))) {
3311                 log_error("Could not allocate message.");
3312                 return -ENOMEM;
3313         }
3314
3315         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3316
3317                 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3318                         /* There's always a fallback possible for
3319                          * legacy actions. */
3320                         r = -EADDRNOTAVAIL;
3321                         goto finish;
3322                 }
3323
3324                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3325                 r = -EIO;
3326                 goto finish;
3327         }
3328
3329         r = 0;
3330
3331 finish:
3332         if (m)
3333                 dbus_message_unref(m);
3334
3335         if (reply)
3336                 dbus_message_unref(reply);
3337
3338         dbus_error_free(&error);
3339
3340         return r;
3341 }
3342
3343 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3344         DBusMessage *m = NULL, *reply = NULL;
3345         unsigned i;
3346         int r;
3347         DBusError error;
3348
3349         assert(bus);
3350         dbus_error_init(&error);
3351
3352         if (n <= 1)
3353                 return daemon_reload(bus, args, n);
3354
3355         for (i = 1; i < n; i++) {
3356
3357                 if (!(m = dbus_message_new_method_call(
3358                                       "org.freedesktop.systemd1",
3359                                       "/org/freedesktop/systemd1",
3360                                       "org.freedesktop.systemd1.Manager",
3361                                       "ResetFailedUnit"))) {
3362                         log_error("Could not allocate message.");
3363                         r = -ENOMEM;
3364                         goto finish;
3365                 }
3366
3367                 if (!dbus_message_append_args(m,
3368                                               DBUS_TYPE_STRING, args + i,
3369                                               DBUS_TYPE_INVALID)) {
3370                         log_error("Could not append arguments to message.");
3371                         r = -ENOMEM;
3372                         goto finish;
3373                 }
3374
3375                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3376                         log_error("Failed to issue method call: %s", bus_error_message(&error));
3377                         r = -EIO;
3378                         goto finish;
3379                 }
3380
3381                 dbus_message_unref(m);
3382                 dbus_message_unref(reply);
3383                 m = reply = NULL;
3384         }
3385
3386         r = 0;
3387
3388 finish:
3389         if (m)
3390                 dbus_message_unref(m);
3391
3392         if (reply)
3393                 dbus_message_unref(reply);
3394
3395         dbus_error_free(&error);
3396
3397         return r;
3398 }
3399
3400 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3401         DBusMessage *m = NULL, *reply = NULL;
3402         DBusError error;
3403         DBusMessageIter iter, sub, sub2;
3404         int r;
3405         const char
3406                 *interface = "org.freedesktop.systemd1.Manager",
3407                 *property = "Environment";
3408
3409         dbus_error_init(&error);
3410
3411         pager_open();
3412
3413         if (!(m = dbus_message_new_method_call(
3414                               "org.freedesktop.systemd1",
3415                               "/org/freedesktop/systemd1",
3416                               "org.freedesktop.DBus.Properties",
3417                               "Get"))) {
3418                 log_error("Could not allocate message.");
3419                 return -ENOMEM;
3420         }
3421
3422         if (!dbus_message_append_args(m,
3423                                       DBUS_TYPE_STRING, &interface,
3424                                       DBUS_TYPE_STRING, &property,
3425                                       DBUS_TYPE_INVALID)) {
3426                 log_error("Could not append arguments to message.");
3427                 r = -ENOMEM;
3428                 goto finish;
3429         }
3430
3431         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3432                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3433                 r = -EIO;
3434                 goto finish;
3435         }
3436
3437         if (!dbus_message_iter_init(reply, &iter) ||
3438             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
3439                 log_error("Failed to parse reply.");
3440                 r = -EIO;
3441                 goto finish;
3442         }
3443
3444         dbus_message_iter_recurse(&iter, &sub);
3445
3446         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3447             dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING)  {
3448                 log_error("Failed to parse reply.");
3449                 r = -EIO;
3450                 goto finish;
3451         }
3452
3453         dbus_message_iter_recurse(&sub, &sub2);
3454
3455         while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3456                 const char *text;
3457
3458                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3459                         log_error("Failed to parse reply.");
3460                         r = -EIO;
3461                         goto finish;
3462                 }
3463
3464                 dbus_message_iter_get_basic(&sub2, &text);
3465                 printf("%s\n", text);
3466
3467                 dbus_message_iter_next(&sub2);
3468         }
3469
3470         r = 0;
3471
3472 finish:
3473         if (m)
3474                 dbus_message_unref(m);
3475
3476         if (reply)
3477                 dbus_message_unref(reply);
3478
3479         dbus_error_free(&error);
3480
3481         return r;
3482 }
3483
3484 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3485         DBusMessage *m = NULL, *reply = NULL;
3486         DBusError error;
3487         int r;
3488         const char *method;
3489         DBusMessageIter iter, sub;
3490         unsigned i;
3491
3492         dbus_error_init(&error);
3493
3494         method = streq(args[0], "set-environment")
3495                 ? "SetEnvironment"
3496                 : "UnsetEnvironment";
3497
3498         if (!(m = dbus_message_new_method_call(
3499                               "org.freedesktop.systemd1",
3500                               "/org/freedesktop/systemd1",
3501                               "org.freedesktop.systemd1.Manager",
3502                               method))) {
3503
3504                 log_error("Could not allocate message.");
3505                 return -ENOMEM;
3506         }
3507
3508         dbus_message_iter_init_append(m, &iter);
3509
3510         if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3511                 log_error("Could not append arguments to message.");
3512                 r = -ENOMEM;
3513                 goto finish;
3514         }
3515
3516         for (i = 1; i < n; i++)
3517                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3518                         log_error("Could not append arguments to message.");
3519                         r = -ENOMEM;
3520                         goto finish;
3521                 }
3522
3523         if (!dbus_message_iter_close_container(&iter, &sub)) {
3524                 log_error("Could not append arguments to message.");
3525                 r = -ENOMEM;
3526                 goto finish;
3527         }
3528
3529         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3530                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3531                 r = -EIO;
3532                 goto finish;
3533         }
3534
3535         r = 0;
3536
3537 finish:
3538         if (m)
3539                 dbus_message_unref(m);
3540
3541         if (reply)
3542                 dbus_message_unref(reply);
3543
3544         dbus_error_free(&error);
3545
3546         return r;
3547 }
3548
3549 typedef struct {
3550         char *name;
3551         char *path;
3552
3553         char **aliases;
3554         char **wanted_by;
3555 } InstallInfo;
3556
3557 static Hashmap *will_install = NULL, *have_installed = NULL;
3558 static Set *remove_symlinks_to = NULL;
3559 static unsigned n_symlinks = 0;
3560
3561 static void install_info_free(InstallInfo *i) {
3562         assert(i);
3563
3564         free(i->name);
3565         free(i->path);
3566         strv_free(i->aliases);
3567         strv_free(i->wanted_by);
3568         free(i);
3569 }
3570
3571 static void install_info_hashmap_free(Hashmap *m) {
3572         InstallInfo *i;
3573
3574         while ((i = hashmap_steal_first(m)))
3575                 install_info_free(i);
3576
3577         hashmap_free(m);
3578 }
3579
3580 static int install_info_add(const char *name) {
3581         InstallInfo *i;
3582         int r;
3583
3584         assert(will_install);
3585
3586         if (!unit_name_is_valid_no_type(name, true)) {
3587                 log_warning("Unit name %s is not a valid unit name.", name);
3588                 return -EINVAL;
3589         }
3590
3591         if (hashmap_get(have_installed, name) ||
3592             hashmap_get(will_install, name))
3593                 return 0;
3594
3595         if (!(i = new0(InstallInfo, 1))) {
3596                 r = -ENOMEM;
3597                 goto fail;
3598         }
3599
3600         if (!(i->name = strdup(name))) {
3601                 r = -ENOMEM;
3602                 goto fail;
3603         }
3604
3605         if ((r = hashmap_put(will_install, i->name, i)) < 0)
3606                 goto fail;
3607
3608         return 0;
3609
3610 fail:
3611         if (i)
3612                 install_info_free(i);
3613
3614         return r;
3615 }
3616
3617 static int config_parse_also(
3618                 const char *filename,
3619                 unsigned line,
3620                 const char *section,
3621                 const char *lvalue,
3622                 int ltype,
3623                 const char *rvalue,
3624                 void *data,
3625                 void *userdata) {
3626
3627         char *w;
3628         size_t l;
3629         char *state;
3630
3631         assert(filename);
3632         assert(lvalue);
3633         assert(rvalue);
3634
3635         FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3636                 char *n;
3637                 int r;
3638
3639                 if (!(n = strndup(w, l)))
3640                         return -ENOMEM;
3641
3642                 if ((r = install_info_add(n)) < 0) {
3643                         log_warning("Cannot install unit %s: %s", n, strerror(-r));
3644                         free(n);
3645                         return r;
3646                 }
3647
3648                 free(n);
3649         }
3650
3651         return 0;
3652 }
3653
3654 static int mark_symlink_for_removal(const char *p) {
3655         char *n;
3656         int r;
3657
3658         assert(p);
3659         assert(path_is_absolute(p));
3660
3661         if (!remove_symlinks_to)
3662                 return 0;
3663
3664         if (!(n = strdup(p)))
3665                 return -ENOMEM;
3666
3667         path_kill_slashes(n);
3668
3669         if ((r = set_put(remove_symlinks_to, n)) < 0) {
3670                 free(n);
3671                 return r == -EEXIST ? 0 : r;
3672         }
3673
3674         return 0;
3675 }
3676
3677 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3678         int r = 0;
3679         DIR *d;
3680         struct dirent *de;
3681
3682         assert(fd >= 0);
3683         assert(root);
3684         assert(deleted);
3685
3686         if (!(d = fdopendir(fd))) {
3687                 close_nointr_nofail(fd);
3688                 return -errno;
3689         }
3690
3691         rewinddir(d);
3692
3693         while ((de = readdir(d))) {
3694                 bool is_dir = false, is_link = false;
3695
3696                 if (ignore_file(de->d_name))
3697                         continue;
3698
3699                 if (de->d_type == DT_LNK)
3700                         is_link = true;
3701                 else if (de->d_type == DT_DIR)
3702                         is_dir = true;
3703                 else if (de->d_type == DT_UNKNOWN) {
3704                         struct stat st;
3705
3706                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3707                                 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3708
3709                                 if (r == 0)
3710                                         r = -errno;
3711                                 continue;
3712                         }
3713
3714                         is_link = S_ISLNK(st.st_mode);
3715                         is_dir = S_ISDIR(st.st_mode);
3716                 } else
3717                         continue;
3718
3719                 if (is_dir) {
3720                         int nfd, q;
3721                         char *p;
3722
3723                         if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3724                                 log_error("Failed to open %s/%s: %m", root, de->d_name);
3725
3726                                 if (r == 0)
3727                                         r = -errno;
3728                                 continue;
3729                         }
3730
3731                         if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3732                                 log_error("Failed to allocate directory string.");
3733                                 close_nointr_nofail(nfd);
3734                                 r = -ENOMEM;
3735                                 break;
3736                         }
3737
3738                         /* This will close nfd, regardless whether it succeeds or not */
3739                         q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3740                         free(p);
3741
3742                         if (r == 0)
3743                                 r = q;
3744
3745                 } else if (is_link) {
3746                         char *p, *dest, *c;
3747                         int q;
3748
3749                         if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3750                                 log_error("Failed to allocate symlink string.");
3751                                 r = -ENOMEM;
3752                                 break;
3753                         }
3754
3755                         if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3756                                 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3757                                 free(p);
3758
3759                                 if (r == 0)
3760                                         r = q;
3761                                 continue;
3762                         }
3763
3764                         if ((c = canonicalize_file_name(dest))) {
3765                                 /* This might fail if the destination
3766                                  * is already removed */
3767
3768                                 free(dest);
3769                                 dest = c;
3770                         }
3771
3772                         path_kill_slashes(dest);
3773                         if (set_get(remove_symlinks_to, dest)) {
3774
3775                                 if (!arg_quiet)
3776                                         log_info("rm '%s'", p);
3777
3778                                 if (unlink(p) < 0) {
3779                                         log_error("Cannot unlink symlink %s: %m", p);
3780
3781                                         if (r == 0)
3782                                                 r = -errno;
3783                                 } else {
3784                                         rmdir_parents(p, config_path);
3785                                         path_kill_slashes(p);
3786
3787                                         if (!set_get(remove_symlinks_to, p)) {
3788
3789                                                 if ((r = mark_symlink_for_removal(p)) < 0) {
3790                                                         if (r == 0)
3791                                                                 r = q;
3792                                                 } else
3793                                                         *deleted = true;
3794                                         }
3795                                 }
3796                         }
3797
3798                         free(p);
3799                         free(dest);
3800                 }
3801         }
3802
3803         closedir(d);
3804
3805         return r;
3806 }
3807
3808 static int remove_marked_symlinks(const char *config_path) {
3809         int fd, r = 0;
3810         bool deleted;
3811
3812         assert(config_path);
3813
3814         if (set_size(remove_symlinks_to) <= 0)
3815                 return 0;
3816
3817         if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3818                 return -errno;
3819
3820         do {
3821                 int q, cfd;
3822                 deleted = false;
3823
3824                 if ((cfd = dup(fd)) < 0) {
3825                         r = -errno;
3826                         break;
3827                 }
3828
3829                 /* This takes possession of cfd and closes it */
3830                 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3831                         if (r == 0)
3832                                 r = q;
3833                 }
3834         } while (deleted);
3835
3836         close_nointr_nofail(fd);
3837
3838         return r;
3839 }
3840
3841 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3842         int r;
3843
3844         assert(old_path);
3845         assert(new_path);
3846         assert(verb);
3847
3848         if (streq(verb, "enable")) {
3849                 char *dest;
3850
3851                 mkdir_parents(new_path, 0755);
3852
3853                 if (symlink(old_path, new_path) >= 0) {
3854
3855                         if (!arg_quiet)
3856                                 log_info("ln -s '%s' '%s'", old_path, new_path);
3857
3858                         return 0;
3859                 }
3860
3861                 if (errno != EEXIST) {
3862                         log_error("Cannot link %s to %s: %m", old_path, new_path);
3863                         return -errno;
3864                 }
3865
3866                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3867
3868                         if (errno == EINVAL) {
3869                                 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3870                                 return -EEXIST;
3871                         }
3872
3873                         log_error("readlink() failed: %s", strerror(-r));
3874                         return r;
3875                 }
3876
3877                 if (streq(dest, old_path)) {
3878                         free(dest);
3879                         return 0;
3880                 }
3881
3882                 if (!arg_force) {
3883                         log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3884                         free(dest);
3885                         return -EEXIST;
3886                 }
3887
3888                 free(dest);
3889                 unlink(new_path);
3890
3891                 if (!arg_quiet)
3892                         log_info("ln -s '%s' '%s'", old_path, new_path);
3893
3894                 if (symlink(old_path, new_path) >= 0)
3895                         return 0;
3896
3897                 log_error("Cannot link %s to %s: %m", old_path, new_path);
3898                 return -errno;
3899
3900         } else if (streq(verb, "disable")) {
3901                 char *dest;
3902
3903                 if ((r = mark_symlink_for_removal(old_path)) < 0)
3904                         return r;
3905
3906                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3907                         if (errno == ENOENT)
3908                                 return 0;
3909
3910                         if (errno == EINVAL) {
3911                                 log_warning("File %s not a symlink, ignoring.", old_path);
3912                                 return 0;
3913                         }
3914
3915                         log_error("readlink() failed: %s", strerror(-r));
3916                         return r;
3917                 }
3918
3919                 if (!streq(dest, old_path)) {
3920                         log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3921                         free(dest);
3922                         return 0;
3923                 }
3924
3925                 free(dest);
3926
3927                 if ((r = mark_symlink_for_removal(new_path)) < 0)
3928                         return r;
3929
3930                 if (!arg_quiet)
3931                         log_info("rm '%s'", new_path);
3932
3933                 if (unlink(new_path) >= 0)
3934                         return 0;
3935
3936                 log_error("Cannot unlink %s: %m", new_path);
3937                 return -errno;
3938
3939         } else if (streq(verb, "is-enabled")) {
3940                 char *dest;
3941
3942                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3943
3944                         if (errno == ENOENT || errno == EINVAL)
3945                                 return 0;
3946
3947                         log_error("readlink() failed: %s", strerror(-r));
3948                         return r;
3949                 }
3950
3951                 if (streq(dest, old_path)) {
3952                         free(dest);
3953                         return 1;
3954                 }
3955
3956                 return 0;
3957         }
3958
3959         assert_not_reached("Unknown action.");
3960 }
3961
3962 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3963         char **s;
3964         char *alias_path = NULL;
3965         int r;
3966
3967         assert(verb);
3968         assert(i);
3969         assert(config_path);
3970
3971         STRV_FOREACH(s, i->aliases) {
3972
3973                 free(alias_path);
3974                 if (!(alias_path = path_make_absolute(*s, config_path))) {
3975                         log_error("Out of memory");
3976                         r = -ENOMEM;
3977                         goto finish;
3978                 }
3979
3980                 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3981                         goto finish;
3982
3983                 if (streq(verb, "disable"))
3984                         rmdir_parents(alias_path, config_path);
3985         }
3986         r = 0;
3987
3988 finish:
3989         free(alias_path);
3990
3991         return r;
3992 }
3993
3994 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3995         char **s;
3996         char *alias_path = NULL;
3997         int r;
3998
3999         assert(verb);
4000         assert(i);
4001         assert(config_path);
4002
4003         STRV_FOREACH(s, i->wanted_by) {
4004                 if (!unit_name_is_valid_no_type(*s, true)) {
4005                         log_error("Invalid name %s.", *s);
4006                         r = -EINVAL;
4007                         goto finish;
4008                 }
4009
4010                 free(alias_path);
4011                 alias_path = NULL;
4012
4013                 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
4014                         log_error("Out of memory");
4015                         r = -ENOMEM;
4016                         goto finish;
4017                 }
4018
4019                 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
4020                         goto finish;
4021
4022                 if (streq(verb, "disable"))
4023                         rmdir_parents(alias_path, config_path);
4024         }
4025
4026         r = 0;
4027
4028 finish:
4029         free(alias_path);
4030
4031         return r;
4032 }
4033
4034 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
4035
4036         const ConfigItem items[] = {
4037                 { "Alias",    config_parse_strv, 0, &i->aliases,   "Install" },
4038                 { "WantedBy", config_parse_strv, 0, &i->wanted_by, "Install" },
4039                 { "Also",     config_parse_also, 0, NULL,          "Install" },
4040
4041                 { NULL, NULL, 0, NULL, NULL }
4042         };
4043
4044         char **p;
4045         char *filename = NULL;
4046         FILE *f = NULL;
4047         int r;
4048
4049         assert(paths);
4050         assert(i);
4051
4052         STRV_FOREACH(p, paths->unit_path) {
4053                 int fd;
4054
4055                 if (!(filename = path_make_absolute(i->name, *p))) {
4056                         log_error("Out of memory");
4057                         return -ENOMEM;
4058                 }
4059
4060                 /* Ensure that we don't follow symlinks */
4061                 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
4062                         if ((f = fdopen(fd, "re")))
4063                                 break;
4064
4065                 if (errno == ELOOP) {
4066                         log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
4067                         free(filename);
4068                         return -errno;
4069                 }
4070
4071                 if (errno != ENOENT) {
4072                         log_error("Failed to open %s: %m", filename);
4073                         free(filename);
4074                         return -errno;
4075                 }
4076
4077                 free(filename);
4078                 filename = NULL;
4079         }
4080
4081         if (!f) {
4082 #if (defined(TARGET_FEDORA) || defined(TARGET_MANDRIVA)) && defined (HAVE_SYSV_COMPAT)
4083
4084                 if (endswith(i->name, ".service")) {
4085                         char *sysv;
4086                         bool exists;
4087
4088                         if (asprintf(&sysv, SYSTEM_SYSVINIT_PATH "/%s", i->name) < 0) {
4089                                 log_error("Out of memory");
4090                                 return -ENOMEM;
4091                         }
4092
4093                         sysv[strlen(sysv) - sizeof(".service") + 1] = 0;
4094                         exists = access(sysv, F_OK) >= 0;
4095
4096                         if (exists) {
4097                                 pid_t pid;
4098                                 siginfo_t status;
4099
4100                                 const char *argv[] = {
4101                                         "/sbin/chkconfig",
4102                                         NULL,
4103                                         NULL,
4104                                         NULL
4105                                 };
4106
4107                                 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", i->name);
4108
4109                                 argv[1] = file_name_from_path(sysv);
4110                                 argv[2] =
4111                                         streq(verb, "enable") ? "on" :
4112                                         streq(verb, "disable") ? "off" : "--level=5";
4113
4114                                 log_info("Executing %s %s %s", argv[0], argv[1], strempty(argv[2]));
4115
4116                                 if ((pid = fork()) < 0) {
4117                                         log_error("Failed to fork: %m");
4118                                         free(sysv);
4119                                         return -errno;
4120                                 } else if (pid == 0) {
4121                                         execv(argv[0], (char**) argv);
4122                                         _exit(EXIT_FAILURE);
4123                                 }
4124
4125                                 free(sysv);
4126
4127                                 if ((r = wait_for_terminate(pid, &status)) < 0)
4128                                         return r;
4129
4130                                 if (status.si_code == CLD_EXITED) {
4131
4132                                         if (streq(verb, "is-enabled"))
4133                                                 return status.si_status == 0 ? 1 : 0;
4134
4135                                         if (status.si_status == 0)
4136                                                 n_symlinks ++;
4137
4138                                         return status.si_status == 0 ? 0 : -EINVAL;
4139
4140                                 } else
4141                                         return -EPROTO;
4142                         }
4143
4144                         free(sysv);
4145                 }
4146
4147 #endif
4148
4149                 log_error("Couldn't find %s.", i->name);
4150                 return -ENOENT;
4151         }
4152
4153         i->path = filename;
4154
4155         if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
4156                 fclose(f);
4157                 return r;
4158         }
4159
4160         n_symlinks += strv_length(i->aliases);
4161         n_symlinks += strv_length(i->wanted_by);
4162
4163         fclose(f);
4164
4165         if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
4166                 return r;
4167
4168         if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
4169                 return r;
4170
4171         if ((r = mark_symlink_for_removal(filename)) < 0)
4172                 return r;
4173
4174         if ((r = remove_marked_symlinks(config_path)) < 0)
4175                 return r;
4176
4177         return 0;
4178 }
4179
4180 static char *get_config_path(void) {
4181
4182         if (arg_user && arg_global)
4183                 return strdup(USER_CONFIG_UNIT_PATH);
4184
4185         if (arg_user) {
4186                 char *p;
4187
4188                 if (user_config_home(&p) < 0)
4189                         return NULL;
4190
4191                 return p;
4192         }
4193
4194         return strdup(SYSTEM_CONFIG_UNIT_PATH);
4195 }
4196
4197 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
4198         DBusError error;
4199         int r;
4200         LookupPaths paths;
4201         char *config_path = NULL;
4202         unsigned j;
4203         InstallInfo *i;
4204         const char *verb = args[0];
4205
4206         dbus_error_init(&error);
4207
4208         zero(paths);
4209         if ((r = lookup_paths_init(&paths, arg_user ? MANAGER_USER : MANAGER_SYSTEM)) < 0) {
4210                 log_error("Failed to determine lookup paths: %s", strerror(-r));
4211                 goto finish;
4212         }
4213
4214         if (!(config_path = get_config_path())) {
4215                 log_error("Failed to determine config path");
4216                 r = -ENOMEM;
4217                 goto finish;
4218         }
4219
4220         will_install = hashmap_new(string_hash_func, string_compare_func);
4221         have_installed = hashmap_new(string_hash_func, string_compare_func);
4222
4223         if (!will_install || !have_installed) {
4224                 log_error("Failed to allocate unit sets.");
4225                 r = -ENOMEM;
4226                 goto finish;
4227         }
4228
4229         if (!arg_defaults && streq(verb, "disable"))
4230                 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
4231                         log_error("Failed to allocate symlink sets.");
4232                         r = -ENOMEM;
4233                         goto finish;
4234                 }
4235
4236         for (j = 1; j < n; j++)
4237                 if ((r = install_info_add(args[j])) < 0) {
4238                         log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
4239                         goto finish;
4240                 }
4241
4242         r = 0;
4243
4244         while ((i = hashmap_first(will_install))) {
4245                 int q;
4246
4247                 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
4248
4249                 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
4250
4251                         if (q < 0) {
4252                                 if (r == 0)
4253                                         r = q;
4254                                 goto finish;
4255                         }
4256
4257                         /* In test mode and found something */
4258                         r = 1;
4259                         break;
4260                 }
4261         }
4262
4263         if (streq(verb, "is-enabled"))
4264                 r = r > 0 ? 0 : -ENOENT;
4265         else {
4266                 if (n_symlinks <= 0)
4267                         log_warning("Unit files contain no applicable installation information. Ignoring.");
4268
4269                 if (bus &&
4270                     /* Don't try to reload anything if the user asked us to not do this */
4271                     !arg_no_reload &&
4272                     /* Don't try to reload anything when updating a unit globally */
4273                     !arg_global &&
4274                     /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
4275                     (arg_user || sd_booted() > 0) &&
4276                     /* Don't try to reload anything if we are running in a chroot environment */
4277                     (arg_user || running_in_chroot() <= 0) ) {
4278                         int q;
4279
4280                         if ((q = daemon_reload(bus, args, n)) < 0)
4281                                 r = q;
4282                 }
4283         }
4284
4285 finish:
4286         install_info_hashmap_free(will_install);
4287         install_info_hashmap_free(have_installed);
4288
4289         set_free_free(remove_symlinks_to);
4290
4291         lookup_paths_free(&paths);
4292
4293         free(config_path);
4294
4295         return r;
4296 }
4297
4298 static int systemctl_help(void) {
4299
4300         printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4301                "Send control commands to or query the systemd manager.\n\n"
4302                "  -h --help           Show this help\n"
4303                "     --version        Show package version\n"
4304                "  -t --type=TYPE      List only units of a particular type\n"
4305                "  -p --property=NAME  Show only properties by this name\n"
4306                "  -a --all            Show all units/properties, including dead/empty ones\n"
4307                "     --failed         Show only failed units\n"
4308                "     --full           Don't ellipsize unit names on output\n"
4309                "     --fail           When queueing a new job, fail if conflicting jobs are\n"
4310                "                      pending\n"
4311                "     --ignore-dependencies\n"
4312                "                      When queueing a new job, ignore all its dependencies\n"
4313                "     --kill-mode=MODE How to send signal\n"
4314                "     --kill-who=WHO   Who to send signal to\n"
4315                "  -s --signal=SIGNAL  Which signal to send\n"
4316                "  -H --host=[user@]host\n"
4317                "                      Show information for remote host\n"
4318                "  -P --privileged     Acquire privileges before execution\n"
4319                "  -q --quiet          Suppress output\n"
4320                "     --no-block       Do not wait until operation finished\n"
4321                "     --no-wall        Don't send wall message before halt/power-off/reboot\n"
4322                "     --no-reload      When enabling/disabling unit files, don't reload daemon\n"
4323                "                      configuration\n"
4324                "     --no-pager       Do not pipe output into a pager.\n"
4325                "     --no-ask-password\n"
4326                "                      Do not ask for system passwords\n"
4327                "     --order          When generating graph for dot, show only order\n"
4328                "     --require        When generating graph for dot, show only requirement\n"
4329                "     --system         Connect to system manager\n"
4330                "     --user           Connect to user service manager\n"
4331                "     --global         Enable/disable unit files globally\n"
4332                "  -f --force          When enabling unit files, override existing symlinks\n"
4333                "                      When shutting down, execute action immediately\n"
4334                "     --defaults       When disabling unit files, remove default symlinks only\n\n"
4335                "Commands:\n"
4336                "  list-units                      List units\n"
4337                "  start [NAME...]                 Start (activate) one or more units\n"
4338                "  stop [NAME...]                  Stop (deactivate) one or more units\n"
4339                "  reload [NAME...]                Reload one or more units\n"
4340                "  restart [NAME...]               Start or restart one or more units\n"
4341                "  try-restart [NAME...]           Restart one or more units if active\n"
4342                "  reload-or-restart [NAME...]     Reload one or more units is possible,\n"
4343                "                                  otherwise start or restart\n"
4344                "  reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4345                "                                  otherwise restart if active\n"
4346                "  isolate [NAME]                  Start one unit and stop all others\n"
4347                "  kill [NAME...]                  Send signal to processes of a unit\n"
4348                "  is-active [NAME...]             Check whether units are active\n"
4349                "  status [NAME...|PID...]         Show runtime status of one or more units\n"
4350                "  show [NAME...|JOB...]           Show properties of one or more\n"
4351                "                                  units/jobs or the manager\n"
4352                "  reset-failed [NAME...]          Reset failed state for all, one, or more\n"
4353                "                                  units\n"
4354                "  enable [NAME...]                Enable one or more unit files\n"
4355                "  disable [NAME...]               Disable one or more unit files\n"
4356                "  is-enabled [NAME...]            Check whether unit files are enabled\n"
4357                "  load [NAME...]                  Load one or more units\n"
4358                "  list-jobs                       List jobs\n"
4359                "  cancel [JOB...]                 Cancel all, one, or more jobs\n"
4360                "  monitor                         Monitor unit/job changes\n"
4361                "  dump                            Dump server status\n"
4362                "  dot                             Dump dependency graph for dot(1)\n"
4363                "  snapshot [NAME]                 Create a snapshot\n"
4364                "  delete [NAME...]                Remove one or more snapshots\n"
4365                "  daemon-reload                   Reload systemd manager configuration\n"
4366                "  daemon-reexec                   Reexecute systemd manager\n"
4367                "  show-environment                Dump environment\n"
4368                "  set-environment [NAME=VALUE...] Set one or more environment variables\n"
4369                "  unset-environment [NAME...]     Unset one or more environment variables\n"
4370                "  default                         Enter system default mode\n"
4371                "  rescue                          Enter system rescue mode\n"
4372                "  emergency                       Enter system emergency mode\n"
4373                "  halt                            Shut down and halt the system\n"
4374                "  poweroff                        Shut down and power-off the system\n"
4375                "  reboot                          Shut down and reboot the system\n"
4376                "  kexec                           Shut down and reboot the system with kexec\n"
4377                "  exit                            Ask for user instance termination\n",
4378                program_invocation_short_name);
4379
4380         return 0;
4381 }
4382
4383 static int halt_help(void) {
4384
4385         printf("%s [OPTIONS...]\n\n"
4386                "%s the system.\n\n"
4387                "     --help      Show this help\n"
4388                "     --halt      Halt the machine\n"
4389                "  -p --poweroff  Switch off the machine\n"
4390                "     --reboot    Reboot the machine\n"
4391                "  -f --force     Force immediate halt/power-off/reboot\n"
4392                "  -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4393                "  -d --no-wtmp   Don't write wtmp record\n"
4394                "  -n --no-sync   Don't sync before halt/power-off/reboot\n"
4395                "     --no-wall   Don't send wall message before halt/power-off/reboot\n",
4396                program_invocation_short_name,
4397                arg_action == ACTION_REBOOT   ? "Reboot" :
4398                arg_action == ACTION_POWEROFF ? "Power off" :
4399                                                "Halt");
4400
4401         return 0;
4402 }
4403
4404 static int shutdown_help(void) {
4405
4406         printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4407                "Shut down the system.\n\n"
4408                "     --help      Show this help\n"
4409                "  -H --halt      Halt the machine\n"
4410                "  -P --poweroff  Power-off the machine\n"
4411                "  -r --reboot    Reboot the machine\n"
4412                "  -h             Equivalent to --poweroff, overriden by --halt\n"
4413                "  -k             Don't halt/power-off/reboot, just send warnings\n"
4414                "     --no-wall   Don't send wall message before halt/power-off/reboot\n"
4415                "  -c             Cancel a pending shutdown\n",
4416                program_invocation_short_name);
4417
4418         return 0;
4419 }
4420
4421 static int telinit_help(void) {
4422
4423         printf("%s [OPTIONS...] {COMMAND}\n\n"
4424                "Send control commands to the init daemon.\n\n"
4425                "     --help      Show this help\n"
4426                "     --no-wall   Don't send wall message before halt/power-off/reboot\n\n"
4427                "Commands:\n"
4428                "  0              Power-off the machine\n"
4429                "  6              Reboot the machine\n"
4430                "  2, 3, 4, 5     Start runlevelX.target unit\n"
4431                "  1, s, S        Enter rescue mode\n"
4432                "  q, Q           Reload init daemon configuration\n"
4433                "  u, U           Reexecute init daemon\n",
4434                program_invocation_short_name);
4435
4436         return 0;
4437 }
4438
4439 static int runlevel_help(void) {
4440
4441         printf("%s [OPTIONS...]\n\n"
4442                "Prints the previous and current runlevel of the init system.\n\n"
4443                "     --help      Show this help\n",
4444                program_invocation_short_name);
4445
4446         return 0;
4447 }
4448
4449 static int systemctl_parse_argv(int argc, char *argv[]) {
4450
4451         enum {
4452                 ARG_FAIL = 0x100,
4453                 ARG_IGNORE_DEPENDENCIES,
4454                 ARG_VERSION,
4455                 ARG_USER,
4456                 ARG_SYSTEM,
4457                 ARG_GLOBAL,
4458                 ARG_NO_BLOCK,
4459                 ARG_NO_PAGER,
4460                 ARG_NO_WALL,
4461                 ARG_ORDER,
4462                 ARG_REQUIRE,
4463                 ARG_FULL,
4464                 ARG_NO_RELOAD,
4465                 ARG_DEFAULTS,
4466                 ARG_KILL_MODE,
4467                 ARG_KILL_WHO,
4468                 ARG_NO_ASK_PASSWORD,
4469                 ARG_FAILED
4470         };
4471
4472         static const struct option options[] = {
4473                 { "help",      no_argument,       NULL, 'h'           },
4474                 { "version",   no_argument,       NULL, ARG_VERSION   },
4475                 { "type",      required_argument, NULL, 't'           },
4476                 { "property",  required_argument, NULL, 'p'           },
4477                 { "all",       no_argument,       NULL, 'a'           },
4478                 { "failed",    no_argument,       NULL, ARG_FAILED    },
4479                 { "full",      no_argument,       NULL, ARG_FULL      },
4480                 { "fail",      no_argument,       NULL, ARG_FAIL      },
4481                 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4482                 { "user",      no_argument,       NULL, ARG_USER      },
4483                 { "system",    no_argument,       NULL, ARG_SYSTEM    },
4484                 { "global",    no_argument,       NULL, ARG_GLOBAL    },
4485                 { "no-block",  no_argument,       NULL, ARG_NO_BLOCK  },
4486                 { "no-pager",  no_argument,       NULL, ARG_NO_PAGER  },
4487                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL   },
4488                 { "quiet",     no_argument,       NULL, 'q'           },
4489                 { "order",     no_argument,       NULL, ARG_ORDER     },
4490                 { "require",   no_argument,       NULL, ARG_REQUIRE   },
4491                 { "force",     no_argument,       NULL, 'f'           },
4492                 { "no-reload", no_argument,       NULL, ARG_NO_RELOAD },
4493                 { "defaults",  no_argument,       NULL, ARG_DEFAULTS  },
4494                 { "kill-mode", required_argument, NULL, ARG_KILL_MODE },
4495                 { "kill-who",  required_argument, NULL, ARG_KILL_WHO  },
4496                 { "signal",    required_argument, NULL, 's'           },
4497                 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4498                 { "host",      required_argument, NULL, 'H'           },
4499                 { "privileged",no_argument,       NULL, 'P'           },
4500                 { NULL,        0,                 NULL, 0             }
4501         };
4502
4503         int c;
4504
4505         assert(argc >= 0);
4506         assert(argv);
4507
4508         /* Only when running as systemctl we ask for passwords */
4509         arg_ask_password = true;
4510
4511         while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:P", options, NULL)) >= 0) {
4512
4513                 switch (c) {
4514
4515                 case 'h':
4516                         systemctl_help();
4517                         return 0;
4518
4519                 case ARG_VERSION:
4520                         puts(PACKAGE_STRING);
4521                         puts(DISTRIBUTION);
4522                         puts(SYSTEMD_FEATURES);
4523                         return 0;
4524
4525                 case 't':
4526                         arg_type = optarg;
4527                         break;
4528
4529                 case 'p': {
4530                         char **l;
4531
4532                         if (!(l = strv_append(arg_property, optarg)))
4533                                 return -ENOMEM;
4534
4535                         strv_free(arg_property);
4536                         arg_property = l;
4537
4538                         /* If the user asked for a particular
4539                          * property, show it to him, even if it is
4540                          * empty. */
4541                         arg_all = true;
4542                         break;
4543                 }
4544
4545                 case 'a':
4546                         arg_all = true;
4547                         break;
4548
4549                 case ARG_FAIL:
4550                         arg_job_mode = "fail";
4551                         break;
4552
4553                 case ARG_IGNORE_DEPENDENCIES:
4554                         arg_job_mode = "ignore-dependencies";
4555                         break;
4556
4557                 case ARG_USER:
4558                         arg_user = true;
4559                         break;
4560
4561                 case ARG_SYSTEM:
4562                         arg_user = false;
4563                         break;
4564
4565                 case ARG_NO_BLOCK:
4566                         arg_no_block = true;
4567                         break;
4568
4569                 case ARG_NO_PAGER:
4570                         arg_no_pager = true;
4571                         break;
4572
4573                 case ARG_NO_WALL:
4574                         arg_no_wall = true;
4575                         break;
4576
4577                 case ARG_ORDER:
4578                         arg_dot = DOT_ORDER;
4579                         break;
4580
4581                 case ARG_REQUIRE:
4582                         arg_dot = DOT_REQUIRE;
4583                         break;
4584
4585                 case ARG_FULL:
4586                         arg_full = true;
4587                         break;
4588
4589                 case ARG_FAILED:
4590                         arg_failed = true;
4591                         break;
4592
4593                 case 'q':
4594                         arg_quiet = true;
4595                         break;
4596
4597                 case 'f':
4598                         arg_force = true;
4599                         break;
4600
4601                 case ARG_NO_RELOAD:
4602                         arg_no_reload = true;
4603                         break;
4604
4605                 case ARG_GLOBAL:
4606                         arg_global = true;
4607                         arg_user = true;
4608                         break;
4609
4610                 case ARG_DEFAULTS:
4611                         arg_defaults = true;
4612                         break;
4613
4614                 case ARG_KILL_WHO:
4615                         arg_kill_who = optarg;
4616                         break;
4617
4618                 case ARG_KILL_MODE:
4619                         arg_kill_mode = optarg;
4620                         break;
4621
4622                 case 's':
4623                         if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4624                                 log_error("Failed to parse signal string %s.", optarg);
4625                                 return -EINVAL;
4626                         }
4627                         break;
4628
4629                 case ARG_NO_ASK_PASSWORD:
4630                         arg_ask_password = false;
4631                         break;
4632
4633                 case 'P':
4634                         arg_transport = TRANSPORT_POLKIT;
4635                         break;
4636
4637                 case 'H':
4638                         arg_transport = TRANSPORT_SSH;
4639                         arg_host = optarg;
4640                         break;
4641
4642                 case '?':
4643                         return -EINVAL;
4644
4645                 default:
4646                         log_error("Unknown option code %c", c);
4647                         return -EINVAL;
4648                 }
4649         }
4650
4651         if (arg_transport != TRANSPORT_NORMAL && arg_user) {
4652                 log_error("Cannot access user instance remotely.");
4653                 return -EINVAL;
4654         }
4655
4656         return 1;
4657 }
4658
4659 static int halt_parse_argv(int argc, char *argv[]) {
4660
4661         enum {
4662                 ARG_HELP = 0x100,
4663                 ARG_HALT,
4664                 ARG_REBOOT,
4665                 ARG_NO_WALL
4666         };
4667
4668         static const struct option options[] = {
4669                 { "help",      no_argument,       NULL, ARG_HELP    },
4670                 { "halt",      no_argument,       NULL, ARG_HALT    },
4671                 { "poweroff",  no_argument,       NULL, 'p'         },
4672                 { "reboot",    no_argument,       NULL, ARG_REBOOT  },
4673                 { "force",     no_argument,       NULL, 'f'         },
4674                 { "wtmp-only", no_argument,       NULL, 'w'         },
4675                 { "no-wtmp",   no_argument,       NULL, 'd'         },
4676                 { "no-sync",   no_argument,       NULL, 'n'         },
4677                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4678                 { NULL,        0,                 NULL, 0           }
4679         };
4680
4681         int c, runlevel;
4682
4683         assert(argc >= 0);
4684         assert(argv);
4685
4686         if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4687                 if (runlevel == '0' || runlevel == '6')
4688                         arg_immediate = true;
4689
4690         while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4691                 switch (c) {
4692
4693                 case ARG_HELP:
4694                         halt_help();
4695                         return 0;
4696
4697                 case ARG_HALT:
4698                         arg_action = ACTION_HALT;
4699                         break;
4700
4701                 case 'p':
4702                         if (arg_action != ACTION_REBOOT)
4703                                 arg_action = ACTION_POWEROFF;
4704                         break;
4705
4706                 case ARG_REBOOT:
4707                         arg_action = ACTION_REBOOT;
4708                         break;
4709
4710                 case 'f':
4711                         arg_immediate = true;
4712                         break;
4713
4714                 case 'w':
4715                         arg_dry = true;
4716                         break;
4717
4718                 case 'd':
4719                         arg_no_wtmp = true;
4720                         break;
4721
4722                 case 'n':
4723                         arg_no_sync = true;
4724                         break;
4725
4726                 case ARG_NO_WALL:
4727                         arg_no_wall = true;
4728                         break;
4729
4730                 case 'i':
4731                 case 'h':
4732                         /* Compatibility nops */
4733                         break;
4734
4735                 case '?':
4736                         return -EINVAL;
4737
4738                 default:
4739                         log_error("Unknown option code %c", c);
4740                         return -EINVAL;
4741                 }
4742         }
4743
4744         if (optind < argc) {
4745                 log_error("Too many arguments.");
4746                 return -EINVAL;
4747         }
4748
4749         return 1;
4750 }
4751
4752 static int parse_time_spec(const char *t, usec_t *_u) {
4753         assert(t);
4754         assert(_u);
4755
4756         if (streq(t, "now"))
4757                 *_u = 0;
4758         else if (t[0] == '+') {
4759                 uint64_t u;
4760
4761                 if (safe_atou64(t + 1, &u) < 0)
4762                         return -EINVAL;
4763
4764                 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4765         } else {
4766                 char *e = NULL;
4767                 long hour, minute;
4768                 struct tm tm;
4769                 time_t s;
4770                 usec_t n;
4771
4772                 errno = 0;
4773                 hour = strtol(t, &e, 10);
4774                 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4775                         return -EINVAL;
4776
4777                 minute = strtol(e+1, &e, 10);
4778                 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4779                         return -EINVAL;
4780
4781                 n = now(CLOCK_REALTIME);
4782                 s = (time_t) (n / USEC_PER_SEC);
4783
4784                 zero(tm);
4785                 assert_se(localtime_r(&s, &tm));
4786
4787                 tm.tm_hour = (int) hour;
4788                 tm.tm_min = (int) minute;
4789                 tm.tm_sec = 0;
4790
4791                 assert_se(s = mktime(&tm));
4792
4793                 *_u = (usec_t) s * USEC_PER_SEC;
4794
4795                 while (*_u <= n)
4796                         *_u += USEC_PER_DAY;
4797         }
4798
4799         return 0;
4800 }
4801
4802 static bool kexec_loaded(void) {
4803        bool loaded = false;
4804        char *s;
4805
4806        if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4807                if (s[0] == '1')
4808                        loaded = true;
4809                free(s);
4810        }
4811        return loaded;
4812 }
4813
4814 static int shutdown_parse_argv(int argc, char *argv[]) {
4815
4816         enum {
4817                 ARG_HELP = 0x100,
4818                 ARG_NO_WALL
4819         };
4820
4821         static const struct option options[] = {
4822                 { "help",      no_argument,       NULL, ARG_HELP    },
4823                 { "halt",      no_argument,       NULL, 'H'         },
4824                 { "poweroff",  no_argument,       NULL, 'P'         },
4825                 { "reboot",    no_argument,       NULL, 'r'         },
4826                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4827                 { NULL,        0,                 NULL, 0           }
4828         };
4829
4830         int c, r;
4831
4832         assert(argc >= 0);
4833         assert(argv);
4834
4835         while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4836                 switch (c) {
4837
4838                 case ARG_HELP:
4839                         shutdown_help();
4840                         return 0;
4841
4842                 case 'H':
4843                         arg_action = ACTION_HALT;
4844                         break;
4845
4846                 case 'P':
4847                         arg_action = ACTION_POWEROFF;
4848                         break;
4849
4850                 case 'r':
4851                         if (kexec_loaded())
4852                                 arg_action = ACTION_KEXEC;
4853                         else
4854                                 arg_action = ACTION_REBOOT;
4855                         break;
4856
4857                 case 'h':
4858                         if (arg_action != ACTION_HALT)
4859                                 arg_action = ACTION_POWEROFF;
4860                         break;
4861
4862                 case 'k':
4863                         arg_dry = true;
4864                         break;
4865
4866                 case ARG_NO_WALL:
4867                         arg_no_wall = true;
4868                         break;
4869
4870                 case 't':
4871                 case 'a':
4872                         /* Compatibility nops */
4873                         break;
4874
4875                 case 'c':
4876                         arg_action = ACTION_CANCEL_SHUTDOWN;
4877                         break;
4878
4879                 case '?':
4880                         return -EINVAL;
4881
4882                 default:
4883                         log_error("Unknown option code %c", c);
4884                         return -EINVAL;
4885                 }
4886         }
4887
4888         if (argc > optind) {
4889                 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4890                         log_error("Failed to parse time specification: %s", argv[optind]);
4891                         return r;
4892                 }
4893         } else
4894                 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4895
4896         /* We skip the time argument */
4897         if (argc > optind + 1)
4898                 arg_wall = argv + optind + 1;
4899
4900         optind = argc;
4901
4902         return 1;
4903 }
4904
4905 static int telinit_parse_argv(int argc, char *argv[]) {
4906
4907         enum {
4908                 ARG_HELP = 0x100,
4909                 ARG_NO_WALL
4910         };
4911
4912         static const struct option options[] = {
4913                 { "help",      no_argument,       NULL, ARG_HELP    },
4914                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4915                 { NULL,        0,                 NULL, 0           }
4916         };
4917
4918         static const struct {
4919                 char from;
4920                 enum action to;
4921         } table[] = {
4922                 { '0', ACTION_POWEROFF },
4923                 { '6', ACTION_REBOOT },
4924                 { '1', ACTION_RESCUE },
4925                 { '2', ACTION_RUNLEVEL2 },
4926                 { '3', ACTION_RUNLEVEL3 },
4927                 { '4', ACTION_RUNLEVEL4 },
4928                 { '5', ACTION_RUNLEVEL5 },
4929                 { 's', ACTION_RESCUE },
4930                 { 'S', ACTION_RESCUE },
4931                 { 'q', ACTION_RELOAD },
4932                 { 'Q', ACTION_RELOAD },
4933                 { 'u', ACTION_REEXEC },
4934                 { 'U', ACTION_REEXEC }
4935         };
4936
4937         unsigned i;
4938         int c;
4939
4940         assert(argc >= 0);
4941         assert(argv);
4942
4943         while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4944                 switch (c) {
4945
4946                 case ARG_HELP:
4947                         telinit_help();
4948                         return 0;
4949
4950                 case ARG_NO_WALL:
4951                         arg_no_wall = true;
4952                         break;
4953
4954                 case '?':
4955                         return -EINVAL;
4956
4957                 default:
4958                         log_error("Unknown option code %c", c);
4959                         return -EINVAL;
4960                 }
4961         }
4962
4963         if (optind >= argc) {
4964                 telinit_help();
4965                 return -EINVAL;
4966         }
4967
4968         if (optind + 1 < argc) {
4969                 log_error("Too many arguments.");
4970                 return -EINVAL;
4971         }
4972
4973         if (strlen(argv[optind]) != 1) {
4974                 log_error("Expected single character argument.");
4975                 return -EINVAL;
4976         }
4977
4978         for (i = 0; i < ELEMENTSOF(table); i++)
4979                 if (table[i].from == argv[optind][0])
4980                         break;
4981
4982         if (i >= ELEMENTSOF(table)) {
4983                 log_error("Unknown command %s.", argv[optind]);
4984                 return -EINVAL;
4985         }
4986
4987         arg_action = table[i].to;
4988
4989         optind ++;
4990
4991         return 1;
4992 }
4993
4994 static int runlevel_parse_argv(int argc, char *argv[]) {
4995
4996         enum {
4997                 ARG_HELP = 0x100,
4998         };
4999
5000         static const struct option options[] = {
5001                 { "help",      no_argument,       NULL, ARG_HELP    },
5002                 { NULL,        0,                 NULL, 0           }
5003         };
5004
5005         int c;
5006
5007         assert(argc >= 0);
5008         assert(argv);
5009
5010         while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5011                 switch (c) {
5012
5013                 case ARG_HELP:
5014                         runlevel_help();
5015                         return 0;
5016
5017                 case '?':
5018                         return -EINVAL;
5019
5020                 default:
5021                         log_error("Unknown option code %c", c);
5022                         return -EINVAL;
5023                 }
5024         }
5025
5026         if (optind < argc) {
5027                 log_error("Too many arguments.");
5028                 return -EINVAL;
5029         }
5030
5031         return 1;
5032 }
5033
5034 static int parse_argv(int argc, char *argv[]) {
5035         assert(argc >= 0);
5036         assert(argv);
5037
5038         if (program_invocation_short_name) {
5039
5040                 if (strstr(program_invocation_short_name, "halt")) {
5041                         arg_action = ACTION_HALT;
5042                         return halt_parse_argv(argc, argv);
5043                 } else if (strstr(program_invocation_short_name, "poweroff")) {
5044                         arg_action = ACTION_POWEROFF;
5045                         return halt_parse_argv(argc, argv);
5046                 } else if (strstr(program_invocation_short_name, "reboot")) {
5047                         if (kexec_loaded())
5048                                 arg_action = ACTION_KEXEC;
5049                         else
5050                                 arg_action = ACTION_REBOOT;
5051                         return halt_parse_argv(argc, argv);
5052                 } else if (strstr(program_invocation_short_name, "shutdown")) {
5053                         arg_action = ACTION_POWEROFF;
5054                         return shutdown_parse_argv(argc, argv);
5055                 } else if (strstr(program_invocation_short_name, "init")) {
5056
5057                         if (sd_booted() > 0) {
5058                                 arg_action = ACTION_INVALID;
5059                                 return telinit_parse_argv(argc, argv);
5060                         } else {
5061                                 /* Hmm, so some other init system is
5062                                  * running, we need to forward this
5063                                  * request to it. For now we simply
5064                                  * guess that it is Upstart. */
5065
5066                                 execv("/lib/upstart/telinit", argv);
5067
5068                                 log_error("Couldn't find an alternative telinit implementation to spawn.");
5069                                 return -EIO;
5070                         }
5071
5072                 } else if (strstr(program_invocation_short_name, "runlevel")) {
5073                         arg_action = ACTION_RUNLEVEL;
5074                         return runlevel_parse_argv(argc, argv);
5075                 }
5076         }
5077
5078         arg_action = ACTION_SYSTEMCTL;
5079         return systemctl_parse_argv(argc, argv);
5080 }
5081
5082 static int action_to_runlevel(void) {
5083
5084         static const char table[_ACTION_MAX] = {
5085                 [ACTION_HALT] =      '0',
5086                 [ACTION_POWEROFF] =  '0',
5087                 [ACTION_REBOOT] =    '6',
5088                 [ACTION_RUNLEVEL2] = '2',
5089                 [ACTION_RUNLEVEL3] = '3',
5090                 [ACTION_RUNLEVEL4] = '4',
5091                 [ACTION_RUNLEVEL5] = '5',
5092                 [ACTION_RESCUE] =    '1'
5093         };
5094
5095         assert(arg_action < _ACTION_MAX);
5096
5097         return table[arg_action];
5098 }
5099
5100 static int talk_upstart(void) {
5101         DBusMessage *m = NULL, *reply = NULL;
5102         DBusError error;
5103         int previous, rl, r;
5104         char
5105                 env1_buf[] = "RUNLEVEL=X",
5106                 env2_buf[] = "PREVLEVEL=X";
5107         char *env1 = env1_buf, *env2 = env2_buf;
5108         const char *emit = "runlevel";
5109         dbus_bool_t b_false = FALSE;
5110         DBusMessageIter iter, sub;
5111         DBusConnection *bus;
5112
5113         dbus_error_init(&error);
5114
5115         if (!(rl = action_to_runlevel()))
5116                 return 0;
5117
5118         if (utmp_get_runlevel(&previous, NULL) < 0)
5119                 previous = 'N';
5120
5121         if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
5122                 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
5123                         r = 0;
5124                         goto finish;
5125                 }
5126
5127                 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
5128                 r = -EIO;
5129                 goto finish;
5130         }
5131
5132         if ((r = bus_check_peercred(bus)) < 0) {
5133                 log_error("Failed to verify owner of bus.");
5134                 goto finish;
5135         }
5136
5137         if (!(m = dbus_message_new_method_call(
5138                               "com.ubuntu.Upstart",
5139                               "/com/ubuntu/Upstart",
5140                               "com.ubuntu.Upstart0_6",
5141                               "EmitEvent"))) {
5142
5143                 log_error("Could not allocate message.");
5144                 r = -ENOMEM;
5145                 goto finish;
5146         }
5147
5148         dbus_message_iter_init_append(m, &iter);
5149
5150         env1_buf[sizeof(env1_buf)-2] = rl;
5151         env2_buf[sizeof(env2_buf)-2] = previous;
5152
5153         if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5154             !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5155             !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5156             !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5157             !dbus_message_iter_close_container(&iter, &sub) ||
5158             !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5159                 log_error("Could not append arguments to message.");
5160                 r = -ENOMEM;
5161                 goto finish;
5162         }
5163
5164         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5165
5166                 if (error_is_no_service(&error)) {
5167                         r = -EADDRNOTAVAIL;
5168                         goto finish;
5169                 }
5170
5171                 log_error("Failed to issue method call: %s", bus_error_message(&error));
5172                 r = -EIO;
5173                 goto finish;
5174         }
5175
5176         r = 0;
5177
5178 finish:
5179         if (m)
5180                 dbus_message_unref(m);
5181
5182         if (reply)
5183                 dbus_message_unref(reply);
5184
5185         if (bus) {
5186                 dbus_connection_flush(bus);
5187                 dbus_connection_close(bus);
5188                 dbus_connection_unref(bus);
5189         }
5190
5191         dbus_error_free(&error);
5192
5193         return r;
5194 }
5195
5196 static int talk_initctl(void) {
5197         struct init_request request;
5198         int r, fd;
5199         char rl;
5200
5201         if (!(rl = action_to_runlevel()))
5202                 return 0;
5203
5204         zero(request);
5205         request.magic = INIT_MAGIC;
5206         request.sleeptime = 0;
5207         request.cmd = INIT_CMD_RUNLVL;
5208         request.runlevel = rl;
5209
5210         if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5211
5212                 if (errno == ENOENT)
5213                         return 0;
5214
5215                 log_error("Failed to open "INIT_FIFO": %m");
5216                 return -errno;
5217         }
5218
5219         errno = 0;
5220         r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5221         close_nointr_nofail(fd);
5222
5223         if (r < 0) {
5224                 log_error("Failed to write to "INIT_FIFO": %m");
5225                 return errno ? -errno : -EIO;
5226         }
5227
5228         return 1;
5229 }
5230
5231 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5232
5233         static const struct {
5234                 const char* verb;
5235                 const enum {
5236                         MORE,
5237                         LESS,
5238                         EQUAL
5239                 } argc_cmp;
5240                 const int argc;
5241                 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
5242         } verbs[] = {
5243                 { "list-units",            LESS,  1, list_units        },
5244                 { "list-jobs",             EQUAL, 1, list_jobs         },
5245                 { "clear-jobs",            EQUAL, 1, daemon_reload     },
5246                 { "load",                  MORE,  2, load_unit         },
5247                 { "cancel",                MORE,  2, cancel_job        },
5248                 { "start",                 MORE,  2, start_unit        },
5249                 { "stop",                  MORE,  2, start_unit        },
5250                 { "condstop",              MORE,  2, start_unit        }, /* For compatibility with ALTLinux */
5251                 { "reload",                MORE,  2, start_unit        },
5252                 { "restart",               MORE,  2, start_unit        },
5253                 { "try-restart",           MORE,  2, start_unit        },
5254                 { "reload-or-restart",     MORE,  2, start_unit        },
5255                 { "reload-or-try-restart", MORE,  2, start_unit        },
5256                 { "force-reload",          MORE,  2, start_unit        }, /* For compatibility with SysV */
5257                 { "condreload",            MORE,  2, start_unit        }, /* For compatibility with ALTLinux */
5258                 { "condrestart",           MORE,  2, start_unit        }, /* For compatibility with RH */
5259                 { "isolate",               EQUAL, 2, start_unit        },
5260                 { "kill",                  MORE,  2, kill_unit         },
5261                 { "is-active",             MORE,  2, check_unit        },
5262                 { "check",                 MORE,  2, check_unit        },
5263                 { "show",                  MORE,  1, show              },
5264                 { "status",                MORE,  2, show              },
5265                 { "monitor",               EQUAL, 1, monitor           },
5266                 { "dump",                  EQUAL, 1, dump              },
5267                 { "dot",                   EQUAL, 1, dot               },
5268                 { "snapshot",              LESS,  2, snapshot          },
5269                 { "delete",                MORE,  2, delete_snapshot   },
5270                 { "daemon-reload",         EQUAL, 1, daemon_reload     },
5271                 { "daemon-reexec",         EQUAL, 1, daemon_reload     },
5272                 { "show-environment",      EQUAL, 1, show_enviroment   },
5273                 { "set-environment",       MORE,  2, set_environment   },
5274                 { "unset-environment",     MORE,  2, set_environment   },
5275                 { "halt",                  EQUAL, 1, start_special     },
5276                 { "poweroff",              EQUAL, 1, start_special     },
5277                 { "reboot",                EQUAL, 1, start_special     },
5278                 { "kexec",                 EQUAL, 1, start_special     },
5279                 { "default",               EQUAL, 1, start_special     },
5280                 { "rescue",                EQUAL, 1, start_special     },
5281                 { "emergency",             EQUAL, 1, start_special     },
5282                 { "exit",                  EQUAL, 1, start_special     },
5283                 { "reset-failed",          MORE,  1, reset_failed      },
5284                 { "enable",                MORE,  2, enable_unit       },
5285                 { "disable",               MORE,  2, enable_unit       },
5286                 { "is-enabled",            MORE,  2, enable_unit       }
5287         };
5288
5289         int left;
5290         unsigned i;
5291
5292         assert(argc >= 0);
5293         assert(argv);
5294         assert(error);
5295
5296         left = argc - optind;
5297
5298         if (left <= 0)
5299                 /* Special rule: no arguments means "list-units" */
5300                 i = 0;
5301         else {
5302                 if (streq(argv[optind], "help")) {
5303                         systemctl_help();
5304                         return 0;
5305                 }
5306
5307                 for (i = 0; i < ELEMENTSOF(verbs); i++)
5308                         if (streq(argv[optind], verbs[i].verb))
5309                                 break;
5310
5311                 if (i >= ELEMENTSOF(verbs)) {
5312                         log_error("Unknown operation %s", argv[optind]);
5313                         return -EINVAL;
5314                 }
5315         }
5316
5317         switch (verbs[i].argc_cmp) {
5318
5319         case EQUAL:
5320                 if (left != verbs[i].argc) {
5321                         log_error("Invalid number of arguments.");
5322                         return -EINVAL;
5323                 }
5324
5325                 break;
5326
5327         case MORE:
5328                 if (left < verbs[i].argc) {
5329                         log_error("Too few arguments.");
5330                         return -EINVAL;
5331                 }
5332
5333                 break;
5334
5335         case LESS:
5336                 if (left > verbs[i].argc) {
5337                         log_error("Too many arguments.");
5338                         return -EINVAL;
5339                 }
5340
5341                 break;
5342
5343         default:
5344                 assert_not_reached("Unknown comparison operator.");
5345         }
5346
5347         /* Require a bus connection for all operations but
5348          * enable/disable */
5349         if (!streq(verbs[i].verb, "enable") && !streq(verbs[i].verb, "disable")) {
5350
5351                 if (running_in_chroot() > 0) {
5352                         log_info("Running in chroot, ignoring request.");
5353                         return 0;
5354                 }
5355
5356                 if (!bus) {
5357                         log_error("Failed to get D-Bus connection: %s", error->message);
5358                         return -EIO;
5359                 }
5360         }
5361
5362         return verbs[i].dispatch(bus, argv + optind, left);
5363 }
5364
5365 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
5366         int fd = -1;
5367         struct msghdr msghdr;
5368         struct iovec iovec;
5369         union sockaddr_union sockaddr;
5370         struct shutdownd_command c;
5371
5372         zero(c);
5373         c.elapse = t;
5374         c.mode = mode;
5375         c.warn_wall = warn;
5376
5377         if (message)
5378                 strncpy(c.wall_message, message, sizeof(c.wall_message));
5379
5380         if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
5381                 return -errno;
5382
5383         zero(sockaddr);
5384         sockaddr.sa.sa_family = AF_UNIX;
5385         sockaddr.un.sun_path[0] = 0;
5386         strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5387
5388         zero(iovec);
5389         iovec.iov_base = (char*) &c;
5390         iovec.iov_len = sizeof(c);
5391
5392         zero(msghdr);
5393         msghdr.msg_name = &sockaddr;
5394         msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5395
5396         msghdr.msg_iov = &iovec;
5397         msghdr.msg_iovlen = 1;
5398
5399         if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5400                 close_nointr_nofail(fd);
5401                 return -errno;
5402         }
5403
5404         close_nointr_nofail(fd);
5405         return 0;
5406 }
5407
5408 static int reload_with_fallback(DBusConnection *bus) {
5409
5410         if (bus) {
5411                 /* First, try systemd via D-Bus. */
5412                 if (daemon_reload(bus, NULL, 0) > 0)
5413                         return 0;
5414         }
5415
5416         /* Nothing else worked, so let's try signals */
5417         assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5418
5419         if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5420                 log_error("kill() failed: %m");
5421                 return -errno;
5422         }
5423
5424         return 0;
5425 }
5426
5427 static int start_with_fallback(DBusConnection *bus) {
5428
5429         if (bus) {
5430                 /* First, try systemd via D-Bus. */
5431                 if (start_unit(bus, NULL, 0) >= 0)
5432                         goto done;
5433         }
5434
5435         /* Hmm, talking to systemd via D-Bus didn't work. Then
5436          * let's try to talk to Upstart via D-Bus. */
5437         if (talk_upstart() > 0)
5438                 goto done;
5439
5440         /* Nothing else worked, so let's try
5441          * /dev/initctl */
5442         if (talk_initctl() > 0)
5443                 goto done;
5444
5445         log_error("Failed to talk to init daemon.");
5446         return -EIO;
5447
5448 done:
5449         warn_wall(arg_action);
5450         return 0;
5451 }
5452
5453 static int halt_main(DBusConnection *bus) {
5454         int r;
5455
5456         if (geteuid() != 0) {
5457                 log_error("Must be root.");
5458                 return -EPERM;
5459         }
5460
5461         if (arg_when > 0) {
5462                 char *m;
5463                 char date[FORMAT_TIMESTAMP_MAX];
5464
5465                 m = strv_join(arg_wall, " ");
5466                 r = send_shutdownd(arg_when,
5467                                    arg_action == ACTION_HALT     ? 'H' :
5468                                    arg_action == ACTION_POWEROFF ? 'P' :
5469                                                                    'r',
5470                                    !arg_no_wall,
5471                                    m);
5472                 free(m);
5473
5474                 if (r < 0)
5475                         log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5476                 else {
5477                         log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5478                                  format_timestamp(date, sizeof(date), arg_when));
5479                         return 0;
5480                 }
5481         }
5482
5483         if (!arg_dry && !arg_immediate)
5484                 return start_with_fallback(bus);
5485
5486         if (!arg_no_wtmp) {
5487                 if (sd_booted() > 0)
5488                         log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5489                 else if ((r = utmp_put_shutdown(0)) < 0)
5490                         log_warning("Failed to write utmp record: %s", strerror(-r));
5491         }
5492
5493         if (!arg_no_sync)
5494                 sync();
5495
5496         if (arg_dry)
5497                 return 0;
5498
5499         /* Make sure C-A-D is handled by the kernel from this
5500          * point on... */
5501         reboot(RB_ENABLE_CAD);
5502
5503         switch (arg_action) {
5504
5505         case ACTION_HALT:
5506                 log_info("Halting.");
5507                 reboot(RB_HALT_SYSTEM);
5508                 break;
5509
5510         case ACTION_POWEROFF:
5511                 log_info("Powering off.");
5512                 reboot(RB_POWER_OFF);
5513                 break;
5514
5515         case ACTION_REBOOT:
5516                 log_info("Rebooting.");
5517                 reboot(RB_AUTOBOOT);
5518                 break;
5519
5520         default:
5521                 assert_not_reached("Unknown halt action.");
5522         }
5523
5524         /* We should never reach this. */
5525         return -ENOSYS;
5526 }
5527
5528 static int runlevel_main(void) {
5529         int r, runlevel, previous;
5530
5531         if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5532                 printf("unknown\n");
5533                 return r;
5534         }
5535
5536         printf("%c %c\n",
5537                previous <= 0 ? 'N' : previous,
5538                runlevel <= 0 ? 'N' : runlevel);
5539
5540         return 0;
5541 }
5542
5543 static void pager_open(void) {
5544         int fd[2];
5545         const char *pager;
5546         pid_t parent_pid;
5547
5548         if (pager_pid > 0)
5549                 return;
5550
5551         if (!on_tty() || arg_no_pager)
5552                 return;
5553
5554         if ((pager = getenv("PAGER")))
5555                 if (!*pager || streq(pager, "cat"))
5556                         return;
5557
5558         /* Determine and cache number of columns before we spawn the
5559          * pager so that we get the value from the actual tty */
5560         columns();
5561
5562         if (pipe(fd) < 0) {
5563                 log_error("Failed to create pager pipe: %m");
5564                 return;
5565         }
5566
5567         parent_pid = getpid();
5568
5569         pager_pid = fork();
5570         if (pager_pid < 0) {
5571                 log_error("Failed to fork pager: %m");
5572                 close_pipe(fd);
5573                 return;
5574         }
5575
5576         /* In the child start the pager */
5577         if (pager_pid == 0) {
5578
5579                 dup2(fd[0], STDIN_FILENO);
5580                 close_pipe(fd);
5581
5582                 setenv("LESS", "FRSX", 0);
5583
5584                 /* Make sure the pager goes away when the parent dies */
5585                 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5586                         _exit(EXIT_FAILURE);
5587
5588                 /* Check whether our parent died before we were able
5589                  * to set the death signal */
5590                 if (getppid() != parent_pid)
5591                         _exit(EXIT_SUCCESS);
5592
5593                 if (pager) {
5594                         execlp(pager, pager, NULL);
5595                         execl("/bin/sh", "sh", "-c", pager, NULL);
5596                 } else {
5597                         /* Debian's alternatives command for pagers is
5598                          * called 'pager'. Note that we do not call
5599                          * sensible-pagers here, since that is just a
5600                          * shell script that implements a logic that
5601                          * is similar to this one anyway, but is
5602                          * Debian-specific. */
5603                         execlp("pager", "pager", NULL);
5604
5605                         execlp("less", "less", NULL);
5606                         execlp("more", "more", NULL);
5607                 }
5608
5609                 log_error("Unable to execute pager: %m");
5610                 _exit(EXIT_FAILURE);
5611         }
5612
5613         /* Return in the parent */
5614         if (dup2(fd[1], STDOUT_FILENO) < 0)
5615                 log_error("Failed to duplicate pager pipe: %m");
5616
5617         close_pipe(fd);
5618 }
5619
5620 static void pager_close(void) {
5621         siginfo_t dummy;
5622
5623         if (pager_pid <= 0)
5624                 return;
5625
5626         /* Inform pager that we are done */
5627         fclose(stdout);
5628         kill(pager_pid, SIGCONT);
5629         wait_for_terminate(pager_pid, &dummy);
5630         pager_pid = 0;
5631 }
5632
5633 static void agent_close(void) {
5634         siginfo_t dummy;
5635
5636         if (agent_pid <= 0)
5637                 return;
5638
5639         /* Inform agent that we are done */
5640         kill(agent_pid, SIGTERM);
5641         kill(agent_pid, SIGCONT);
5642         wait_for_terminate(agent_pid, &dummy);
5643         agent_pid = 0;
5644 }
5645
5646 int main(int argc, char*argv[]) {
5647         int r, retval = EXIT_FAILURE;
5648         DBusConnection *bus = NULL;
5649         DBusError error;
5650
5651         dbus_error_init(&error);
5652
5653         log_parse_environment();
5654         log_open();
5655
5656         if ((r = parse_argv(argc, argv)) < 0)
5657                 goto finish;
5658         else if (r == 0) {
5659                 retval = EXIT_SUCCESS;
5660                 goto finish;
5661         }
5662
5663         /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5664          * let's shortcut this */
5665         if (arg_action == ACTION_RUNLEVEL) {
5666                 r = runlevel_main();
5667                 retval = r < 0 ? EXIT_FAILURE : r;
5668                 goto finish;
5669         }
5670
5671         if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5672                 log_info("Running in chroot, ignoring request.");
5673                 retval = 0;
5674                 goto finish;
5675         }
5676
5677         if (arg_transport == TRANSPORT_NORMAL)
5678                 bus_connect(arg_user ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5679         else if (arg_transport == TRANSPORT_POLKIT) {
5680                 bus_connect_system_polkit(&bus, &error);
5681                 private_bus = false;
5682         } else if (arg_transport == TRANSPORT_SSH) {
5683                 bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5684                 private_bus = false;
5685         } else
5686                 assert_not_reached("Uh, invalid transport...");
5687
5688         switch (arg_action) {
5689
5690         case ACTION_SYSTEMCTL:
5691                 r = systemctl_main(bus, argc, argv, &error);
5692                 break;
5693
5694         case ACTION_HALT:
5695         case ACTION_POWEROFF:
5696         case ACTION_REBOOT:
5697         case ACTION_KEXEC:
5698                 r = halt_main(bus);
5699                 break;
5700
5701         case ACTION_RUNLEVEL2:
5702         case ACTION_RUNLEVEL3:
5703         case ACTION_RUNLEVEL4:
5704         case ACTION_RUNLEVEL5:
5705         case ACTION_RESCUE:
5706         case ACTION_EMERGENCY:
5707         case ACTION_DEFAULT:
5708                 r = start_with_fallback(bus);
5709                 break;
5710
5711         case ACTION_RELOAD:
5712         case ACTION_REEXEC:
5713                 r = reload_with_fallback(bus);
5714                 break;
5715
5716         case ACTION_CANCEL_SHUTDOWN:
5717                 r = send_shutdownd(0, 0, false, NULL);
5718                 break;
5719
5720         case ACTION_INVALID:
5721         case ACTION_RUNLEVEL:
5722         default:
5723                 assert_not_reached("Unknown action");
5724         }
5725
5726         retval = r < 0 ? EXIT_FAILURE : r;
5727
5728 finish:
5729
5730         if (bus) {
5731                 dbus_connection_flush(bus);
5732                 dbus_connection_close(bus);
5733                 dbus_connection_unref(bus);
5734         }
5735
5736         dbus_error_free(&error);
5737
5738         dbus_shutdown();
5739
5740         strv_free(arg_property);
5741
5742         pager_close();
5743         agent_close();
5744
5745         return retval;
5746 }