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