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