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