chiark / gitweb /
exit-status: add missing files src/exit-status.h src/exit-status.c
[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.DBus.Properties", "PropertiesChanged")) {
2394
2395                 const char *path, *interface, *property = "Id";
2396                 DBusMessageIter iter, sub;
2397
2398                 path = dbus_message_get_path(message);
2399
2400                 if (!dbus_message_get_args(message, &error,
2401                                           DBUS_TYPE_STRING, &interface,
2402                                           DBUS_TYPE_INVALID)) {
2403                         log_error("Failed to parse message: %s", error.message);
2404                         goto finish;
2405                 }
2406
2407                 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2408                     !streq(interface, "org.freedesktop.systemd1.Unit"))
2409                         goto finish;
2410
2411                 if (!(m = dbus_message_new_method_call(
2412                               "org.freedesktop.systemd1",
2413                               path,
2414                               "org.freedesktop.DBus.Properties",
2415                               "Get"))) {
2416                         log_error("Could not allocate message.");
2417                         goto oom;
2418                 }
2419
2420                 if (!dbus_message_append_args(m,
2421                                               DBUS_TYPE_STRING, &interface,
2422                                               DBUS_TYPE_STRING, &property,
2423                                               DBUS_TYPE_INVALID)) {
2424                         log_error("Could not append arguments to message.");
2425                         goto finish;
2426                 }
2427
2428                 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2429                         log_error("Failed to issue method call: %s", error.message);
2430                         goto finish;
2431                 }
2432
2433                 if (!dbus_message_iter_init(reply, &iter) ||
2434                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
2435                         log_error("Failed to parse reply.");
2436                         goto finish;
2437                 }
2438
2439                 dbus_message_iter_recurse(&iter, &sub);
2440
2441                 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2442                         const char *id;
2443
2444                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
2445                                 log_error("Failed to parse reply.");
2446                                 goto finish;
2447                         }
2448
2449                         dbus_message_iter_get_basic(&sub, &id);
2450                         printf("Unit %s changed.\n", id);
2451                 } else {
2452                         uint32_t id;
2453
2454                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32)  {
2455                                 log_error("Failed to parse reply.");
2456                                 goto finish;
2457                         }
2458
2459                         dbus_message_iter_get_basic(&sub, &id);
2460                         printf("Job %u changed.\n", id);
2461                 }
2462         }
2463
2464 finish:
2465         if (m)
2466                 dbus_message_unref(m);
2467
2468         if (reply)
2469                 dbus_message_unref(reply);
2470
2471         dbus_error_free(&error);
2472         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2473
2474 oom:
2475         if (m)
2476                 dbus_message_unref(m);
2477
2478         if (reply)
2479                 dbus_message_unref(reply);
2480
2481         dbus_error_free(&error);
2482         return DBUS_HANDLER_RESULT_NEED_MEMORY;
2483 }
2484
2485 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2486         DBusMessage *m = NULL, *reply = NULL;
2487         DBusError error;
2488         int r;
2489
2490         dbus_error_init(&error);
2491
2492         if (!private_bus) {
2493                 dbus_bus_add_match(bus,
2494                                    "type='signal',"
2495                                    "sender='org.freedesktop.systemd1',"
2496                                    "interface='org.freedesktop.systemd1.Manager',"
2497                                    "path='/org/freedesktop/systemd1'",
2498                                    &error);
2499
2500                 if (dbus_error_is_set(&error)) {
2501                         log_error("Failed to add match: %s", error.message);
2502                         r = -EIO;
2503                         goto finish;
2504                 }
2505
2506                 dbus_bus_add_match(bus,
2507                                    "type='signal',"
2508                                    "sender='org.freedesktop.systemd1',"
2509                                    "interface='org.freedesktop.DBus.Properties',"
2510                                    "member='PropertiesChanged'",
2511                                    &error);
2512
2513                 if (dbus_error_is_set(&error)) {
2514                         log_error("Failed to add match: %s", error.message);
2515                         r = -EIO;
2516                         goto finish;
2517                 }
2518         }
2519
2520         if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2521                 log_error("Failed to add filter.");
2522                 r = -ENOMEM;
2523                 goto finish;
2524         }
2525
2526         if (!(m = dbus_message_new_method_call(
2527                               "org.freedesktop.systemd1",
2528                               "/org/freedesktop/systemd1",
2529                               "org.freedesktop.systemd1.Manager",
2530                               "Subscribe"))) {
2531                 log_error("Could not allocate message.");
2532                 r = -ENOMEM;
2533                 goto finish;
2534         }
2535
2536         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2537                 log_error("Failed to issue method call: %s", error.message);
2538                 r = -EIO;
2539                 goto finish;
2540         }
2541
2542         while (dbus_connection_read_write_dispatch(bus, -1))
2543                 ;
2544
2545         r = 0;
2546
2547 finish:
2548
2549         /* This is slightly dirty, since we don't undo the filter or the matches. */
2550
2551         if (m)
2552                 dbus_message_unref(m);
2553
2554         if (reply)
2555                 dbus_message_unref(reply);
2556
2557         dbus_error_free(&error);
2558
2559         return r;
2560 }
2561
2562 static int dump(DBusConnection *bus, char **args, unsigned n) {
2563         DBusMessage *m = NULL, *reply = NULL;
2564         DBusError error;
2565         int r;
2566         const char *text;
2567
2568         dbus_error_init(&error);
2569
2570         if (!(m = dbus_message_new_method_call(
2571                               "org.freedesktop.systemd1",
2572                               "/org/freedesktop/systemd1",
2573                               "org.freedesktop.systemd1.Manager",
2574                               "Dump"))) {
2575                 log_error("Could not allocate message.");
2576                 return -ENOMEM;
2577         }
2578
2579         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2580                 log_error("Failed to issue method call: %s", error.message);
2581                 r = -EIO;
2582                 goto finish;
2583         }
2584
2585         if (!dbus_message_get_args(reply, &error,
2586                                    DBUS_TYPE_STRING, &text,
2587                                    DBUS_TYPE_INVALID)) {
2588                 log_error("Failed to parse reply: %s", error.message);
2589                 r = -EIO;
2590                 goto finish;
2591         }
2592
2593         fputs(text, stdout);
2594
2595         r = 0;
2596
2597 finish:
2598         if (m)
2599                 dbus_message_unref(m);
2600
2601         if (reply)
2602                 dbus_message_unref(reply);
2603
2604         dbus_error_free(&error);
2605
2606         return r;
2607 }
2608
2609 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2610         DBusMessage *m = NULL, *reply = NULL;
2611         DBusError error;
2612         int r;
2613         const char *name = "", *path, *id;
2614         dbus_bool_t cleanup = FALSE;
2615         DBusMessageIter iter, sub;
2616         const char
2617                 *interface = "org.freedesktop.systemd1.Unit",
2618                 *property = "Id";
2619
2620         dbus_error_init(&error);
2621
2622         if (!(m = dbus_message_new_method_call(
2623                               "org.freedesktop.systemd1",
2624                               "/org/freedesktop/systemd1",
2625                               "org.freedesktop.systemd1.Manager",
2626                               "CreateSnapshot"))) {
2627                 log_error("Could not allocate message.");
2628                 return -ENOMEM;
2629         }
2630
2631         if (n > 1)
2632                 name = args[1];
2633
2634         if (!dbus_message_append_args(m,
2635                                       DBUS_TYPE_STRING, &name,
2636                                       DBUS_TYPE_BOOLEAN, &cleanup,
2637                                       DBUS_TYPE_INVALID)) {
2638                 log_error("Could not append arguments to message.");
2639                 r = -ENOMEM;
2640                 goto finish;
2641         }
2642
2643         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2644                 log_error("Failed to issue method call: %s", error.message);
2645                 r = -EIO;
2646                 goto finish;
2647         }
2648
2649         if (!dbus_message_get_args(reply, &error,
2650                                    DBUS_TYPE_OBJECT_PATH, &path,
2651                                    DBUS_TYPE_INVALID)) {
2652                 log_error("Failed to parse reply: %s", error.message);
2653                 r = -EIO;
2654                 goto finish;
2655         }
2656
2657         dbus_message_unref(m);
2658         if (!(m = dbus_message_new_method_call(
2659                               "org.freedesktop.systemd1",
2660                               path,
2661                               "org.freedesktop.DBus.Properties",
2662                               "Get"))) {
2663                 log_error("Could not allocate message.");
2664                 return -ENOMEM;
2665         }
2666
2667         if (!dbus_message_append_args(m,
2668                                       DBUS_TYPE_STRING, &interface,
2669                                       DBUS_TYPE_STRING, &property,
2670                                       DBUS_TYPE_INVALID)) {
2671                 log_error("Could not append arguments to message.");
2672                 r = -ENOMEM;
2673                 goto finish;
2674         }
2675
2676         dbus_message_unref(reply);
2677         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2678                 log_error("Failed to issue method call: %s", error.message);
2679                 r = -EIO;
2680                 goto finish;
2681         }
2682
2683         if (!dbus_message_iter_init(reply, &iter) ||
2684             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
2685                 log_error("Failed to parse reply.");
2686                 r = -EIO;
2687                 goto finish;
2688         }
2689
2690         dbus_message_iter_recurse(&iter, &sub);
2691
2692         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
2693                 log_error("Failed to parse reply.");
2694                 r = -EIO;
2695                 goto finish;
2696         }
2697
2698         dbus_message_iter_get_basic(&sub, &id);
2699
2700         if (!arg_quiet)
2701                 puts(id);
2702         r = 0;
2703
2704 finish:
2705         if (m)
2706                 dbus_message_unref(m);
2707
2708         if (reply)
2709                 dbus_message_unref(reply);
2710
2711         dbus_error_free(&error);
2712
2713         return r;
2714 }
2715
2716 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2717         DBusMessage *m = NULL, *reply = NULL;
2718         int r;
2719         DBusError error;
2720         unsigned i;
2721
2722         assert(bus);
2723         assert(args);
2724
2725         dbus_error_init(&error);
2726
2727         for (i = 1; i < n; i++) {
2728                 const char *path = NULL;
2729
2730                 if (!(m = dbus_message_new_method_call(
2731                                       "org.freedesktop.systemd1",
2732                                       "/org/freedesktop/systemd1",
2733                                       "org.freedesktop.systemd1.Manager",
2734                                       "GetUnit"))) {
2735                         log_error("Could not allocate message.");
2736                         r = -ENOMEM;
2737                         goto finish;
2738                 }
2739
2740                 if (!dbus_message_append_args(m,
2741                                               DBUS_TYPE_STRING, &args[i],
2742                                               DBUS_TYPE_INVALID)) {
2743                         log_error("Could not append arguments to message.");
2744                         r = -ENOMEM;
2745                         goto finish;
2746                 }
2747
2748                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2749                         log_error("Failed to issue method call: %s", error.message);
2750                         r = -EIO;
2751                         goto finish;
2752                 }
2753
2754                 if (!dbus_message_get_args(reply, &error,
2755                                            DBUS_TYPE_OBJECT_PATH, &path,
2756                                            DBUS_TYPE_INVALID)) {
2757                         log_error("Failed to parse reply: %s", error.message);
2758                         r = -EIO;
2759                         goto finish;
2760                 }
2761
2762                 dbus_message_unref(m);
2763                 if (!(m = dbus_message_new_method_call(
2764                                       "org.freedesktop.systemd1",
2765                                       path,
2766                                       "org.freedesktop.systemd1.Snapshot",
2767                                       "Remove"))) {
2768                         log_error("Could not allocate message.");
2769                         r = -ENOMEM;
2770                         goto finish;
2771                 }
2772
2773                 dbus_message_unref(reply);
2774                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2775                         log_error("Failed to issue method call: %s", error.message);
2776                         r = -EIO;
2777                         goto finish;
2778                 }
2779
2780                 dbus_message_unref(m);
2781                 dbus_message_unref(reply);
2782                 m = reply = NULL;
2783         }
2784
2785         r = 0;
2786
2787 finish:
2788         if (m)
2789                 dbus_message_unref(m);
2790
2791         if (reply)
2792                 dbus_message_unref(reply);
2793
2794         dbus_error_free(&error);
2795
2796         return r;
2797 }
2798
2799 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2800         DBusMessage *m = NULL, *reply = NULL;
2801         DBusError error;
2802         int r;
2803         const char *method;
2804
2805         dbus_error_init(&error);
2806
2807         if (arg_action == ACTION_RELOAD)
2808                 method = "Reload";
2809         else if (arg_action == ACTION_REEXEC)
2810                 method = "Reexecute";
2811         else {
2812                 assert(arg_action == ACTION_SYSTEMCTL);
2813
2814                 method =
2815                         streq(args[0], "clear-jobs")        ||
2816                         streq(args[0], "cancel")            ? "ClearJobs" :
2817                         streq(args[0], "daemon-reexec")     ? "Reexecute" :
2818                         streq(args[0], "reset-maintenance") ? "ResetMaintenance" :
2819                         streq(args[0], "daemon-exit")       ? "Exit" :
2820                                                               "Reload";
2821         }
2822
2823         if (!(m = dbus_message_new_method_call(
2824                               "org.freedesktop.systemd1",
2825                               "/org/freedesktop/systemd1",
2826                               "org.freedesktop.systemd1.Manager",
2827                               method))) {
2828                 log_error("Could not allocate message.");
2829                 return -ENOMEM;
2830         }
2831
2832         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2833
2834                 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
2835                         /* There's always a fallback possible for
2836                          * legacy actions. */
2837                         r = 0;
2838                         goto finish;
2839                 }
2840
2841                 log_error("Failed to issue method call: %s", error.message);
2842                 r = -EIO;
2843                 goto finish;
2844         }
2845
2846         r = 1;
2847
2848 finish:
2849         if (m)
2850                 dbus_message_unref(m);
2851
2852         if (reply)
2853                 dbus_message_unref(reply);
2854
2855         dbus_error_free(&error);
2856
2857         return r;
2858 }
2859
2860 static int reset_maintenance(DBusConnection *bus, char **args, unsigned n) {
2861         DBusMessage *m = NULL, *reply = NULL;
2862         unsigned i;
2863         int r;
2864         DBusError error;
2865
2866         assert(bus);
2867         dbus_error_init(&error);
2868
2869         if (n <= 1)
2870                 return daemon_reload(bus, args, n);
2871
2872         for (i = 1; i < n; i++) {
2873
2874                 if (!(m = dbus_message_new_method_call(
2875                                       "org.freedesktop.systemd1",
2876                                       "/org/freedesktop/systemd1",
2877                                       "org.freedesktop.systemd1.Manager",
2878                                       "ResetMaintenanceUnit"))) {
2879                         log_error("Could not allocate message.");
2880                         r = -ENOMEM;
2881                         goto finish;
2882                 }
2883
2884                 if (!dbus_message_append_args(m,
2885                                               DBUS_TYPE_STRING, args + i,
2886                                               DBUS_TYPE_INVALID)) {
2887                         log_error("Could not append arguments to message.");
2888                         r = -ENOMEM;
2889                         goto finish;
2890                 }
2891
2892                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2893                         log_error("Failed to issue method call: %s", error.message);
2894                         r = -EIO;
2895                         goto finish;
2896                 }
2897
2898                 dbus_message_unref(m);
2899                 dbus_message_unref(reply);
2900                 m = reply = NULL;
2901         }
2902
2903         r = 0;
2904
2905 finish:
2906         if (m)
2907                 dbus_message_unref(m);
2908
2909         if (reply)
2910                 dbus_message_unref(reply);
2911
2912         dbus_error_free(&error);
2913
2914         return r;
2915 }
2916
2917 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
2918         DBusMessage *m = NULL, *reply = NULL;
2919         DBusError error;
2920         DBusMessageIter iter, sub, sub2;
2921         int r;
2922         const char
2923                 *interface = "org.freedesktop.systemd1.Manager",
2924                 *property = "Environment";
2925
2926         dbus_error_init(&error);
2927
2928         if (!(m = dbus_message_new_method_call(
2929                               "org.freedesktop.systemd1",
2930                               "/org/freedesktop/systemd1",
2931                               "org.freedesktop.DBus.Properties",
2932                               "Get"))) {
2933                 log_error("Could not allocate message.");
2934                 return -ENOMEM;
2935         }
2936
2937         if (!dbus_message_append_args(m,
2938                                       DBUS_TYPE_STRING, &interface,
2939                                       DBUS_TYPE_STRING, &property,
2940                                       DBUS_TYPE_INVALID)) {
2941                 log_error("Could not append arguments to message.");
2942                 r = -ENOMEM;
2943                 goto finish;
2944         }
2945
2946         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2947                 log_error("Failed to issue method call: %s", error.message);
2948                 r = -EIO;
2949                 goto finish;
2950         }
2951
2952         if (!dbus_message_iter_init(reply, &iter) ||
2953             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
2954                 log_error("Failed to parse reply.");
2955                 r = -EIO;
2956                 goto finish;
2957         }
2958
2959         dbus_message_iter_recurse(&iter, &sub);
2960
2961         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
2962             dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING)  {
2963                 log_error("Failed to parse reply.");
2964                 r = -EIO;
2965                 goto finish;
2966         }
2967
2968         dbus_message_iter_recurse(&sub, &sub2);
2969
2970         while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
2971                 const char *text;
2972
2973                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
2974                         log_error("Failed to parse reply.");
2975                         r = -EIO;
2976                         goto finish;
2977                 }
2978
2979                 dbus_message_iter_get_basic(&sub2, &text);
2980                 printf("%s\n", text);
2981
2982                 dbus_message_iter_next(&sub2);
2983         }
2984
2985         r = 0;
2986
2987 finish:
2988         if (m)
2989                 dbus_message_unref(m);
2990
2991         if (reply)
2992                 dbus_message_unref(reply);
2993
2994         dbus_error_free(&error);
2995
2996         return r;
2997 }
2998
2999 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3000         DBusMessage *m = NULL, *reply = NULL;
3001         DBusError error;
3002         int r;
3003         const char *method;
3004         DBusMessageIter iter, sub;
3005         unsigned i;
3006
3007         dbus_error_init(&error);
3008
3009         method = streq(args[0], "set-environment")
3010                 ? "SetEnvironment"
3011                 : "UnsetEnvironment";
3012
3013         if (!(m = dbus_message_new_method_call(
3014                               "org.freedesktop.systemd1",
3015                               "/org/freedesktop/systemd1",
3016                               "org.freedesktop.systemd1.Manager",
3017                               method))) {
3018
3019                 log_error("Could not allocate message.");
3020                 return -ENOMEM;
3021         }
3022
3023         dbus_message_iter_init_append(m, &iter);
3024
3025         if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3026                 log_error("Could not append arguments to message.");
3027                 r = -ENOMEM;
3028                 goto finish;
3029         }
3030
3031         for (i = 1; i < n; i++)
3032                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3033                         log_error("Could not append arguments to message.");
3034                         r = -ENOMEM;
3035                         goto finish;
3036                 }
3037
3038         if (!dbus_message_iter_close_container(&iter, &sub)) {
3039                 log_error("Could not append arguments to message.");
3040                 r = -ENOMEM;
3041                 goto finish;
3042         }
3043
3044         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3045                 log_error("Failed to issue method call: %s", error.message);
3046                 r = -EIO;
3047                 goto finish;
3048         }
3049
3050         r = 0;
3051
3052 finish:
3053         if (m)
3054                 dbus_message_unref(m);
3055
3056         if (reply)
3057                 dbus_message_unref(reply);
3058
3059         dbus_error_free(&error);
3060
3061         return r;
3062 }
3063
3064 typedef struct {
3065         char *name;
3066         char *path;
3067
3068         char **aliases;
3069         char **wanted_by;
3070 } InstallInfo;
3071
3072 static Hashmap *will_install = NULL, *have_installed = NULL;
3073 static Set *remove_symlinks_to = NULL;
3074
3075 static void install_info_free(InstallInfo *i) {
3076         assert(i);
3077
3078         free(i->name);
3079         free(i->path);
3080         strv_free(i->aliases);
3081         strv_free(i->wanted_by);
3082         free(i);
3083 }
3084
3085 static void install_info_hashmap_free(Hashmap *m) {
3086         InstallInfo *i;
3087
3088         while ((i = hashmap_steal_first(m)))
3089                 install_info_free(i);
3090
3091         hashmap_free(m);
3092 }
3093
3094 static bool unit_name_valid(const char *name) {
3095
3096         /* This is a minimal version of unit_name_valid() from
3097          * unit-name.c */
3098
3099         if (!*name)
3100                 return false;
3101
3102         if (ignore_file(name))
3103                 return false;
3104
3105         return true;
3106 }
3107
3108 static int install_info_add(const char *name) {
3109         InstallInfo *i;
3110         int r;
3111
3112         assert(will_install);
3113
3114         if (!unit_name_valid(name))
3115                 return -EINVAL;
3116
3117         if (hashmap_get(have_installed, name) ||
3118             hashmap_get(will_install, name))
3119                 return 0;
3120
3121         if (!(i = new0(InstallInfo, 1))) {
3122                 r = -ENOMEM;
3123                 goto fail;
3124         }
3125
3126         if (!(i->name = strdup(name))) {
3127                 r = -ENOMEM;
3128                 goto fail;
3129         }
3130
3131         if ((r = hashmap_put(will_install, i->name, i)) < 0)
3132                 goto fail;
3133
3134         return 0;
3135
3136 fail:
3137         if (i)
3138                 install_info_free(i);
3139
3140         return r;
3141 }
3142
3143 static int config_parse_also(
3144                 const char *filename,
3145                 unsigned line,
3146                 const char *section,
3147                 const char *lvalue,
3148                 const char *rvalue,
3149                 void *data,
3150                 void *userdata) {
3151
3152         char *w;
3153         size_t l;
3154         char *state;
3155
3156         assert(filename);
3157         assert(lvalue);
3158         assert(rvalue);
3159
3160         FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3161                 char *n;
3162                 int r;
3163
3164                 if (!(n = strndup(w, l)))
3165                         return -ENOMEM;
3166
3167                 r = install_info_add(n);
3168                 free(n);
3169
3170                 if (r < 0)
3171                         return r;
3172         }
3173
3174         return 0;
3175 }
3176
3177 static int mark_symlink_for_removal(const char *p) {
3178         char *n;
3179         int r;
3180
3181         assert(p);
3182         assert(path_is_absolute(p));
3183
3184         if (!remove_symlinks_to)
3185                 return 0;
3186
3187         if (!(n = strdup(p)))
3188                 return -ENOMEM;
3189
3190         path_kill_slashes(n);
3191
3192         if ((r = set_put(remove_symlinks_to, n)) < 0) {
3193                 free(n);
3194                 return r == -EEXIST ? 0 : r;
3195         }
3196
3197         return 0;
3198 }
3199
3200 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3201         int r = 0;
3202         DIR *d;
3203         struct dirent *de;
3204
3205         assert(fd >= 0);
3206         assert(root);
3207         assert(deleted);
3208
3209         if (!(d = fdopendir(fd))) {
3210                 close_nointr_nofail(fd);
3211                 return -errno;
3212         }
3213
3214         rewinddir(d);
3215
3216         while ((de = readdir(d))) {
3217                 bool is_dir = false, is_link = false;
3218
3219                 if (ignore_file(de->d_name))
3220                         continue;
3221
3222                 if (de->d_type == DT_LNK)
3223                         is_link = true;
3224                 else if (de->d_type == DT_DIR)
3225                         is_dir = true;
3226                 else if (de->d_type == DT_UNKNOWN) {
3227                         struct stat st;
3228
3229                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3230                                 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3231
3232                                 if (r == 0)
3233                                         r = -errno;
3234                                 continue;
3235                         }
3236
3237                         is_link = S_ISLNK(st.st_mode);
3238                         is_dir = S_ISDIR(st.st_mode);
3239                 } else
3240                         continue;
3241
3242                 if (is_dir) {
3243                         int nfd, q;
3244                         char *p;
3245
3246                         if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3247                                 log_error("Failed to open %s/%s: %m", root, de->d_name);
3248
3249                                 if (r == 0)
3250                                         r = -errno;
3251                                 continue;
3252                         }
3253
3254                         if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3255                                 log_error("Failed to allocate directory string.");
3256                                 close_nointr_nofail(nfd);
3257                                 r = -ENOMEM;
3258                                 break;
3259                         }
3260
3261                         /* This will close nfd, regardless whether it succeeds or not */
3262                         q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3263                         free(p);
3264
3265                         if (r == 0)
3266                                 r = q;
3267
3268                 } else if (is_link) {
3269                         char *p, *dest, *c;
3270                         int q;
3271
3272                         if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3273                                 log_error("Failed to allocate symlink string.");
3274                                 r = -ENOMEM;
3275                                 break;
3276                         }
3277
3278                         if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3279                                 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3280                                 free(p);
3281
3282                                 if (r == 0)
3283                                         r = q;
3284                                 continue;
3285                         }
3286
3287                         if ((c = canonicalize_file_name(dest))) {
3288                                 /* This might fail if the destination
3289                                  * is already removed */
3290
3291                                 free(dest);
3292                                 dest = c;
3293                         }
3294
3295                         path_kill_slashes(dest);
3296                         if (set_get(remove_symlinks_to, dest)) {
3297
3298                                 if (!arg_quiet)
3299                                         log_info("rm '%s'", p);
3300
3301                                 if (unlink(p) < 0) {
3302                                         log_error("Cannot unlink symlink %s: %m", p);
3303
3304                                         if (r == 0)
3305                                                 r = -errno;
3306                                 } else {
3307                                         rmdir_parents(p, config_path);
3308                                         path_kill_slashes(p);
3309
3310                                         if (!set_get(remove_symlinks_to, p)) {
3311
3312                                                 if ((r = mark_symlink_for_removal(p)) < 0) {
3313                                                         if (r == 0)
3314                                                                 r = q;
3315                                                 } else
3316                                                         *deleted = true;
3317                                         }
3318                                 }
3319                         }
3320
3321                         free(p);
3322                         free(dest);
3323                 }
3324         }
3325
3326         closedir(d);
3327
3328         return r;
3329 }
3330
3331 static int remove_marked_symlinks(const char *config_path) {
3332         int fd, r = 0;
3333         bool deleted;
3334
3335         assert(config_path);
3336
3337         if (set_size(remove_symlinks_to) <= 0)
3338                 return 0;
3339
3340         if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3341                 return -errno;
3342
3343         do {
3344                 int q, cfd;
3345                 deleted = false;
3346
3347                 if ((cfd = dup(fd)) < 0) {
3348                         r = -errno;
3349                         break;
3350                 }
3351
3352                 /* This takes possession of cfd and closes it */
3353                 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3354                         if (r == 0)
3355                                 r = q;
3356                 }
3357         } while (deleted);
3358
3359         close_nointr_nofail(fd);
3360
3361         return r;
3362 }
3363
3364 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3365         int r;
3366
3367         assert(old_path);
3368         assert(new_path);
3369         assert(verb);
3370
3371         if (streq(verb, "enable")) {
3372                 char *dest;
3373
3374                 mkdir_parents(new_path, 0755);
3375
3376                 if (symlink(old_path, new_path) >= 0) {
3377
3378                         if (!arg_quiet)
3379                                 log_info("ln -s '%s' '%s'", old_path, new_path);
3380
3381                         return 0;
3382                 }
3383
3384                 if (errno != EEXIST) {
3385                         log_error("Cannot link %s to %s: %m", old_path, new_path);
3386                         return -errno;
3387                 }
3388
3389                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3390
3391                         if (errno == EINVAL) {
3392                                 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3393                                 return -EEXIST;
3394                         }
3395
3396                         log_error("readlink() failed: %s", strerror(-r));
3397                         return r;
3398                 }
3399
3400                 if (streq(dest, old_path)) {
3401                         free(dest);
3402                         return 0;
3403                 }
3404
3405                 if (!arg_force) {
3406                         log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3407                         free(dest);
3408                         return -EEXIST;
3409                 }
3410
3411                 free(dest);
3412                 unlink(new_path);
3413
3414                 if (!arg_quiet)
3415                         log_info("ln -s '%s' '%s'", old_path, new_path);
3416
3417                 if (symlink(old_path, new_path) >= 0)
3418                         return 0;
3419
3420                 log_error("Cannot link %s to %s: %m", old_path, new_path);
3421                 return -errno;
3422
3423         } else if (streq(verb, "disable")) {
3424                 char *dest;
3425
3426                 if ((r = mark_symlink_for_removal(old_path)) < 0)
3427                         return r;
3428
3429                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3430                         if (errno == ENOENT)
3431                                 return 0;
3432
3433                         if (errno == EINVAL) {
3434                                 log_warning("File %s not a symlink, ignoring.", old_path);
3435                                 return 0;
3436                         }
3437
3438                         log_error("readlink() failed: %s", strerror(-r));
3439                         return r;
3440                 }
3441
3442                 if (!streq(dest, old_path)) {
3443                         log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3444                         free(dest);
3445                         return 0;
3446                 }
3447
3448                 free(dest);
3449
3450                 if ((r = mark_symlink_for_removal(new_path)) < 0)
3451                         return r;
3452
3453                 if (!arg_quiet)
3454                         log_info("rm '%s'", new_path);
3455
3456                 if (unlink(new_path) >= 0)
3457                         return 0;
3458
3459                 log_error("Cannot unlink %s: %m", new_path);
3460                 return -errno;
3461
3462         } else if (streq(verb, "is-enabled")) {
3463                 char *dest;
3464
3465                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3466
3467                         if (errno == ENOENT || errno == EINVAL)
3468                                 return 0;
3469
3470                         log_error("readlink() failed: %s", strerror(-r));
3471                         return r;
3472                 }
3473
3474                 if (streq(dest, old_path)) {
3475                         free(dest);
3476                         return 1;
3477                 }
3478
3479                 return 0;
3480         }
3481
3482         assert_not_reached("Unknown action.");
3483 }
3484
3485 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3486         char **s;
3487         char *alias_path = NULL;
3488         int r;
3489
3490         assert(verb);
3491         assert(i);
3492         assert(config_path);
3493
3494         STRV_FOREACH(s, i->aliases) {
3495
3496                 if (!unit_name_valid(*s)) {
3497                         log_error("Invalid name %s.", *s);
3498                         r = -EINVAL;
3499                         goto finish;
3500                 }
3501
3502                 free(alias_path);
3503                 if (!(alias_path = path_make_absolute(*s, config_path))) {
3504                         log_error("Out of memory");
3505                         r = -ENOMEM;
3506                         goto finish;
3507                 }
3508
3509                 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3510                         goto finish;
3511
3512                 if (streq(verb, "disable"))
3513                         rmdir_parents(alias_path, config_path);
3514         }
3515
3516         r = 0;
3517
3518 finish:
3519         free(alias_path);
3520
3521         return r;
3522 }
3523
3524 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3525         char **s;
3526         char *alias_path = NULL;
3527         int r;
3528
3529         assert(verb);
3530         assert(i);
3531         assert(config_path);
3532
3533         STRV_FOREACH(s, i->wanted_by) {
3534                 if (!unit_name_valid(*s)) {
3535                         log_error("Invalid name %s.", *s);
3536                         r = -EINVAL;
3537                         goto finish;
3538                 }
3539
3540                 free(alias_path);
3541                 alias_path = NULL;
3542
3543                 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3544                         log_error("Out of memory");
3545                         r = -ENOMEM;
3546                         goto finish;
3547                 }
3548
3549                 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3550                         goto finish;
3551
3552                 if (streq(verb, "disable"))
3553                         rmdir_parents(alias_path, config_path);
3554         }
3555
3556         r = 0;
3557
3558 finish:
3559         free(alias_path);
3560
3561         return r;
3562 }
3563
3564 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3565
3566         const ConfigItem items[] = {
3567                 { "Alias",    config_parse_strv, &i->aliases,   "Install" },
3568                 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3569                 { "Also",     config_parse_also, NULL,          "Install" },
3570
3571                 { NULL, NULL, NULL, NULL }
3572         };
3573
3574         char **p;
3575         char *filename = NULL;
3576         FILE *f = NULL;
3577         int r;
3578
3579         assert(paths);
3580         assert(i);
3581
3582         STRV_FOREACH(p, paths->unit_path) {
3583                 int fd;
3584
3585                 if (!(filename = path_make_absolute(i->name, *p))) {
3586                         log_error("Out of memory");
3587                         return -ENOMEM;
3588                 }
3589
3590                 /* Ensure that we don't follow symlinks */
3591                 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3592                         if ((f = fdopen(fd, "re")))
3593                                 break;
3594
3595                 if (errno == ELOOP) {
3596                         log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3597                         free(filename);
3598                         return -errno;
3599                 }
3600
3601                 if (errno != ENOENT) {
3602                         log_error("Failed to open %s: %m", filename);
3603                         free(filename);
3604                         return -errno;
3605                 }
3606
3607                 free(filename);
3608                 filename = NULL;
3609         }
3610
3611         if (!f) {
3612                 log_error("Couldn't find %s.", i->name);
3613                 return -ENOENT;
3614         }
3615
3616         i->path = filename;
3617
3618         if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3619                 fclose(f);
3620                 return r;
3621         }
3622
3623         fclose(f);
3624
3625         if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3626                 return r;
3627
3628         if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3629                 return r;
3630
3631         if ((r = mark_symlink_for_removal(filename)) < 0)
3632                 return r;
3633
3634         if ((r = remove_marked_symlinks(config_path)) < 0)
3635                 return r;
3636
3637         return 0;
3638 }
3639
3640 static char *get_config_path(void) {
3641
3642         if (arg_session && arg_global)
3643                 return strdup(SESSION_CONFIG_UNIT_PATH);
3644
3645         if (arg_session) {
3646                 char *p;
3647
3648                 if (session_config_home(&p) < 0)
3649                         return NULL;
3650
3651                 return p;
3652         }
3653
3654         return strdup(SYSTEM_CONFIG_UNIT_PATH);
3655 }
3656
3657 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3658         DBusError error;
3659         int r;
3660         LookupPaths paths;
3661         char *config_path = NULL;
3662         unsigned j;
3663         InstallInfo *i;
3664         const char *verb = args[0];
3665
3666         dbus_error_init(&error);
3667
3668         zero(paths);
3669         if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3670                 log_error("Failed to determine lookup paths: %s", strerror(-r));
3671                 goto finish;
3672         }
3673
3674         if (!(config_path = get_config_path())) {
3675                 log_error("Failed to determine config path");
3676                 r = -ENOMEM;
3677                 goto finish;
3678         }
3679
3680         will_install = hashmap_new(string_hash_func, string_compare_func);
3681         have_installed = hashmap_new(string_hash_func, string_compare_func);
3682
3683         if (!will_install || !have_installed) {
3684                 log_error("Failed to allocate unit sets.");
3685                 r = -ENOMEM;
3686                 goto finish;
3687         }
3688
3689         if (!arg_defaults && streq(verb, "disable"))
3690                 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3691                         log_error("Failed to allocate symlink sets.");
3692                         r = -ENOMEM;
3693                         goto finish;
3694                 }
3695
3696         for (j = 1; j < n; j++)
3697                 if ((r = install_info_add(args[j])) < 0)
3698                         goto finish;
3699
3700         while ((i = hashmap_first(will_install))) {
3701                 int q;
3702
3703                 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3704
3705                 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3706
3707                         if (q < 0) {
3708                                 if (r == 0)
3709                                         r = q;
3710                                 goto finish;
3711                         }
3712
3713                         /* In test mode and found something */
3714                         r = 1;
3715                         break;
3716                 }
3717         }
3718
3719         if (streq(verb, "is-enabled"))
3720                 r = r > 0 ? 0 : -ENOENT;
3721         else if (bus &&
3722                  /* Don't try to reload anything if the user asked us to not do this */
3723                  !arg_no_reload &&
3724                  /* Don't try to reload anything when updating a unit globally */
3725                  !arg_global &&
3726                  /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3727                  (arg_session || sd_booted() > 0) &&
3728                  /* Don't try to reload anything if we are running in a chroot environment */
3729                  (arg_session || running_in_chroot() <= 0) ) {
3730                 int q;
3731
3732                 if ((q = daemon_reload(bus, args, n)) < 0)
3733                         r = q;
3734         }
3735
3736 finish:
3737         install_info_hashmap_free(will_install);
3738         install_info_hashmap_free(have_installed);
3739
3740         set_free_free(remove_symlinks_to);
3741
3742         lookup_paths_free(&paths);
3743
3744         free(config_path);
3745
3746         return r;
3747 }
3748
3749 static int systemctl_help(void) {
3750
3751         printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3752                "Send control commands to or query the systemd manager.\n\n"
3753                "  -h --help          Show this help\n"
3754                "  -t --type=TYPE     List only units of a particular type\n"
3755                "  -p --property=NAME Show only properties by this name\n"
3756                "  -a --all           Show all units/properties, including dead/empty ones\n"
3757                "     --full          Don't ellipsize unit names on output\n"
3758                "     --fail          When queueing a new job, fail if conflicting jobs are\n"
3759                "                     pending\n"
3760                "  -q --quiet         Suppress output\n"
3761                "     --no-block      Do not wait until operation finished\n"
3762                "     --system        Connect to system bus\n"
3763                "     --session       Connect to session bus\n"
3764                "     --order         When generating graph for dot, show only order\n"
3765                "     --require       When generating graph for dot, show only requirement\n"
3766                "     --no-wall       Don't send wall message before halt/power-off/reboot\n"
3767                "     --global        Enable/disable unit files globally\n"
3768                "     --no-reload     When enabling/disabling unit files, don't reload daemon\n"
3769                "                     configuration\n"
3770                "     --force         When enabling unit files, override existing symlinks\n"
3771                "     --defaults      When disabling unit files, remove default symlinks only\n\n"
3772                "Commands:\n"
3773                "  list-units                      List units\n"
3774                "  start [NAME...]                 Start (activate) one or more units\n"
3775                "  stop [NAME...]                  Stop (deactivate) one or more units\n"
3776                "  reload [NAME...]                Reload one or more units\n"
3777                "  restart [NAME...]               Start or restart one or more units\n"
3778                "  try-restart [NAME...]           Restart one or more units if active\n"
3779                "  reload-or-restart [NAME...]     Reload one or more units is possible,\n"
3780                "                                  otherwise start or restart\n"
3781                "  reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3782                "                                  otherwise restart if active\n"
3783                "  isolate [NAME]                  Start one unit and stop all others\n"
3784                "  is-active [NAME...]             Check whether units are active\n"
3785                "  status [NAME...|PID...]         Show runtime status of one or more units\n"
3786                "  show [NAME...|JOB...]           Show properties of one or more\n"
3787                "                                  units/jobs or the manager\n"
3788                "  reset-maintenance [NAME...]     Reset maintenance state for all, one,\n"
3789                "                                  or more units\n"
3790                "  enable [NAME...]                Enable one or more unit files\n"
3791                "  disable [NAME...]               Disable one or more unit files\n"
3792                "  is-enabled [NAME...]            Check whether unit files are enabled\n"
3793                "  load [NAME...]                  Load one or more units\n"
3794                "  list-jobs                       List jobs\n"
3795                "  cancel [JOB...]                 Cancel all, one, or more jobs\n"
3796                "  monitor                         Monitor unit/job changes\n"
3797                "  dump                            Dump server status\n"
3798                "  dot                             Dump dependency graph for dot(1)\n"
3799                "  snapshot [NAME]                 Create a snapshot\n"
3800                "  delete [NAME...]                Remove one or more snapshots\n"
3801                "  daemon-reload                   Reload systemd manager configuration\n"
3802                "  daemon-reexec                   Reexecute systemd manager\n"
3803                "  daemon-exit                     Ask the systemd manager to quit\n"
3804                "  show-environment                Dump environment\n"
3805                "  set-environment [NAME=VALUE...] Set one or more environment variables\n"
3806                "  unset-environment [NAME...]     Unset one or more environment variables\n"
3807                "  halt                            Shut down and halt the system\n"
3808                "  poweroff                        Shut down and power-off the system\n"
3809                "  reboot                          Shut down and reboot the system\n"
3810                "  rescue                          Enter system rescue mode\n"
3811                "  emergency                       Enter system emergency mode\n"
3812                "  default                         Enter system default mode\n",
3813                program_invocation_short_name);
3814
3815         return 0;
3816 }
3817
3818 static int halt_help(void) {
3819
3820         printf("%s [OPTIONS...]\n\n"
3821                "%s the system.\n\n"
3822                "     --help      Show this help\n"
3823                "     --halt      Halt the machine\n"
3824                "  -p --poweroff  Switch off the machine\n"
3825                "     --reboot    Reboot the machine\n"
3826                "  -f --force     Force immediate halt/power-off/reboot\n"
3827                "  -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3828                "  -d --no-wtmp   Don't write wtmp record\n"
3829                "  -n --no-sync   Don't sync before halt/power-off/reboot\n"
3830                "     --no-wall   Don't send wall message before halt/power-off/reboot\n",
3831                program_invocation_short_name,
3832                arg_action == ACTION_REBOOT   ? "Reboot" :
3833                arg_action == ACTION_POWEROFF ? "Power off" :
3834                                                "Halt");
3835
3836         return 0;
3837 }
3838
3839 static int shutdown_help(void) {
3840
3841         printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3842                "Shut down the system.\n\n"
3843                "     --help      Show this help\n"
3844                "  -H --halt      Halt the machine\n"
3845                "  -P --poweroff  Power-off the machine\n"
3846                "  -r --reboot    Reboot the machine\n"
3847                "  -h             Equivalent to --poweroff, overriden by --halt\n"
3848                "  -k             Don't halt/power-off/reboot, just send warnings\n"
3849                "     --no-wall   Don't send wall message before halt/power-off/reboot\n"
3850                "  -c             Cancel a pending shutdown\n",
3851                program_invocation_short_name);
3852
3853         return 0;
3854 }
3855
3856 static int telinit_help(void) {
3857
3858         printf("%s [OPTIONS...] {COMMAND}\n\n"
3859                "Send control commands to the init daemon.\n\n"
3860                "     --help      Show this help\n"
3861                "     --no-wall   Don't send wall message before halt/power-off/reboot\n\n"
3862                "Commands:\n"
3863                "  0              Power-off the machine\n"
3864                "  6              Reboot the machine\n"
3865                "  2, 3, 4, 5     Start runlevelX.target unit\n"
3866                "  1, s, S        Enter rescue mode\n"
3867                "  q, Q           Reload init daemon configuration\n"
3868                "  u, U           Reexecute init daemon\n",
3869                program_invocation_short_name);
3870
3871         return 0;
3872 }
3873
3874 static int runlevel_help(void) {
3875
3876         printf("%s [OPTIONS...]\n\n"
3877                "Prints the previous and current runlevel of the init system.\n\n"
3878                "     --help      Show this help\n",
3879                program_invocation_short_name);
3880
3881         return 0;
3882 }
3883
3884 static int systemctl_parse_argv(int argc, char *argv[]) {
3885
3886         enum {
3887                 ARG_FAIL = 0x100,
3888                 ARG_SESSION,
3889                 ARG_SYSTEM,
3890                 ARG_GLOBAL,
3891                 ARG_NO_BLOCK,
3892                 ARG_NO_WALL,
3893                 ARG_ORDER,
3894                 ARG_REQUIRE,
3895                 ARG_FULL,
3896                 ARG_FORCE,
3897                 ARG_NO_RELOAD,
3898                 ARG_DEFAULTS
3899         };
3900
3901         static const struct option options[] = {
3902                 { "help",      no_argument,       NULL, 'h'           },
3903                 { "type",      required_argument, NULL, 't'           },
3904                 { "property",  required_argument, NULL, 'p'           },
3905                 { "all",       no_argument,       NULL, 'a'           },
3906                 { "full",      no_argument,       NULL, ARG_FULL      },
3907                 { "fail",      no_argument,       NULL, ARG_FAIL      },
3908                 { "session",   no_argument,       NULL, ARG_SESSION   },
3909                 { "system",    no_argument,       NULL, ARG_SYSTEM    },
3910                 { "global",    no_argument,       NULL, ARG_GLOBAL    },
3911                 { "no-block",  no_argument,       NULL, ARG_NO_BLOCK  },
3912                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL   },
3913                 { "quiet",     no_argument,       NULL, 'q'           },
3914                 { "order",     no_argument,       NULL, ARG_ORDER     },
3915                 { "require",   no_argument,       NULL, ARG_REQUIRE   },
3916                 { "force",     no_argument,       NULL, ARG_FORCE     },
3917                 { "no-reload", no_argument,       NULL, ARG_NO_RELOAD },
3918                 { "defaults",   no_argument,      NULL, ARG_DEFAULTS  },
3919                 { NULL,        0,                 NULL, 0             }
3920         };
3921
3922         int c;
3923
3924         assert(argc >= 0);
3925         assert(argv);
3926
3927         while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
3928
3929                 switch (c) {
3930
3931                 case 'h':
3932                         systemctl_help();
3933                         return 0;
3934
3935                 case 't':
3936                         arg_type = optarg;
3937                         break;
3938
3939                 case 'p': {
3940                         char **l;
3941
3942                         if (!(l = strv_append(arg_property, optarg)))
3943                                 return -ENOMEM;
3944
3945                         strv_free(arg_property);
3946                         arg_property = l;
3947
3948                         /* If the user asked for a particular
3949                          * property, show it to him, even if it is
3950                          * empty. */
3951                         arg_all = true;
3952                         break;
3953                 }
3954
3955                 case 'a':
3956                         arg_all = true;
3957                         break;
3958
3959                 case ARG_FAIL:
3960                         arg_fail = true;
3961                         break;
3962
3963                 case ARG_SESSION:
3964                         arg_session = true;
3965                         break;
3966
3967                 case ARG_SYSTEM:
3968                         arg_session = false;
3969                         break;
3970
3971                 case ARG_NO_BLOCK:
3972                         arg_no_block = true;
3973                         break;
3974
3975                 case ARG_NO_WALL:
3976                         arg_no_wall = true;
3977                         break;
3978
3979                 case ARG_ORDER:
3980                         arg_dot = DOT_ORDER;
3981                         break;
3982
3983                 case ARG_REQUIRE:
3984                         arg_dot = DOT_REQUIRE;
3985                         break;
3986
3987                 case ARG_FULL:
3988                         arg_full = true;
3989                         break;
3990
3991                 case 'q':
3992                         arg_quiet = true;
3993                         break;
3994
3995                 case ARG_FORCE:
3996                         arg_force = true;
3997                         break;
3998
3999                 case ARG_NO_RELOAD:
4000                         arg_no_reload = true;
4001                         break;
4002
4003                 case ARG_GLOBAL:
4004                         arg_global = true;
4005                         arg_session = true;
4006                         break;
4007
4008                 case ARG_DEFAULTS:
4009                         arg_defaults = true;
4010                         break;
4011
4012                 case '?':
4013                         return -EINVAL;
4014
4015                 default:
4016                         log_error("Unknown option code %c", c);
4017                         return -EINVAL;
4018                 }
4019         }
4020
4021         return 1;
4022 }
4023
4024 static int halt_parse_argv(int argc, char *argv[]) {
4025
4026         enum {
4027                 ARG_HELP = 0x100,
4028                 ARG_HALT,
4029                 ARG_REBOOT,
4030                 ARG_NO_WALL
4031         };
4032
4033         static const struct option options[] = {
4034                 { "help",      no_argument,       NULL, ARG_HELP    },
4035                 { "halt",      no_argument,       NULL, ARG_HALT    },
4036                 { "poweroff",  no_argument,       NULL, 'p'         },
4037                 { "reboot",    no_argument,       NULL, ARG_REBOOT  },
4038                 { "force",     no_argument,       NULL, 'f'         },
4039                 { "wtmp-only", no_argument,       NULL, 'w'         },
4040                 { "no-wtmp",   no_argument,       NULL, 'd'         },
4041                 { "no-sync",   no_argument,       NULL, 'n'         },
4042                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4043                 { NULL,        0,                 NULL, 0           }
4044         };
4045
4046         int c, runlevel;
4047
4048         assert(argc >= 0);
4049         assert(argv);
4050
4051         if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4052                 if (runlevel == '0' || runlevel == '6')
4053                         arg_immediate = true;
4054
4055         while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4056                 switch (c) {
4057
4058                 case ARG_HELP:
4059                         halt_help();
4060                         return 0;
4061
4062                 case ARG_HALT:
4063                         arg_action = ACTION_HALT;
4064                         break;
4065
4066                 case 'p':
4067                         if (arg_action != ACTION_REBOOT)
4068                                 arg_action = ACTION_POWEROFF;
4069                         break;
4070
4071                 case ARG_REBOOT:
4072                         arg_action = ACTION_REBOOT;
4073                         break;
4074
4075                 case 'f':
4076                         arg_immediate = true;
4077                         break;
4078
4079                 case 'w':
4080                         arg_dry = true;
4081                         break;
4082
4083                 case 'd':
4084                         arg_no_wtmp = true;
4085                         break;
4086
4087                 case 'n':
4088                         arg_no_sync = true;
4089                         break;
4090
4091                 case ARG_NO_WALL:
4092                         arg_no_wall = true;
4093                         break;
4094
4095                 case 'i':
4096                 case 'h':
4097                         /* Compatibility nops */
4098                         break;
4099
4100                 case '?':
4101                         return -EINVAL;
4102
4103                 default:
4104                         log_error("Unknown option code %c", c);
4105                         return -EINVAL;
4106                 }
4107         }
4108
4109         if (optind < argc) {
4110                 log_error("Too many arguments.");
4111                 return -EINVAL;
4112         }
4113
4114         return 1;
4115 }
4116
4117 static int parse_time_spec(const char *t, usec_t *_u) {
4118         assert(t);
4119         assert(_u);
4120
4121         if (streq(t, "now"))
4122                 *_u = 0;
4123         else if (t[0] == '+') {
4124                 uint64_t u;
4125
4126                 if (safe_atou64(t + 1, &u) < 0)
4127                         return -EINVAL;
4128
4129                 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4130         } else {
4131                 char *e = NULL;
4132                 long hour, minute;
4133                 struct tm tm;
4134                 time_t s;
4135                 usec_t n;
4136
4137                 errno = 0;
4138                 hour = strtol(t, &e, 10);
4139                 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4140                         return -EINVAL;
4141
4142                 minute = strtol(e+1, &e, 10);
4143                 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4144                         return -EINVAL;
4145
4146                 n = now(CLOCK_REALTIME);
4147                 s = (time_t) (n / USEC_PER_SEC);
4148
4149                 zero(tm);
4150                 assert_se(localtime_r(&s, &tm));
4151
4152                 tm.tm_hour = (int) hour;
4153                 tm.tm_min = (int) minute;
4154                 tm.tm_sec = 0;
4155
4156                 assert_se(s = mktime(&tm));
4157
4158                 *_u = (usec_t) s * USEC_PER_SEC;
4159
4160                 while (*_u <= n)
4161                         *_u += USEC_PER_DAY;
4162         }
4163
4164         return 0;
4165 }
4166
4167 static int shutdown_parse_argv(int argc, char *argv[]) {
4168
4169         enum {
4170                 ARG_HELP = 0x100,
4171                 ARG_NO_WALL
4172         };
4173
4174         static const struct option options[] = {
4175                 { "help",      no_argument,       NULL, ARG_HELP    },
4176                 { "halt",      no_argument,       NULL, 'H'         },
4177                 { "poweroff",  no_argument,       NULL, 'P'         },
4178                 { "reboot",    no_argument,       NULL, 'r'         },
4179                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4180                 { NULL,        0,                 NULL, 0           }
4181         };
4182
4183         int c, r;
4184
4185         assert(argc >= 0);
4186         assert(argv);
4187
4188         while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4189                 switch (c) {
4190
4191                 case ARG_HELP:
4192                         shutdown_help();
4193                         return 0;
4194
4195                 case 'H':
4196                         arg_action = ACTION_HALT;
4197                         break;
4198
4199                 case 'P':
4200                         arg_action = ACTION_POWEROFF;
4201                         break;
4202
4203                 case 'r':
4204                         arg_action = ACTION_REBOOT;
4205                         break;
4206
4207                 case 'h':
4208                         if (arg_action != ACTION_HALT)
4209                                 arg_action = ACTION_POWEROFF;
4210                         break;
4211
4212                 case 'k':
4213                         arg_dry = true;
4214                         break;
4215
4216                 case ARG_NO_WALL:
4217                         arg_no_wall = true;
4218                         break;
4219
4220                 case 't':
4221                 case 'a':
4222                         /* Compatibility nops */
4223                         break;
4224
4225                 case 'c':
4226                         arg_action = ACTION_CANCEL_SHUTDOWN;
4227                         break;
4228
4229                 case '?':
4230                         return -EINVAL;
4231
4232                 default:
4233                         log_error("Unknown option code %c", c);
4234                         return -EINVAL;
4235                 }
4236         }
4237
4238         if (argc > optind) {
4239                 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4240                         log_error("Failed to parse time specification: %s", argv[optind]);
4241                         return r;
4242                 }
4243         } else
4244                 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4245
4246         /* We skip the time argument */
4247         if (argc > optind + 1)
4248                 arg_wall = argv + optind + 1;
4249
4250         optind = argc;
4251
4252         return 1;
4253 }
4254
4255 static int telinit_parse_argv(int argc, char *argv[]) {
4256
4257         enum {
4258                 ARG_HELP = 0x100,
4259                 ARG_NO_WALL
4260         };
4261
4262         static const struct option options[] = {
4263                 { "help",      no_argument,       NULL, ARG_HELP    },
4264                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4265                 { NULL,        0,                 NULL, 0           }
4266         };
4267
4268         static const struct {
4269                 char from;
4270                 enum action to;
4271         } table[] = {
4272                 { '0', ACTION_POWEROFF },
4273                 { '6', ACTION_REBOOT },
4274                 { '1', ACTION_RESCUE },
4275                 { '2', ACTION_RUNLEVEL2 },
4276                 { '3', ACTION_RUNLEVEL3 },
4277                 { '4', ACTION_RUNLEVEL4 },
4278                 { '5', ACTION_RUNLEVEL5 },
4279                 { 's', ACTION_RESCUE },
4280                 { 'S', ACTION_RESCUE },
4281                 { 'q', ACTION_RELOAD },
4282                 { 'Q', ACTION_RELOAD },
4283                 { 'u', ACTION_REEXEC },
4284                 { 'U', ACTION_REEXEC }
4285         };
4286
4287         unsigned i;
4288         int c;
4289
4290         assert(argc >= 0);
4291         assert(argv);
4292
4293         while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4294                 switch (c) {
4295
4296                 case ARG_HELP:
4297                         telinit_help();
4298                         return 0;
4299
4300                 case ARG_NO_WALL:
4301                         arg_no_wall = true;
4302                         break;
4303
4304                 case '?':
4305                         return -EINVAL;
4306
4307                 default:
4308                         log_error("Unknown option code %c", c);
4309                         return -EINVAL;
4310                 }
4311         }
4312
4313         if (optind >= argc) {
4314                 telinit_help();
4315                 return -EINVAL;
4316         }
4317
4318         if (optind + 1 < argc) {
4319                 log_error("Too many arguments.");
4320                 return -EINVAL;
4321         }
4322
4323         if (strlen(argv[optind]) != 1) {
4324                 log_error("Expected single character argument.");
4325                 return -EINVAL;
4326         }
4327
4328         for (i = 0; i < ELEMENTSOF(table); i++)
4329                 if (table[i].from == argv[optind][0])
4330                         break;
4331
4332         if (i >= ELEMENTSOF(table)) {
4333                 log_error("Unknown command %s.", argv[optind]);
4334                 return -EINVAL;
4335         }
4336
4337         arg_action = table[i].to;
4338
4339         optind ++;
4340
4341         return 1;
4342 }
4343
4344 static int runlevel_parse_argv(int argc, char *argv[]) {
4345
4346         enum {
4347                 ARG_HELP = 0x100,
4348         };
4349
4350         static const struct option options[] = {
4351                 { "help",      no_argument,       NULL, ARG_HELP    },
4352                 { NULL,        0,                 NULL, 0           }
4353         };
4354
4355         int c;
4356
4357         assert(argc >= 0);
4358         assert(argv);
4359
4360         while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4361                 switch (c) {
4362
4363                 case ARG_HELP:
4364                         runlevel_help();
4365                         return 0;
4366
4367                 case '?':
4368                         return -EINVAL;
4369
4370                 default:
4371                         log_error("Unknown option code %c", c);
4372                         return -EINVAL;
4373                 }
4374         }
4375
4376         if (optind < argc) {
4377                 log_error("Too many arguments.");
4378                 return -EINVAL;
4379         }
4380
4381         return 1;
4382 }
4383
4384 static int parse_argv(int argc, char *argv[]) {
4385         assert(argc >= 0);
4386         assert(argv);
4387
4388         if (program_invocation_short_name) {
4389
4390                 if (strstr(program_invocation_short_name, "halt")) {
4391                         arg_action = ACTION_HALT;
4392                         return halt_parse_argv(argc, argv);
4393                 } else if (strstr(program_invocation_short_name, "poweroff")) {
4394                         arg_action = ACTION_POWEROFF;
4395                         return halt_parse_argv(argc, argv);
4396                 } else if (strstr(program_invocation_short_name, "reboot")) {
4397                         arg_action = ACTION_REBOOT;
4398                         return halt_parse_argv(argc, argv);
4399                 } else if (strstr(program_invocation_short_name, "shutdown")) {
4400                         arg_action = ACTION_POWEROFF;
4401                         return shutdown_parse_argv(argc, argv);
4402                 } else if (strstr(program_invocation_short_name, "init")) {
4403
4404                         if (sd_booted() > 0) {
4405                                 arg_action = ACTION_INVALID;
4406                                 return telinit_parse_argv(argc, argv);
4407                         } else {
4408                                 /* Hmm, so some other init system is
4409                                  * running, we need to forward this
4410                                  * request to it. For now we simply
4411                                  * guess that it is Upstart. */
4412
4413                                 execv("/lib/upstart/telinit", argv);
4414
4415                                 log_error("Couldn't find an alternative telinit implementation to spawn.");
4416                                 return -EIO;
4417                         }
4418
4419                 } else if (strstr(program_invocation_short_name, "runlevel")) {
4420                         arg_action = ACTION_RUNLEVEL;
4421                         return runlevel_parse_argv(argc, argv);
4422                 }
4423         }
4424
4425         arg_action = ACTION_SYSTEMCTL;
4426         return systemctl_parse_argv(argc, argv);
4427 }
4428
4429 static int action_to_runlevel(void) {
4430
4431         static const char table[_ACTION_MAX] = {
4432                 [ACTION_HALT] =      '0',
4433                 [ACTION_POWEROFF] =  '0',
4434                 [ACTION_REBOOT] =    '6',
4435                 [ACTION_RUNLEVEL2] = '2',
4436                 [ACTION_RUNLEVEL3] = '3',
4437                 [ACTION_RUNLEVEL4] = '4',
4438                 [ACTION_RUNLEVEL5] = '5',
4439                 [ACTION_RESCUE] =    '1'
4440         };
4441
4442         assert(arg_action < _ACTION_MAX);
4443
4444         return table[arg_action];
4445 }
4446
4447 static int talk_upstart(void) {
4448         DBusMessage *m = NULL, *reply = NULL;
4449         DBusError error;
4450         int previous, rl, r;
4451         char
4452                 env1_buf[] = "RUNLEVEL=X",
4453                 env2_buf[] = "PREVLEVEL=X";
4454         char *env1 = env1_buf, *env2 = env2_buf;
4455         const char *emit = "runlevel";
4456         dbus_bool_t b_false = FALSE;
4457         DBusMessageIter iter, sub;
4458         DBusConnection *bus;
4459
4460         dbus_error_init(&error);
4461
4462         if (!(rl = action_to_runlevel()))
4463                 return 0;
4464
4465         if (utmp_get_runlevel(&previous, NULL) < 0)
4466                 previous = 'N';
4467
4468         if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4469                 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4470                         r = 0;
4471                         goto finish;
4472                 }
4473
4474                 log_error("Failed to connect to Upstart bus: %s", error.message);
4475                 r = -EIO;
4476                 goto finish;
4477         }
4478
4479         if ((r = bus_check_peercred(bus)) < 0) {
4480                 log_error("Failed to verify owner of bus.");
4481                 goto finish;
4482         }
4483
4484         if (!(m = dbus_message_new_method_call(
4485                               "com.ubuntu.Upstart",
4486                               "/com/ubuntu/Upstart",
4487                               "com.ubuntu.Upstart0_6",
4488                               "EmitEvent"))) {
4489
4490                 log_error("Could not allocate message.");
4491                 r = -ENOMEM;
4492                 goto finish;
4493         }
4494
4495         dbus_message_iter_init_append(m, &iter);
4496
4497         env1_buf[sizeof(env1_buf)-2] = rl;
4498         env2_buf[sizeof(env2_buf)-2] = previous;
4499
4500         if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4501             !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4502             !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4503             !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4504             !dbus_message_iter_close_container(&iter, &sub) ||
4505             !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4506                 log_error("Could not append arguments to message.");
4507                 r = -ENOMEM;
4508                 goto finish;
4509         }
4510
4511         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4512
4513                 if (error_is_no_service(&error)) {
4514                         r = 0;
4515                         goto finish;
4516                 }
4517
4518                 log_error("Failed to issue method call: %s", error.message);
4519                 r = -EIO;
4520                 goto finish;
4521         }
4522
4523         r = 1;
4524
4525 finish:
4526         if (m)
4527                 dbus_message_unref(m);
4528
4529         if (reply)
4530                 dbus_message_unref(reply);
4531
4532         if (bus) {
4533                 dbus_connection_close(bus);
4534                 dbus_connection_unref(bus);
4535         }
4536
4537         dbus_error_free(&error);
4538
4539         return r;
4540 }
4541
4542 static int talk_initctl(void) {
4543         struct init_request request;
4544         int r, fd;
4545         char rl;
4546
4547         if (!(rl = action_to_runlevel()))
4548                 return 0;
4549
4550         zero(request);
4551         request.magic = INIT_MAGIC;
4552         request.sleeptime = 0;
4553         request.cmd = INIT_CMD_RUNLVL;
4554         request.runlevel = rl;
4555
4556         if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4557
4558                 if (errno == ENOENT)
4559                         return 0;
4560
4561                 log_error("Failed to open "INIT_FIFO": %m");
4562                 return -errno;
4563         }
4564
4565         errno = 0;
4566         r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4567         close_nointr_nofail(fd);
4568
4569         if (r < 0) {
4570                 log_error("Failed to write to "INIT_FIFO": %m");
4571                 return errno ? -errno : -EIO;
4572         }
4573
4574         return 1;
4575 }
4576
4577 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4578
4579         static const struct {
4580                 const char* verb;
4581                 const enum {
4582                         MORE,
4583                         LESS,
4584                         EQUAL
4585                 } argc_cmp;
4586                 const int argc;
4587                 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4588         } verbs[] = {
4589                 { "list-units",            LESS,  1, list_units        },
4590                 { "list-jobs",             EQUAL, 1, list_jobs         },
4591                 { "clear-jobs",            EQUAL, 1, daemon_reload     },
4592                 { "load",                  MORE,  2, load_unit         },
4593                 { "cancel",                MORE,  2, cancel_job        },
4594                 { "start",                 MORE,  2, start_unit        },
4595                 { "stop",                  MORE,  2, start_unit        },
4596                 { "reload",                MORE,  2, start_unit        },
4597                 { "restart",               MORE,  2, start_unit        },
4598                 { "try-restart",           MORE,  2, start_unit        },
4599                 { "reload-or-restart",     MORE,  2, start_unit        },
4600                 { "reload-or-try-restart", MORE,  2, start_unit        },
4601                 { "force-reload",          MORE,  2, start_unit        }, /* For compatibility with SysV */
4602                 { "condrestart",           MORE,  2, start_unit        }, /* For compatibility with RH */
4603                 { "isolate",               EQUAL, 2, start_unit        },
4604                 { "is-active",             MORE,  2, check_unit        },
4605                 { "check",                 MORE,  2, check_unit        },
4606                 { "show",                  MORE,  1, show              },
4607                 { "status",                MORE,  2, show              },
4608                 { "monitor",               EQUAL, 1, monitor           },
4609                 { "dump",                  EQUAL, 1, dump              },
4610                 { "dot",                   EQUAL, 1, dot               },
4611                 { "snapshot",              LESS,  2, snapshot          },
4612                 { "delete",                MORE,  2, delete_snapshot   },
4613                 { "daemon-reload",         EQUAL, 1, daemon_reload     },
4614                 { "daemon-reexec",         EQUAL, 1, daemon_reload     },
4615                 { "daemon-exit",           EQUAL, 1, daemon_reload     },
4616                 { "show-environment",      EQUAL, 1, show_enviroment   },
4617                 { "set-environment",       MORE,  2, set_environment   },
4618                 { "unset-environment",     MORE,  2, set_environment   },
4619                 { "halt",                  EQUAL, 1, start_special     },
4620                 { "poweroff",              EQUAL, 1, start_special     },
4621                 { "reboot",                EQUAL, 1, start_special     },
4622                 { "default",               EQUAL, 1, start_special     },
4623                 { "rescue",                EQUAL, 1, start_special     },
4624                 { "emergency",             EQUAL, 1, start_special     },
4625                 { "reset-maintenance",     MORE,  1, reset_maintenance },
4626                 { "enable",                MORE,  2, enable_unit       },
4627                 { "disable",               MORE,  2, enable_unit       },
4628                 { "is-enabled",            MORE,  2, enable_unit       }
4629         };
4630
4631         int left;
4632         unsigned i;
4633
4634         assert(argc >= 0);
4635         assert(argv);
4636         assert(error);
4637
4638         left = argc - optind;
4639
4640         if (left <= 0)
4641                 /* Special rule: no arguments means "list-units" */
4642                 i = 0;
4643         else {
4644                 if (streq(argv[optind], "help")) {
4645                         systemctl_help();
4646                         return 0;
4647                 }
4648
4649                 for (i = 0; i < ELEMENTSOF(verbs); i++)
4650                         if (streq(argv[optind], verbs[i].verb))
4651                                 break;
4652
4653                 if (i >= ELEMENTSOF(verbs)) {
4654                         log_error("Unknown operation %s", argv[optind]);
4655                         return -EINVAL;
4656                 }
4657         }
4658
4659         switch (verbs[i].argc_cmp) {
4660
4661         case EQUAL:
4662                 if (left != verbs[i].argc) {
4663                         log_error("Invalid number of arguments.");
4664                         return -EINVAL;
4665                 }
4666
4667                 break;
4668
4669         case MORE:
4670                 if (left < verbs[i].argc) {
4671                         log_error("Too few arguments.");
4672                         return -EINVAL;
4673                 }
4674
4675                 break;
4676
4677         case LESS:
4678                 if (left > verbs[i].argc) {
4679                         log_error("Too many arguments.");
4680                         return -EINVAL;
4681                 }
4682
4683                 break;
4684
4685         default:
4686                 assert_not_reached("Unknown comparison operator.");
4687         }
4688
4689         /* Require a bus connection for all operations but
4690          * enable/disable */
4691         if (!streq(verbs[i].verb, "enable") &&
4692             !streq(verbs[i].verb, "disable") &&
4693             !bus) {
4694                 log_error("Failed to get D-Bus connection: %s", error->message);
4695                 return -EIO;
4696         }
4697
4698         return verbs[i].dispatch(bus, argv + optind, left);
4699 }
4700
4701 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
4702         int fd = -1;
4703         struct msghdr msghdr;
4704         struct iovec iovec;
4705         union sockaddr_union sockaddr;
4706         struct ucred *ucred;
4707         union {
4708                 struct cmsghdr cmsghdr;
4709                 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
4710         } control;
4711         struct shutdownd_command c;
4712
4713         zero(c);
4714         c.elapse = t;
4715         c.mode = mode;
4716         c.warn_wall = warn;
4717
4718         if (message)
4719                 strncpy(c.wall_message, message, sizeof(c.wall_message));
4720
4721         if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4722                 return -errno;
4723
4724         zero(sockaddr);
4725         sockaddr.sa.sa_family = AF_UNIX;
4726         sockaddr.un.sun_path[0] = 0;
4727         strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
4728
4729         zero(iovec);
4730         iovec.iov_base = (char*) &c;
4731         iovec.iov_len = sizeof(c);
4732
4733         zero(control);
4734         control.cmsghdr.cmsg_level = SOL_SOCKET;
4735         control.cmsghdr.cmsg_type = SCM_CREDENTIALS;
4736         control.cmsghdr.cmsg_len = CMSG_LEN(sizeof(struct ucred));
4737
4738         ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
4739         ucred->pid = getpid();
4740         ucred->uid = getuid();
4741         ucred->gid = getgid();
4742
4743         zero(msghdr);
4744         msghdr.msg_name = &sockaddr;
4745         msghdr.msg_namelen = sizeof(sa_family_t) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
4746
4747         msghdr.msg_iov = &iovec;
4748         msghdr.msg_iovlen = 1;
4749         msghdr.msg_control = &control;
4750         msghdr.msg_controllen = control.cmsghdr.cmsg_len;
4751
4752         if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
4753                 close_nointr_nofail(fd);
4754                 return -errno;
4755         }
4756
4757         close_nointr_nofail(fd);
4758         return 0;
4759 }
4760
4761 static int reload_with_fallback(DBusConnection *bus) {
4762
4763         if (bus) {
4764                 /* First, try systemd via D-Bus. */
4765                 if (daemon_reload(bus, NULL, 0) > 0)
4766                         return 0;
4767         }
4768
4769         /* Nothing else worked, so let's try signals */
4770         assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
4771
4772         if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
4773                 log_error("kill() failed: %m");
4774                 return -errno;
4775         }
4776
4777         return 0;
4778 }
4779
4780 static int start_with_fallback(DBusConnection *bus) {
4781
4782         if (bus) {
4783                 /* First, try systemd via D-Bus. */
4784                 if (start_unit(bus, NULL, 0) > 0)
4785                         goto done;
4786         }
4787
4788         /* Hmm, talking to systemd via D-Bus didn't work. Then
4789          * let's try to talk to Upstart via D-Bus. */
4790         if (talk_upstart() > 0)
4791                 goto done;
4792
4793         /* Nothing else worked, so let's try
4794          * /dev/initctl */
4795         if (talk_initctl() > 0)
4796                 goto done;
4797
4798         log_error("Failed to talk to init daemon.");
4799         return -EIO;
4800
4801 done:
4802         warn_wall(arg_action);
4803         return 0;
4804 }
4805
4806 static int halt_main(DBusConnection *bus) {
4807         int r;
4808
4809         if (geteuid() != 0) {
4810                 log_error("Must to be root.");
4811                 return -EPERM;
4812         }
4813
4814         if (arg_when > 0) {
4815                 char *m;
4816                 char date[FORMAT_TIMESTAMP_MAX];
4817
4818                 m = strv_join(arg_wall, " ");
4819                 r = send_shutdownd(arg_when,
4820                                    arg_action == ACTION_HALT     ? 'H' :
4821                                    arg_action == ACTION_POWEROFF ? 'P' :
4822                                                                    'r',
4823                                    !arg_no_wall,
4824                                    m);
4825                 free(m);
4826
4827                 if (r < 0)
4828                         log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
4829                 else {
4830                         log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
4831                                  format_timestamp(date, sizeof(date), arg_when));
4832                         return 0;
4833                 }
4834         }
4835
4836         if (!arg_dry && !arg_immediate)
4837                 return start_with_fallback(bus);
4838
4839         if (!arg_no_wtmp) {
4840                 if (sd_booted() > 0)
4841                         log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
4842                 else if ((r = utmp_put_shutdown(0)) < 0)
4843                         log_warning("Failed to write utmp record: %s", strerror(-r));
4844         }
4845
4846         if (!arg_no_sync)
4847                 sync();
4848
4849         if (arg_dry)
4850                 return 0;
4851
4852         /* Make sure C-A-D is handled by the kernel from this
4853          * point on... */
4854         reboot(RB_ENABLE_CAD);
4855
4856         switch (arg_action) {
4857
4858         case ACTION_HALT:
4859                 log_info("Halting.");
4860                 reboot(RB_HALT_SYSTEM);
4861                 break;
4862
4863         case ACTION_POWEROFF:
4864                 log_info("Powering off.");
4865                 reboot(RB_POWER_OFF);
4866                 break;
4867
4868         case ACTION_REBOOT:
4869                 log_info("Rebooting.");
4870                 reboot(RB_AUTOBOOT);
4871                 break;
4872
4873         default:
4874                 assert_not_reached("Unknown halt action.");
4875         }
4876
4877         /* We should never reach this. */
4878         return -ENOSYS;
4879 }
4880
4881 static int runlevel_main(void) {
4882         int r, runlevel, previous;
4883
4884         if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
4885                 printf("unknown\n");
4886                 return r;
4887         }
4888
4889         printf("%c %c\n",
4890                previous <= 0 ? 'N' : previous,
4891                runlevel <= 0 ? 'N' : runlevel);
4892
4893         return 0;
4894 }
4895
4896 int main(int argc, char*argv[]) {
4897         int r, retval = 1;
4898         DBusConnection *bus = NULL;
4899         DBusError error;
4900
4901         dbus_error_init(&error);
4902
4903         log_parse_environment();
4904         log_open();
4905
4906         if ((r = parse_argv(argc, argv)) < 0)
4907                 goto finish;
4908         else if (r == 0) {
4909                 retval = 0;
4910                 goto finish;
4911         }
4912
4913         /* /sbin/runlevel doesn't need to communicate via D-Bus, so
4914          * let's shortcut this */
4915         if (arg_action == ACTION_RUNLEVEL) {
4916                 retval = runlevel_main() < 0;
4917                 goto finish;
4918         }
4919
4920         bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
4921
4922         switch (arg_action) {
4923
4924         case ACTION_SYSTEMCTL: {
4925                 retval = systemctl_main(bus, argc, argv, &error) < 0;
4926                 break;
4927         }
4928
4929         case ACTION_HALT:
4930         case ACTION_POWEROFF:
4931         case ACTION_REBOOT:
4932                 retval = halt_main(bus) < 0;
4933                 break;
4934
4935         case ACTION_RUNLEVEL2:
4936         case ACTION_RUNLEVEL3:
4937         case ACTION_RUNLEVEL4:
4938         case ACTION_RUNLEVEL5:
4939         case ACTION_RESCUE:
4940         case ACTION_EMERGENCY:
4941         case ACTION_DEFAULT:
4942                 retval = start_with_fallback(bus) < 0;
4943                 break;
4944
4945         case ACTION_RELOAD:
4946         case ACTION_REEXEC:
4947                 retval = reload_with_fallback(bus) < 0;
4948                 break;
4949
4950         case ACTION_CANCEL_SHUTDOWN:
4951                 retval = send_shutdownd(0, 0, false, NULL) < 0;
4952                 break;
4953
4954         case ACTION_INVALID:
4955         case ACTION_RUNLEVEL:
4956         default:
4957                 assert_not_reached("Unknown action");
4958         }
4959
4960 finish:
4961
4962         if (bus) {
4963                 dbus_connection_close(bus);
4964                 dbus_connection_unref(bus);
4965         }
4966
4967         dbus_error_free(&error);
4968
4969         dbus_shutdown();
4970
4971         strv_free(arg_property);
4972
4973         return retval;
4974 }