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