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