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