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