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