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