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