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