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