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