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