chiark / gitweb /
4f39cac07b8a20f08030ae7d4b0088b84e3affa4
[elogind.git] / src / systemctl.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <sys/reboot.h>
23 #include <stdio.h>
24 #include <getopt.h>
25 #include <stdbool.h>
26 #include <string.h>
27 #include <errno.h>
28 #include <sys/ioctl.h>
29 #include <termios.h>
30 #include <unistd.h>
31 #include <fcntl.h>
32 #include <sys/socket.h>
33 #include <sys/stat.h>
34
35 #include <dbus/dbus.h>
36
37 #include "log.h"
38 #include "util.h"
39 #include "macro.h"
40 #include "set.h"
41 #include "utmp-wtmp.h"
42 #include "special.h"
43 #include "initreq.h"
44 #include "strv.h"
45 #include "dbus-common.h"
46 #include "cgroup-show.h"
47 #include "cgroup-util.h"
48 #include "list.h"
49 #include "path-lookup.h"
50 #include "conf-parser.h"
51 #include "sd-daemon.h"
52 #include "shutdownd.h"
53
54 static const char *arg_type = NULL;
55 static char **arg_property = NULL;
56 static bool arg_all = false;
57 static bool arg_fail = false;
58 static bool arg_session = false;
59 static bool arg_global = false;
60 static bool arg_immediate = false;
61 static bool arg_no_block = false;
62 static bool arg_no_wtmp = false;
63 static bool arg_no_sync = false;
64 static bool arg_no_wall = false;
65 static bool arg_no_reload = false;
66 static bool arg_dry = false;
67 static bool arg_quiet = false;
68 static bool arg_full = false;
69 static bool arg_force = false;
70 static bool arg_defaults = false;
71 static char **arg_wall = NULL;
72 static usec_t arg_when = 0;
73 static enum action {
74         ACTION_INVALID,
75         ACTION_SYSTEMCTL,
76         ACTION_HALT,
77         ACTION_POWEROFF,
78         ACTION_REBOOT,
79         ACTION_RUNLEVEL2,
80         ACTION_RUNLEVEL3,
81         ACTION_RUNLEVEL4,
82         ACTION_RUNLEVEL5,
83         ACTION_RESCUE,
84         ACTION_EMERGENCY,
85         ACTION_DEFAULT,
86         ACTION_RELOAD,
87         ACTION_REEXEC,
88         ACTION_RUNLEVEL,
89         ACTION_CANCEL_SHUTDOWN,
90         _ACTION_MAX
91 } arg_action = ACTION_SYSTEMCTL;
92 static enum dot {
93         DOT_ALL,
94         DOT_ORDER,
95         DOT_REQUIRE
96 } arg_dot = DOT_ALL;
97
98 static bool private_bus = false;
99
100 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
101
102 static bool on_tty(void) {
103         static int t = -1;
104
105         if (_unlikely_(t < 0))
106                 t = isatty(STDOUT_FILENO) > 0;
107
108         return t;
109 }
110
111 static const char *ansi_highlight(bool b) {
112
113         if (!on_tty())
114                 return "";
115
116         return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
117 }
118
119 static const char *ansi_highlight_green(bool b) {
120
121         if (!on_tty())
122                 return "";
123
124         return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
125 }
126
127 static bool error_is_no_service(DBusError *error) {
128
129         assert(error);
130
131         if (!dbus_error_is_set(error))
132                 return false;
133
134         if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
135                 return true;
136
137         if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
138                 return true;
139
140         return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
141 }
142
143 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
144
145         assert(iter);
146         assert(data);
147
148         if (dbus_message_iter_get_arg_type(iter) != type)
149                 return -EIO;
150
151         dbus_message_iter_get_basic(iter, data);
152
153         if (!dbus_message_iter_next(iter) != !next)
154                 return -EIO;
155
156         return 0;
157 }
158
159 static void warn_wall(enum action action) {
160         static const char *table[_ACTION_MAX] = {
161                 [ACTION_HALT]      = "The system is going down for system halt NOW!",
162                 [ACTION_REBOOT]    = "The system is going down for reboot NOW!",
163                 [ACTION_POWEROFF]  = "The system is going down for power-off NOW!",
164                 [ACTION_RESCUE]    = "The system is going down to rescue mode NOW!",
165                 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
166         };
167
168         if (arg_no_wall)
169                 return;
170
171         if (arg_wall) {
172                 char *p;
173
174                 if (!(p = strv_join(arg_wall, " "))) {
175                         log_error("Failed to join strings.");
176                         return;
177                 }
178
179                 if (*p) {
180                         utmp_wall(p);
181                         free(p);
182                         return;
183                 }
184
185                 free(p);
186         }
187
188         if (!table[action])
189                 return;
190
191         utmp_wall(table[action]);
192 }
193
194 struct unit_info {
195         const char *id;
196         const char *description;
197         const char *load_state;
198         const char *active_state;
199         const char *sub_state;
200         const char *following;
201         const char *unit_path;
202         uint32_t job_id;
203         const char *job_type;
204         const char *job_path;
205 };
206
207 static int compare_unit_info(const void *a, const void *b) {
208         const char *d1, *d2;
209         const struct unit_info *u = a, *v = b;
210
211         d1 = strrchr(u->id, '.');
212         d2 = strrchr(v->id, '.');
213
214         if (d1 && d2) {
215                 int r;
216
217                 if ((r = strcasecmp(d1, d2)) != 0)
218                         return r;
219         }
220
221         return strcasecmp(u->id, v->id);
222 }
223
224 static int list_units(DBusConnection *bus, char **args, unsigned n) {
225         DBusMessage *m = NULL, *reply = NULL;
226         DBusError error;
227         int r;
228         DBusMessageIter iter, sub, sub2;
229         unsigned c = 0, k, n_units = 0;
230         struct unit_info *unit_infos = NULL;
231
232         dbus_error_init(&error);
233
234         assert(bus);
235
236         if (!(m = dbus_message_new_method_call(
237                               "org.freedesktop.systemd1",
238                               "/org/freedesktop/systemd1",
239                               "org.freedesktop.systemd1.Manager",
240                               "ListUnits"))) {
241                 log_error("Could not allocate message.");
242                 return -ENOMEM;
243         }
244
245         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
246                 log_error("Failed to issue method call: %s", error.message);
247                 r = -EIO;
248                 goto finish;
249         }
250
251         if (!dbus_message_iter_init(reply, &iter) ||
252             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
253             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT)  {
254                 log_error("Failed to parse reply.");
255                 r = -EIO;
256                 goto finish;
257         }
258
259         dbus_message_iter_recurse(&iter, &sub);
260
261         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
262                 struct unit_info *u;
263
264                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
265                         log_error("Failed to parse reply.");
266                         r = -EIO;
267                         goto finish;
268                 }
269
270                 if (c >= n_units) {
271                         struct unit_info *w;
272
273                         n_units = MAX(2*c, 16);
274                         w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
275
276                         if (!w) {
277                                 log_error("Failed to allocate unit array.");
278                                 r = -ENOMEM;
279                                 goto finish;
280                         }
281
282                         unit_infos = w;
283                 }
284
285                 u = unit_infos+c;
286
287                 dbus_message_iter_recurse(&sub, &sub2);
288
289                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
290                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
291                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
292                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
293                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
294                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
295                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
296                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
297                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
298                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
299                         log_error("Failed to parse reply.");
300                         r = -EIO;
301                         goto finish;
302                 }
303
304                 dbus_message_iter_next(&sub);
305                 c++;
306         }
307
308         qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
309
310         if (isatty(STDOUT_FILENO))
311                 printf("%-45s %-6s %-12s %-12s %-15s %s\n", "UNIT", "LOAD", "ACTIVE", "SUB", "JOB", "DESCRIPTION");
312
313         for (k = 0; k < c; k++) {
314                 const char *dot;
315                 struct unit_info *u = unit_infos+k;
316
317                 if ((!arg_type || ((dot = strrchr(u->id, '.')) &&
318                                    streq(dot+1, arg_type))) &&
319                     (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0)) {
320                         char *e;
321                         int a = 0, b = 0;
322                         const char *on, *off;
323
324                         if (streq(u->active_state, "maintenance")) {
325                                 on = ansi_highlight(true);
326                                 off = ansi_highlight(false);
327                         } else
328                                 on = off = "";
329
330                         e = arg_full ? NULL : ellipsize(u->id, 45, 33);
331                         printf("%-45s %-6s %s%-12s %-12s%s%n", e ? e : u->id, u->load_state, on, u->active_state, u->sub_state, off, &a);
332                         free(e);
333
334                         a -= strlen(on) + strlen(off);
335
336                         if (u->job_id != 0)
337                                 printf(" => %-12s%n", u->job_type, &b);
338                         else
339                                 b = 1 + 15;
340
341                         if (a + b + 2 < columns()) {
342                                 if (u->job_id == 0)
343                                         printf("                ");
344
345                                 printf(" %.*s", columns() - a - b - 2, u->description);
346                         }
347
348                         fputs("\n", stdout);
349                 }
350         }
351
352         if (isatty(STDOUT_FILENO)) {
353
354                 printf("\nLOAD   = Reflects whether the unit definition was properly loaded.\n"
355                        "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
356                        "SUB    = The low-level unit activation state, values depend on unit type.\n"
357                        "JOB    = Pending job for the unit.\n");
358
359                 if (arg_all)
360                         printf("\n%u units listed.\n", c);
361                 else
362                         printf("\n%u units listed. Pass --all to see inactive units, too.\n", c);
363         }
364
365         r = 0;
366
367 finish:
368         if (m)
369                 dbus_message_unref(m);
370
371         if (reply)
372                 dbus_message_unref(reply);
373
374         free(unit_infos);
375
376         dbus_error_free(&error);
377
378         return r;
379 }
380
381 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
382         static const char * const colors[] = {
383                 "Requires",              "[color=\"black\"]",
384                 "RequiresOverridable",   "[color=\"black\"]",
385                 "Requisite",             "[color=\"darkblue\"]",
386                 "RequisiteOverridable",  "[color=\"darkblue\"]",
387                 "Wants",                 "[color=\"darkgrey\"]",
388                 "Conflicts",             "[color=\"red\"]",
389                 "ConflictedBy",          "[color=\"red\"]",
390                 "After",                 "[color=\"green\"]"
391         };
392
393         const char *c = NULL;
394         unsigned i;
395
396         assert(name);
397         assert(prop);
398         assert(iter);
399
400         for (i = 0; i < ELEMENTSOF(colors); i += 2)
401                 if (streq(colors[i], prop)) {
402                         c = colors[i+1];
403                         break;
404                 }
405
406         if (!c)
407                 return 0;
408
409         if (arg_dot != DOT_ALL)
410                 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
411                         return 0;
412
413         switch (dbus_message_iter_get_arg_type(iter)) {
414
415         case DBUS_TYPE_ARRAY:
416
417                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
418                         DBusMessageIter sub;
419
420                         dbus_message_iter_recurse(iter, &sub);
421
422                         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
423                                 const char *s;
424
425                                 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
426                                 dbus_message_iter_get_basic(&sub, &s);
427                                 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
428
429                                 dbus_message_iter_next(&sub);
430                         }
431
432                         return 0;
433                 }
434         }
435
436         return 0;
437 }
438
439 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
440         DBusMessage *m = NULL, *reply = NULL;
441         const char *interface = "org.freedesktop.systemd1.Unit";
442         int r;
443         DBusError error;
444         DBusMessageIter iter, sub, sub2, sub3;
445
446         assert(bus);
447         assert(path);
448
449         dbus_error_init(&error);
450
451         if (!(m = dbus_message_new_method_call(
452                               "org.freedesktop.systemd1",
453                               path,
454                               "org.freedesktop.DBus.Properties",
455                               "GetAll"))) {
456                 log_error("Could not allocate message.");
457                 r = -ENOMEM;
458                 goto finish;
459         }
460
461         if (!dbus_message_append_args(m,
462                                       DBUS_TYPE_STRING, &interface,
463                                       DBUS_TYPE_INVALID)) {
464                 log_error("Could not append arguments to message.");
465                 r = -ENOMEM;
466                 goto finish;
467         }
468
469         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
470                 log_error("Failed to issue method call: %s", error.message);
471                 r = -EIO;
472                 goto finish;
473         }
474
475         if (!dbus_message_iter_init(reply, &iter) ||
476             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
477             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY)  {
478                 log_error("Failed to parse reply.");
479                 r = -EIO;
480                 goto finish;
481         }
482
483         dbus_message_iter_recurse(&iter, &sub);
484
485         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
486                 const char *prop;
487
488                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
489                         log_error("Failed to parse reply.");
490                         r = -EIO;
491                         goto finish;
492                 }
493
494                 dbus_message_iter_recurse(&sub, &sub2);
495
496                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
497                         log_error("Failed to parse reply.");
498                         r = -EIO;
499                         goto finish;
500                 }
501
502                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT)  {
503                         log_error("Failed to parse reply.");
504                         r = -EIO;
505                         goto finish;
506                 }
507
508                 dbus_message_iter_recurse(&sub2, &sub3);
509
510                 if (dot_one_property(name, prop, &sub3)) {
511                         log_error("Failed to parse reply.");
512                         r = -EIO;
513                         goto finish;
514                 }
515
516                 dbus_message_iter_next(&sub);
517         }
518
519         r = 0;
520
521 finish:
522         if (m)
523                 dbus_message_unref(m);
524
525         if (reply)
526                 dbus_message_unref(reply);
527
528         dbus_error_free(&error);
529
530         return r;
531 }
532
533 static int dot(DBusConnection *bus, char **args, unsigned n) {
534         DBusMessage *m = NULL, *reply = NULL;
535         DBusError error;
536         int r;
537         DBusMessageIter iter, sub, sub2;
538
539         dbus_error_init(&error);
540
541         assert(bus);
542
543         if (!(m = dbus_message_new_method_call(
544                               "org.freedesktop.systemd1",
545                               "/org/freedesktop/systemd1",
546                               "org.freedesktop.systemd1.Manager",
547                               "ListUnits"))) {
548                 log_error("Could not allocate message.");
549                 return -ENOMEM;
550         }
551
552         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
553                 log_error("Failed to issue method call: %s", error.message);
554                 r = -EIO;
555                 goto finish;
556         }
557
558         if (!dbus_message_iter_init(reply, &iter) ||
559             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
560             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT)  {
561                 log_error("Failed to parse reply.");
562                 r = -EIO;
563                 goto finish;
564         }
565
566         printf("digraph systemd {\n");
567
568         dbus_message_iter_recurse(&iter, &sub);
569         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
570                 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
571
572                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
573                         log_error("Failed to parse reply.");
574                         r = -EIO;
575                         goto finish;
576                 }
577
578                 dbus_message_iter_recurse(&sub, &sub2);
579
580                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
581                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
582                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
583                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
584                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
585                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
586                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
587                         log_error("Failed to parse reply.");
588                         r = -EIO;
589                         goto finish;
590                 }
591
592                 if ((r = dot_one(bus, id, unit_path)) < 0)
593                         goto finish;
594
595                 /* printf("\t\"%s\";\n", id); */
596                 dbus_message_iter_next(&sub);
597         }
598
599         printf("}\n");
600
601         log_info("   Color legend: black     = Requires\n"
602                  "                 dark blue = Requisite\n"
603                  "                 dark grey = Wants\n"
604                  "                 red       = Conflicts\n"
605                  "                 green     = After\n");
606
607         if (isatty(fileno(stdout)))
608                 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
609                            "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
610
611         r = 0;
612
613 finish:
614         if (m)
615                 dbus_message_unref(m);
616
617         if (reply)
618                 dbus_message_unref(reply);
619
620         dbus_error_free(&error);
621
622         return r;
623 }
624
625 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
626         DBusMessage *m = NULL, *reply = NULL;
627         DBusError error;
628         int r;
629         DBusMessageIter iter, sub, sub2;
630         unsigned k = 0;
631
632         dbus_error_init(&error);
633
634         assert(bus);
635
636         if (!(m = dbus_message_new_method_call(
637                               "org.freedesktop.systemd1",
638                               "/org/freedesktop/systemd1",
639                               "org.freedesktop.systemd1.Manager",
640                               "ListJobs"))) {
641                 log_error("Could not allocate message.");
642                 return -ENOMEM;
643         }
644
645         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
646                 log_error("Failed to issue method call: %s", error.message);
647                 r = -EIO;
648                 goto finish;
649         }
650
651         if (!dbus_message_iter_init(reply, &iter) ||
652             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
653             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT)  {
654                 log_error("Failed to parse reply.");
655                 r = -EIO;
656                 goto finish;
657         }
658
659         dbus_message_iter_recurse(&iter, &sub);
660
661         printf("%4s %-45s %-17s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
662
663         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
664                 const char *name, *type, *state, *job_path, *unit_path;
665                 uint32_t id;
666                 char *e;
667
668                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
669                         log_error("Failed to parse reply.");
670                         r = -EIO;
671                         goto finish;
672                 }
673
674                 dbus_message_iter_recurse(&sub, &sub2);
675
676                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
677                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
678                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
679                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
680                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
681                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
682                         log_error("Failed to parse reply.");
683                         r = -EIO;
684                         goto finish;
685                 }
686
687                 e = arg_full ? NULL : ellipsize(name, 45, 33);
688                 printf("%4u %-45s %-17s %-7s\n", id, e ? e : name, type, state);
689                 free(e);
690
691                 k++;
692
693                 dbus_message_iter_next(&sub);
694         }
695
696         printf("\n%u jobs listed.\n", k);
697         r = 0;
698
699 finish:
700         if (m)
701                 dbus_message_unref(m);
702
703         if (reply)
704                 dbus_message_unref(reply);
705
706         dbus_error_free(&error);
707
708         return r;
709 }
710
711 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
712         DBusMessage *m = NULL, *reply = NULL;
713         DBusError error;
714         int r;
715         unsigned i;
716
717         dbus_error_init(&error);
718
719         assert(bus);
720         assert(args);
721
722         for (i = 1; i < n; i++) {
723
724                 if (!(m = dbus_message_new_method_call(
725                                       "org.freedesktop.systemd1",
726                                       "/org/freedesktop/systemd1",
727                                       "org.freedesktop.systemd1.Manager",
728                                       "LoadUnit"))) {
729                         log_error("Could not allocate message.");
730                         r = -ENOMEM;
731                         goto finish;
732                 }
733
734                 if (!dbus_message_append_args(m,
735                                               DBUS_TYPE_STRING, &args[i],
736                                               DBUS_TYPE_INVALID)) {
737                         log_error("Could not append arguments to message.");
738                         r = -ENOMEM;
739                         goto finish;
740                 }
741
742                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
743                         log_error("Failed to issue method call: %s", error.message);
744                         r = -EIO;
745                         goto finish;
746                 }
747
748                 dbus_message_unref(m);
749                 dbus_message_unref(reply);
750
751                 m = reply = NULL;
752         }
753
754         r = 0;
755
756 finish:
757         if (m)
758                 dbus_message_unref(m);
759
760         if (reply)
761                 dbus_message_unref(reply);
762
763         dbus_error_free(&error);
764
765         return r;
766 }
767
768 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
769         DBusMessage *m = NULL, *reply = NULL;
770         DBusError error;
771         int r;
772         unsigned i;
773
774         dbus_error_init(&error);
775
776         assert(bus);
777         assert(args);
778
779         if (n <= 1)
780                 return daemon_reload(bus, args, n);
781
782         for (i = 1; i < n; i++) {
783                 unsigned id;
784                 const char *path;
785
786                 if (!(m = dbus_message_new_method_call(
787                                       "org.freedesktop.systemd1",
788                                       "/org/freedesktop/systemd1",
789                                       "org.freedesktop.systemd1.Manager",
790                                       "GetJob"))) {
791                         log_error("Could not allocate message.");
792                         r = -ENOMEM;
793                         goto finish;
794                 }
795
796                 if ((r = safe_atou(args[i], &id)) < 0) {
797                         log_error("Failed to parse job id: %s", strerror(-r));
798                         goto finish;
799                 }
800
801                 assert_cc(sizeof(uint32_t) == sizeof(id));
802                 if (!dbus_message_append_args(m,
803                                               DBUS_TYPE_UINT32, &id,
804                                               DBUS_TYPE_INVALID)) {
805                         log_error("Could not append arguments to message.");
806                         r = -ENOMEM;
807                         goto finish;
808                 }
809
810                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
811                         log_error("Failed to issue method call: %s", error.message);
812                         r = -EIO;
813                         goto finish;
814                 }
815
816                 if (!dbus_message_get_args(reply, &error,
817                                            DBUS_TYPE_OBJECT_PATH, &path,
818                                            DBUS_TYPE_INVALID)) {
819                         log_error("Failed to parse reply: %s", error.message);
820                         r = -EIO;
821                         goto finish;
822                 }
823
824                 dbus_message_unref(m);
825                 if (!(m = dbus_message_new_method_call(
826                                       "org.freedesktop.systemd1",
827                                       path,
828                                       "org.freedesktop.systemd1.Job",
829                                       "Cancel"))) {
830                         log_error("Could not allocate message.");
831                         r = -ENOMEM;
832                         goto finish;
833                 }
834
835                 dbus_message_unref(reply);
836                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
837                         log_error("Failed to issue method call: %s", error.message);
838                         r = -EIO;
839                         goto finish;
840                 }
841
842                 dbus_message_unref(m);
843                 dbus_message_unref(reply);
844                 m = reply = NULL;
845         }
846
847         r = 0;
848
849 finish:
850         if (m)
851                 dbus_message_unref(m);
852
853         if (reply)
854                 dbus_message_unref(reply);
855
856         dbus_error_free(&error);
857
858         return r;
859 }
860
861 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
862         DBusMessage *m = NULL, *reply = NULL;
863         dbus_bool_t b = FALSE;
864         DBusMessageIter iter, sub;
865         const char
866                 *interface = "org.freedesktop.systemd1.Unit",
867                 *property = "NeedDaemonReload",
868                 *path;
869
870         /* We ignore all errors here, since this is used to show a warning only */
871
872         if (!(m = dbus_message_new_method_call(
873                               "org.freedesktop.systemd1",
874                               "/org/freedesktop/systemd1",
875                               "org.freedesktop.systemd1.Manager",
876                               "GetUnit")))
877                 goto finish;
878
879         if (!dbus_message_append_args(m,
880                                       DBUS_TYPE_STRING, &unit,
881                                       DBUS_TYPE_INVALID))
882                 goto finish;
883
884         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
885                 goto finish;
886
887         if (!dbus_message_get_args(reply, NULL,
888                                    DBUS_TYPE_OBJECT_PATH, &path,
889                                    DBUS_TYPE_INVALID))
890                 goto finish;
891
892         dbus_message_unref(m);
893         if (!(m = dbus_message_new_method_call(
894                               "org.freedesktop.systemd1",
895                               path,
896                               "org.freedesktop.DBus.Properties",
897                               "Get")))
898                 goto finish;
899
900         if (!dbus_message_append_args(m,
901                                       DBUS_TYPE_STRING, &interface,
902                                       DBUS_TYPE_STRING, &property,
903                                       DBUS_TYPE_INVALID)) {
904                 goto finish;
905         }
906
907         dbus_message_unref(reply);
908         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
909                 goto finish;
910
911         if (!dbus_message_iter_init(reply, &iter) ||
912             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
913                 goto finish;
914
915         dbus_message_iter_recurse(&iter, &sub);
916
917         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
918                 goto finish;
919
920         dbus_message_iter_get_basic(&sub, &b);
921
922 finish:
923         if (m)
924                 dbus_message_unref(m);
925
926         if (reply)
927                 dbus_message_unref(reply);
928
929         return b;
930 }
931
932 typedef struct WaitData {
933         Set *set;
934         bool failed;
935 } WaitData;
936
937 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
938         DBusError error;
939         WaitData *d = data;
940
941         assert(connection);
942         assert(message);
943         assert(d);
944
945         dbus_error_init(&error);
946
947         log_debug("Got D-Bus request: %s.%s() on %s",
948                   dbus_message_get_interface(message),
949                   dbus_message_get_member(message),
950                   dbus_message_get_path(message));
951
952         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
953                 log_error("Warning! D-Bus connection terminated.");
954                 dbus_connection_close(connection);
955
956         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
957                 uint32_t id;
958                 const char *path;
959                 dbus_bool_t success = true;
960
961                 if (!dbus_message_get_args(message, &error,
962                                            DBUS_TYPE_UINT32, &id,
963                                            DBUS_TYPE_OBJECT_PATH, &path,
964                                            DBUS_TYPE_BOOLEAN, &success,
965                                            DBUS_TYPE_INVALID))
966                         log_error("Failed to parse message: %s", error.message);
967                 else {
968                         char *p;
969
970                         if ((p = set_remove(d->set, (char*) path)))
971                                 free(p);
972
973                         if (!success)
974                                 d->failed = true;
975                 }
976         }
977
978         dbus_error_free(&error);
979         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
980 }
981
982 static int enable_wait_for_jobs(DBusConnection *bus) {
983         DBusError error;
984
985         assert(bus);
986
987         if (private_bus)
988                 return 0;
989
990         dbus_error_init(&error);
991         dbus_bus_add_match(bus,
992                            "type='signal',"
993                            "sender='org.freedesktop.systemd1',"
994                            "interface='org.freedesktop.systemd1.Manager',"
995                            "member='JobRemoved',"
996                            "path='/org/freedesktop/systemd1'",
997                            &error);
998
999         if (dbus_error_is_set(&error)) {
1000                 log_error("Failed to add match: %s", error.message);
1001                 dbus_error_free(&error);
1002                 return -EIO;
1003         }
1004
1005         /* This is slightly dirty, since we don't undo the match registrations. */
1006         return 0;
1007 }
1008
1009 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1010         int r;
1011         WaitData d;
1012
1013         assert(bus);
1014         assert(s);
1015
1016         zero(d);
1017         d.set = s;
1018         d.failed = false;
1019
1020         if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1021                 log_error("Failed to add filter.");
1022                 r = -ENOMEM;
1023                 goto finish;
1024         }
1025
1026         while (!set_isempty(s) &&
1027                dbus_connection_read_write_dispatch(bus, -1))
1028                 ;
1029
1030         if (!arg_quiet && d.failed)
1031                 log_error("Job failed, see logs for details.");
1032
1033         r = d.failed ? -EIO : 0;
1034
1035 finish:
1036         /* This is slightly dirty, since we don't undo the filter registration. */
1037
1038         return r;
1039 }
1040
1041 static int start_unit_one(
1042                 DBusConnection *bus,
1043                 const char *method,
1044                 const char *name,
1045                 const char *mode,
1046                 Set *s) {
1047
1048         DBusMessage *m = NULL, *reply = NULL;
1049         DBusError error;
1050         const char *path;
1051         int r;
1052
1053         assert(bus);
1054         assert(method);
1055         assert(name);
1056         assert(mode);
1057         assert(arg_no_block || s);
1058
1059         dbus_error_init(&error);
1060
1061         if (!(m = dbus_message_new_method_call(
1062                               "org.freedesktop.systemd1",
1063                               "/org/freedesktop/systemd1",
1064                               "org.freedesktop.systemd1.Manager",
1065                               method))) {
1066                 log_error("Could not allocate message.");
1067                 r = -ENOMEM;
1068                 goto finish;
1069         }
1070
1071         if (!dbus_message_append_args(m,
1072                                       DBUS_TYPE_STRING, &name,
1073                                       DBUS_TYPE_STRING, &mode,
1074                                       DBUS_TYPE_INVALID)) {
1075                 log_error("Could not append arguments to message.");
1076                 r = -ENOMEM;
1077                 goto finish;
1078         }
1079
1080         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1081
1082                 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
1083                         /* There's always a fallback possible for
1084                          * legacy actions. */
1085                         r = 0;
1086                         goto finish;
1087                 }
1088
1089                 log_error("Failed to issue method call: %s", error.message);
1090                 r = -EIO;
1091                 goto finish;
1092         }
1093
1094         if (!dbus_message_get_args(reply, &error,
1095                                    DBUS_TYPE_OBJECT_PATH, &path,
1096                                    DBUS_TYPE_INVALID)) {
1097                 log_error("Failed to parse reply: %s", error.message);
1098                 r = -EIO;
1099                 goto finish;
1100         }
1101
1102         if (need_daemon_reload(bus, name))
1103                 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1104                             arg_session ? "--session" : "--system");
1105
1106         if (!arg_no_block) {
1107                 char *p;
1108
1109                 if (!(p = strdup(path))) {
1110                         log_error("Failed to duplicate path.");
1111                         r = -ENOMEM;
1112                         goto finish;
1113                 }
1114
1115                 if ((r = set_put(s, p)) < 0) {
1116                         free(p);
1117                         log_error("Failed to add path to set.");
1118                         goto finish;
1119                 }
1120         }
1121
1122         r = 1;
1123
1124 finish:
1125         if (m)
1126                 dbus_message_unref(m);
1127
1128         if (reply)
1129                 dbus_message_unref(reply);
1130
1131         dbus_error_free(&error);
1132
1133         return r;
1134 }
1135
1136 static enum action verb_to_action(const char *verb) {
1137         if (streq(verb, "halt"))
1138                 return ACTION_HALT;
1139         else if (streq(verb, "poweroff"))
1140                 return ACTION_POWEROFF;
1141         else if (streq(verb, "reboot"))
1142                 return ACTION_REBOOT;
1143         else if (streq(verb, "rescue"))
1144                 return ACTION_RESCUE;
1145         else if (streq(verb, "emergency"))
1146                 return ACTION_EMERGENCY;
1147         else if (streq(verb, "default"))
1148                 return ACTION_DEFAULT;
1149         else
1150                 return ACTION_INVALID;
1151 }
1152
1153 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1154
1155         static const char * const table[_ACTION_MAX] = {
1156                 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1157                 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1158                 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1159                 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1160                 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1161                 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1162                 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1163                 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1164                 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1165                 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET
1166         };
1167
1168         int r;
1169         unsigned i;
1170         const char *method, *mode, *one_name;
1171         Set *s = NULL;
1172
1173         assert(bus);
1174
1175         if (arg_action == ACTION_SYSTEMCTL) {
1176                 method =
1177                         streq(args[0], "stop")                  ? "StopUnit" :
1178                         streq(args[0], "reload")                ? "ReloadUnit" :
1179                         streq(args[0], "restart")               ? "RestartUnit" :
1180                         streq(args[0], "try-restart")           ? "TryRestartUnit" :
1181                         streq(args[0], "reload-or-restart")     ? "ReloadOrRestartUnit" :
1182                         streq(args[0], "reload-or-try-restart") ||
1183                         streq(args[0], "force-reload")          ||
1184                         streq(args[0], "condrestart")           ? "ReloadOrTryRestartUnit" :
1185                                                                   "StartUnit";
1186
1187                 mode =
1188                         (streq(args[0], "isolate") ||
1189                          streq(args[0], "rescue")  ||
1190                          streq(args[0], "emergency")) ? "isolate" :
1191                                              arg_fail ? "fail" :
1192                                                         "replace";
1193
1194                 one_name = table[verb_to_action(args[0])];
1195
1196         } else {
1197                 assert(arg_action < ELEMENTSOF(table));
1198                 assert(table[arg_action]);
1199
1200                 method = "StartUnit";
1201
1202                 mode = (arg_action == ACTION_EMERGENCY ||
1203                         arg_action == ACTION_RESCUE) ? "isolate" : "replace";
1204
1205                 one_name = table[arg_action];
1206         }
1207
1208         if (!arg_no_block) {
1209                 if ((r = enable_wait_for_jobs(bus)) < 0) {
1210                         log_error("Could not watch jobs: %s", strerror(-r));
1211                         goto finish;
1212                 }
1213
1214                 if (!(s = set_new(string_hash_func, string_compare_func))) {
1215                         log_error("Failed to allocate set.");
1216                         r = -ENOMEM;
1217                         goto finish;
1218                 }
1219         }
1220
1221         r = 0;
1222
1223         if (one_name) {
1224                 if ((r = start_unit_one(bus, method, one_name, mode, s)) <= 0)
1225                         goto finish;
1226         } else {
1227                 for (i = 1; i < n; i++)
1228                         if ((r = start_unit_one(bus, method, args[i], mode, s)) < 0)
1229                                 goto finish;
1230         }
1231
1232         if (!arg_no_block)
1233                 if ((r = wait_for_jobs(bus, s)) < 0)
1234                         goto finish;
1235
1236         r = 1;
1237
1238 finish:
1239         if (s)
1240                 set_free_free(s);
1241
1242         return r;
1243 }
1244
1245 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1246         int r;
1247
1248         assert(bus);
1249         assert(args);
1250
1251         r = start_unit(bus, args, n);
1252
1253         if (r >= 0)
1254                 warn_wall(verb_to_action(args[0]));
1255
1256         return r;
1257 }
1258
1259 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1260         DBusMessage *m = NULL, *reply = NULL;
1261         const char
1262                 *interface = "org.freedesktop.systemd1.Unit",
1263                 *property = "ActiveState";
1264         int r = -EADDRNOTAVAIL;
1265         DBusError error;
1266         unsigned i;
1267
1268         assert(bus);
1269         assert(args);
1270
1271         dbus_error_init(&error);
1272
1273         for (i = 1; i < n; i++) {
1274                 const char *path = NULL;
1275                 const char *state;
1276                 DBusMessageIter iter, sub;
1277
1278                 if (!(m = dbus_message_new_method_call(
1279                                       "org.freedesktop.systemd1",
1280                                       "/org/freedesktop/systemd1",
1281                                       "org.freedesktop.systemd1.Manager",
1282                                       "GetUnit"))) {
1283                         log_error("Could not allocate message.");
1284                         r = -ENOMEM;
1285                         goto finish;
1286                 }
1287
1288                 if (!dbus_message_append_args(m,
1289                                               DBUS_TYPE_STRING, &args[i],
1290                                               DBUS_TYPE_INVALID)) {
1291                         log_error("Could not append arguments to message.");
1292                         r = -ENOMEM;
1293                         goto finish;
1294                 }
1295
1296                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1297
1298                         /* Hmm, cannot figure out anything about this unit... */
1299                         if (!arg_quiet)
1300                                 puts("unknown");
1301
1302                         dbus_error_free(&error);
1303                         continue;
1304                 }
1305
1306                 if (!dbus_message_get_args(reply, &error,
1307                                            DBUS_TYPE_OBJECT_PATH, &path,
1308                                            DBUS_TYPE_INVALID)) {
1309                         log_error("Failed to parse reply: %s", error.message);
1310                         r = -EIO;
1311                         goto finish;
1312                 }
1313
1314                 dbus_message_unref(m);
1315                 if (!(m = dbus_message_new_method_call(
1316                                       "org.freedesktop.systemd1",
1317                                       path,
1318                                       "org.freedesktop.DBus.Properties",
1319                                       "Get"))) {
1320                         log_error("Could not allocate message.");
1321                         r = -ENOMEM;
1322                         goto finish;
1323                 }
1324
1325                 if (!dbus_message_append_args(m,
1326                                               DBUS_TYPE_STRING, &interface,
1327                                               DBUS_TYPE_STRING, &property,
1328                                               DBUS_TYPE_INVALID)) {
1329                         log_error("Could not append arguments to message.");
1330                         r = -ENOMEM;
1331                         goto finish;
1332                 }
1333
1334                 dbus_message_unref(reply);
1335                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1336                         log_error("Failed to issue method call: %s", error.message);
1337                         r = -EIO;
1338                         goto finish;
1339                 }
1340
1341                 if (!dbus_message_iter_init(reply, &iter) ||
1342                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
1343                         log_error("Failed to parse reply.");
1344                         r = -EIO;
1345                         goto finish;
1346                 }
1347
1348                 dbus_message_iter_recurse(&iter, &sub);
1349
1350                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
1351                         log_error("Failed to parse reply.");
1352                         r = -EIO;
1353                         goto finish;
1354                 }
1355
1356                 dbus_message_iter_get_basic(&sub, &state);
1357
1358                 if (!arg_quiet)
1359                         puts(state);
1360
1361                 if (streq(state, "active") || startswith(state, "reloading"))
1362                         r = 0;
1363
1364                 dbus_message_unref(m);
1365                 dbus_message_unref(reply);
1366                 m = reply = NULL;
1367         }
1368
1369 finish:
1370         if (m)
1371                 dbus_message_unref(m);
1372
1373         if (reply)
1374                 dbus_message_unref(reply);
1375
1376         dbus_error_free(&error);
1377
1378         return r;
1379 }
1380
1381 typedef struct ExecStatusInfo {
1382         char *path;
1383         char **argv;
1384
1385         bool ignore;
1386
1387         usec_t start_timestamp;
1388         usec_t exit_timestamp;
1389         pid_t pid;
1390         int code;
1391         int status;
1392
1393         LIST_FIELDS(struct ExecStatusInfo, exec);
1394 } ExecStatusInfo;
1395
1396 static void exec_status_info_free(ExecStatusInfo *i) {
1397         assert(i);
1398
1399         free(i->path);
1400         strv_free(i->argv);
1401         free(i);
1402 }
1403
1404 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1405         uint64_t start_timestamp, exit_timestamp;
1406         DBusMessageIter sub2, sub3;
1407         const char*path;
1408         unsigned n;
1409         uint32_t pid;
1410         int32_t code, status;
1411         dbus_bool_t ignore;
1412
1413         assert(i);
1414         assert(i);
1415
1416         if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1417                 return -EIO;
1418
1419         dbus_message_iter_recurse(sub, &sub2);
1420
1421         if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1422                 return -EIO;
1423
1424         if (!(i->path = strdup(path)))
1425                 return -ENOMEM;
1426
1427         if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1428             dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1429                 return -EIO;
1430
1431         n = 0;
1432         dbus_message_iter_recurse(&sub2, &sub3);
1433         while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1434                 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1435                 dbus_message_iter_next(&sub3);
1436                 n++;
1437         }
1438
1439
1440         if (!(i->argv = new0(char*, n+1)))
1441                 return -ENOMEM;
1442
1443         n = 0;
1444         dbus_message_iter_recurse(&sub2, &sub3);
1445         while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1446                 const char *s;
1447
1448                 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1449                 dbus_message_iter_get_basic(&sub3, &s);
1450                 dbus_message_iter_next(&sub3);
1451
1452                 if (!(i->argv[n++] = strdup(s)))
1453                         return -ENOMEM;
1454         }
1455
1456         if (!dbus_message_iter_next(&sub2) ||
1457             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1458             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1459             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1460             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1461             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1462             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1463                 return -EIO;
1464
1465         i->ignore = ignore;
1466         i->start_timestamp = (usec_t) start_timestamp;
1467         i->exit_timestamp = (usec_t) exit_timestamp;
1468         i->pid = (pid_t) pid;
1469         i->code = code;
1470         i->status = status;
1471
1472         return 0;
1473 }
1474
1475 typedef struct UnitStatusInfo {
1476         const char *id;
1477         const char *load_state;
1478         const char *active_state;
1479         const char *sub_state;
1480
1481         const char *description;
1482
1483         const char *path;
1484         const char *default_control_group;
1485
1486         bool need_daemon_reload;
1487
1488         /* Service */
1489         pid_t main_pid;
1490         pid_t control_pid;
1491         const char *status_text;
1492         bool running;
1493
1494         usec_t start_timestamp;
1495         usec_t exit_timestamp;
1496
1497         int exit_code, exit_status;
1498
1499         /* Socket */
1500         unsigned n_accepted;
1501         unsigned n_connections;
1502         bool accept;
1503
1504         /* Device */
1505         const char *sysfs_path;
1506
1507         /* Mount, Automount */
1508         const char *where;
1509
1510         /* Swap */
1511         const char *what;
1512
1513         LIST_HEAD(ExecStatusInfo, exec);
1514 } UnitStatusInfo;
1515
1516 static void print_status_info(UnitStatusInfo *i) {
1517         ExecStatusInfo *p;
1518         const char *on, *off, *ss;
1519
1520         assert(i);
1521
1522         /* This shows pretty information about a unit. See
1523          * print_property() for a low-level property printer */
1524
1525         printf("%s", strna(i->id));
1526
1527         if (i->description && !streq_ptr(i->id, i->description))
1528                 printf(" - %s", i->description);
1529
1530         printf("\n");
1531
1532         if (streq_ptr(i->load_state, "failed")) {
1533                 on = ansi_highlight(true);
1534                 off = ansi_highlight(false);
1535         } else
1536                 on = off = "";
1537
1538         if (i->path)
1539                 printf("\t  Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1540         else
1541                 printf("\t  Loaded: %s%s%s\n", on, strna(i->load_state), off);
1542
1543         ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1544
1545         if (streq_ptr(i->active_state, "maintenance")) {
1546                 on = ansi_highlight(true);
1547                 off = ansi_highlight(false);
1548         } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1549                 on = ansi_highlight_green(true);
1550                 off = ansi_highlight_green(false);
1551         } else
1552                 on = off = "";
1553
1554         if (ss)
1555                 printf("\t  Active: %s%s (%s)%s\n",
1556                        on,
1557                        strna(i->active_state),
1558                        ss,
1559                        off);
1560         else
1561                 printf("\t  Active: %s%s%s\n",
1562                        on,
1563                        strna(i->active_state),
1564                        off);
1565
1566         if (i->sysfs_path)
1567                 printf("\t  Device: %s\n", i->sysfs_path);
1568         else if (i->where)
1569                 printf("\t   Where: %s\n", i->where);
1570         else if (i->what)
1571                 printf("\t    What: %s\n", i->what);
1572
1573         if (i->accept)
1574                 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1575
1576         LIST_FOREACH(exec, p, i->exec) {
1577                 char *t;
1578
1579                 /* Only show exited processes here */
1580                 if (p->code == 0)
1581                         continue;
1582
1583                 t = strv_join(p->argv, " ");
1584                 printf("\t  Exited: %u (%s, code=%s, ", p->pid, strna(t), sigchld_code_to_string(p->code));
1585                 free(t);
1586
1587                 if (p->code == CLD_EXITED)
1588                         printf("status=%i", p->status);
1589                 else
1590                         printf("signal=%s", signal_to_string(p->status));
1591                 printf(")\n");
1592
1593                 if (i->main_pid == p->pid &&
1594                     i->start_timestamp == p->start_timestamp &&
1595                     i->exit_timestamp == p->start_timestamp)
1596                         /* Let's not show this twice */
1597                         i->main_pid = 0;
1598
1599                 if (p->pid == i->control_pid)
1600                         i->control_pid = 0;
1601         }
1602
1603         if (i->main_pid > 0 || i->control_pid > 0) {
1604                 printf("\t");
1605
1606                 if (i->main_pid > 0) {
1607                         printf("    Main: %u", (unsigned) i->main_pid);
1608
1609                         if (i->running) {
1610                                 char *t = NULL;
1611                                 get_process_name(i->main_pid, &t);
1612                                 if (t) {
1613                                         printf(" (%s)", t);
1614                                         free(t);
1615                                 }
1616                         } else if (i->exit_code > 0) {
1617                                 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1618
1619                                 if (i->exit_code == CLD_EXITED)
1620                                         printf("status=%i", i->exit_status);
1621                                 else
1622                                         printf("signal=%s", signal_to_string(i->exit_status));
1623                                 printf(")");
1624                         }
1625                 }
1626
1627                 if (i->main_pid > 0 && i->control_pid > 0)
1628                         printf(";");
1629
1630                 if (i->control_pid > 0) {
1631                         char *t = NULL;
1632
1633                         printf(" Control: %u", (unsigned) i->control_pid);
1634
1635                         get_process_name(i->control_pid, &t);
1636                         if (t) {
1637                                 printf(" (%s)", t);
1638                                 free(t);
1639                         }
1640                 }
1641
1642                 printf("\n");
1643         }
1644
1645         if (i->status_text)
1646                 printf("\t  Status: \"%s\"\n", i->status_text);
1647
1648         if (i->default_control_group) {
1649                 unsigned c;
1650
1651                 printf("\t  CGroup: %s\n", i->default_control_group);
1652
1653                 if ((c = columns()) > 18)
1654                         c -= 18;
1655                 else
1656                         c = 0;
1657
1658                 show_cgroup_by_path(i->default_control_group, "\t\t  ", c);
1659         }
1660
1661         if (i->need_daemon_reload)
1662                 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1663                        ansi_highlight(true),
1664                        ansi_highlight(false),
1665                        arg_session ? "--session" : "--system");
1666 }
1667
1668 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1669
1670         switch (dbus_message_iter_get_arg_type(iter)) {
1671
1672         case DBUS_TYPE_STRING: {
1673                 const char *s;
1674
1675                 dbus_message_iter_get_basic(iter, &s);
1676
1677                 if (s[0]) {
1678                         if (streq(name, "Id"))
1679                                 i->id = s;
1680                         else if (streq(name, "LoadState"))
1681                                 i->load_state = s;
1682                         else if (streq(name, "ActiveState"))
1683                                 i->active_state = s;
1684                         else if (streq(name, "SubState"))
1685                                 i->sub_state = s;
1686                         else if (streq(name, "Description"))
1687                                 i->description = s;
1688                         else if (streq(name, "FragmentPath"))
1689                                 i->path = s;
1690                         else if (streq(name, "SysVPath"))
1691                                 i->path = s;
1692                         else if (streq(name, "DefaultControlGroup"))
1693                                 i->default_control_group = s;
1694                         else if (streq(name, "StatusText"))
1695                                 i->status_text = s;
1696                         else if (streq(name, "SysFSPath"))
1697                                 i->sysfs_path = s;
1698                         else if (streq(name, "Where"))
1699                                 i->where = s;
1700                         else if (streq(name, "What"))
1701                                 i->what = s;
1702                 }
1703
1704                 break;
1705         }
1706
1707         case DBUS_TYPE_BOOLEAN: {
1708                 dbus_bool_t b;
1709
1710                 dbus_message_iter_get_basic(iter, &b);
1711
1712                 if (streq(name, "Accept"))
1713                         i->accept = b;
1714                 else if (streq(name, "NeedDaemonReload"))
1715                         i->need_daemon_reload = b;
1716
1717                 break;
1718         }
1719
1720         case DBUS_TYPE_UINT32: {
1721                 uint32_t u;
1722
1723                 dbus_message_iter_get_basic(iter, &u);
1724
1725                 if (streq(name, "MainPID")) {
1726                         if (u > 0) {
1727                                 i->main_pid = (pid_t) u;
1728                                 i->running = true;
1729                         }
1730                 } else if (streq(name, "ControlPID"))
1731                         i->control_pid = (pid_t) u;
1732                 else if (streq(name, "ExecMainPID")) {
1733                         if (u > 0)
1734                                 i->main_pid = (pid_t) u;
1735                 } else if (streq(name, "NAccepted"))
1736                         i->n_accepted = u;
1737                 else if (streq(name, "NConnections"))
1738                         i->n_connections = u;
1739
1740                 break;
1741         }
1742
1743         case DBUS_TYPE_INT32: {
1744                 int32_t j;
1745
1746                 dbus_message_iter_get_basic(iter, &j);
1747
1748                 if (streq(name, "ExecMainCode"))
1749                         i->exit_code = (int) j;
1750                 else if (streq(name, "ExecMainStatus"))
1751                         i->exit_status = (int) j;
1752
1753                 break;
1754         }
1755
1756         case DBUS_TYPE_UINT64: {
1757                 uint64_t u;
1758
1759                 dbus_message_iter_get_basic(iter, &u);
1760
1761                 if (streq(name, "ExecMainStartTimestamp"))
1762                         i->start_timestamp = (usec_t) u;
1763                 else if (streq(name, "ExecMainExitTimestamp"))
1764                         i->exit_timestamp = (usec_t) u;
1765
1766                 break;
1767         }
1768
1769         case DBUS_TYPE_ARRAY: {
1770
1771                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
1772                     startswith(name, "Exec")) {
1773                         DBusMessageIter sub;
1774
1775                         dbus_message_iter_recurse(iter, &sub);
1776                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1777                                 ExecStatusInfo *info;
1778                                 int r;
1779
1780                                 if (!(info = new0(ExecStatusInfo, 1)))
1781                                         return -ENOMEM;
1782
1783                                 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
1784                                         free(info);
1785                                         return r;
1786                                 }
1787
1788                                 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
1789
1790                                 dbus_message_iter_next(&sub);
1791                         }
1792                 }
1793
1794                 break;
1795         }
1796         }
1797
1798         return 0;
1799 }
1800
1801 static int print_property(const char *name, DBusMessageIter *iter) {
1802         assert(name);
1803         assert(iter);
1804
1805         /* This is a low-level property printer, see
1806          * print_status_info() for the nicer output */
1807
1808         if (arg_property && !strv_find(arg_property, name))
1809                 return 0;
1810
1811         switch (dbus_message_iter_get_arg_type(iter)) {
1812
1813         case DBUS_TYPE_STRING: {
1814                 const char *s;
1815                 dbus_message_iter_get_basic(iter, &s);
1816
1817                 if (arg_all || s[0])
1818                         printf("%s=%s\n", name, s);
1819
1820                 return 0;
1821         }
1822
1823         case DBUS_TYPE_BOOLEAN: {
1824                 dbus_bool_t b;
1825                 dbus_message_iter_get_basic(iter, &b);
1826                 printf("%s=%s\n", name, yes_no(b));
1827
1828                 return 0;
1829         }
1830
1831         case DBUS_TYPE_UINT64: {
1832                 uint64_t u;
1833                 dbus_message_iter_get_basic(iter, &u);
1834
1835                 /* Yes, heuristics! But we can change this check
1836                  * should it turn out to not be sufficient */
1837
1838                 if (strstr(name, "Timestamp")) {
1839                         char timestamp[FORMAT_TIMESTAMP_MAX], *t;
1840
1841                         if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
1842                                 printf("%s=%s\n", name, strempty(t));
1843                 } else if (strstr(name, "USec")) {
1844                         char timespan[FORMAT_TIMESPAN_MAX];
1845
1846                         printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
1847                 } else
1848                         printf("%s=%llu\n", name, (unsigned long long) u);
1849
1850                 return 0;
1851         }
1852
1853         case DBUS_TYPE_UINT32: {
1854                 uint32_t u;
1855                 dbus_message_iter_get_basic(iter, &u);
1856
1857                 if (strstr(name, "UMask") || strstr(name, "Mode"))
1858                         printf("%s=%04o\n", name, u);
1859                 else
1860                         printf("%s=%u\n", name, (unsigned) u);
1861
1862                 return 0;
1863         }
1864
1865         case DBUS_TYPE_INT32: {
1866                 int32_t i;
1867                 dbus_message_iter_get_basic(iter, &i);
1868
1869                 printf("%s=%i\n", name, (int) i);
1870                 return 0;
1871         }
1872
1873         case DBUS_TYPE_STRUCT: {
1874                 DBusMessageIter sub;
1875                 dbus_message_iter_recurse(iter, &sub);
1876
1877                 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
1878                         uint32_t u;
1879
1880                         dbus_message_iter_get_basic(&sub, &u);
1881
1882                         if (u)
1883                                 printf("%s=%u\n", name, (unsigned) u);
1884                         else if (arg_all)
1885                                 printf("%s=\n", name);
1886
1887                         return 0;
1888                 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
1889                         const char *s;
1890
1891                         dbus_message_iter_get_basic(&sub, &s);
1892
1893                         if (arg_all || s[0])
1894                                 printf("%s=%s\n", name, s);
1895
1896                         return 0;
1897                 }
1898
1899                 break;
1900         }
1901
1902         case DBUS_TYPE_ARRAY:
1903
1904                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
1905                         DBusMessageIter sub;
1906                         bool space = false;
1907
1908                         dbus_message_iter_recurse(iter, &sub);
1909                         if (arg_all ||
1910                             dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1911                                 printf("%s=", name);
1912
1913                                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1914                                         const char *s;
1915
1916                                         assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
1917                                         dbus_message_iter_get_basic(&sub, &s);
1918                                         printf("%s%s", space ? " " : "", s);
1919
1920                                         space = true;
1921                                         dbus_message_iter_next(&sub);
1922                                 }
1923
1924                                 puts("");
1925                         }
1926
1927                         return 0;
1928
1929                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
1930                         DBusMessageIter sub;
1931
1932                         dbus_message_iter_recurse(iter, &sub);
1933                         if (arg_all ||
1934                             dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1935                                 printf("%s=", name);
1936
1937                                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1938                                         uint8_t u;
1939
1940                                         assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
1941                                         dbus_message_iter_get_basic(&sub, &u);
1942                                         printf("%02x", u);
1943
1944                                         dbus_message_iter_next(&sub);
1945                                 }
1946
1947                                 puts("");
1948                         }
1949
1950                         return 0;
1951
1952                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
1953                         DBusMessageIter sub, sub2;
1954
1955                         dbus_message_iter_recurse(iter, &sub);
1956                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1957                                 const char *type, *path;
1958
1959                                 dbus_message_iter_recurse(&sub, &sub2);
1960
1961                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
1962                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
1963                                         printf("%s=%s\n", type, path);
1964
1965                                 dbus_message_iter_next(&sub);
1966                         }
1967
1968                         return 0;
1969
1970                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
1971                         DBusMessageIter sub, sub2;
1972
1973                         dbus_message_iter_recurse(iter, &sub);
1974                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1975                                 const char *base;
1976                                 uint64_t value, next_elapse;
1977
1978                                 dbus_message_iter_recurse(&sub, &sub2);
1979
1980                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
1981                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
1982                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
1983                                         char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
1984
1985                                         printf("%s={ value=%s ; next_elapse=%s }\n",
1986                                                base,
1987                                                format_timespan(timespan1, sizeof(timespan1), value),
1988                                                format_timespan(timespan2, sizeof(timespan2), next_elapse));
1989                                 }
1990
1991                                 dbus_message_iter_next(&sub);
1992                         }
1993
1994                         return 0;
1995
1996                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
1997                         DBusMessageIter sub;
1998
1999                         dbus_message_iter_recurse(iter, &sub);
2000                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2001                                 ExecStatusInfo info;
2002
2003                                 zero(info);
2004                                 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2005                                         char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2006                                         char *t;
2007
2008                                         t = strv_join(info.argv, " ");
2009
2010                                         printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2011                                                name,
2012                                                strna(info.path),
2013                                                strna(t),
2014                                                yes_no(info.ignore),
2015                                                strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2016                                                strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2017                                                (unsigned) info. pid,
2018                                                sigchld_code_to_string(info.code),
2019                                                info.status,
2020                                                info.code == CLD_EXITED ? "" : "/",
2021                                                strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2022
2023                                         free(t);
2024                                 }
2025
2026                                 free(info.path);
2027                                 strv_free(info.argv);
2028
2029                                 dbus_message_iter_next(&sub);
2030                         }
2031
2032                         return 0;
2033                 }
2034
2035                 break;
2036         }
2037
2038         if (arg_all)
2039                 printf("%s=[unprintable]\n", name);
2040
2041         return 0;
2042 }
2043
2044 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2045         DBusMessage *m = NULL, *reply = NULL;
2046         const char *interface = "";
2047         int r;
2048         DBusError error;
2049         DBusMessageIter iter, sub, sub2, sub3;
2050         UnitStatusInfo info;
2051         ExecStatusInfo *p;
2052
2053         assert(bus);
2054         assert(path);
2055         assert(new_line);
2056
2057         zero(info);
2058         dbus_error_init(&error);
2059
2060         if (!(m = dbus_message_new_method_call(
2061                               "org.freedesktop.systemd1",
2062                               path,
2063                               "org.freedesktop.DBus.Properties",
2064                               "GetAll"))) {
2065                 log_error("Could not allocate message.");
2066                 r = -ENOMEM;
2067                 goto finish;
2068         }
2069
2070         if (!dbus_message_append_args(m,
2071                                       DBUS_TYPE_STRING, &interface,
2072                                       DBUS_TYPE_INVALID)) {
2073                 log_error("Could not append arguments to message.");
2074                 r = -ENOMEM;
2075                 goto finish;
2076         }
2077
2078         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2079                 log_error("Failed to issue method call: %s", error.message);
2080                 r = -EIO;
2081                 goto finish;
2082         }
2083
2084         if (!dbus_message_iter_init(reply, &iter) ||
2085             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2086             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY)  {
2087                 log_error("Failed to parse reply.");
2088                 r = -EIO;
2089                 goto finish;
2090         }
2091
2092         dbus_message_iter_recurse(&iter, &sub);
2093
2094         if (*new_line)
2095                 printf("\n");
2096
2097         *new_line = true;
2098
2099         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2100                 const char *name;
2101
2102                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2103                         log_error("Failed to parse reply.");
2104                         r = -EIO;
2105                         goto finish;
2106                 }
2107
2108                 dbus_message_iter_recurse(&sub, &sub2);
2109
2110                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2111                         log_error("Failed to parse reply.");
2112                         r = -EIO;
2113                         goto finish;
2114                 }
2115
2116                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT)  {
2117                         log_error("Failed to parse reply.");
2118                         r = -EIO;
2119                         goto finish;
2120                 }
2121
2122                 dbus_message_iter_recurse(&sub2, &sub3);
2123
2124                 if (show_properties)
2125                         r = print_property(name, &sub3);
2126                 else
2127                         r = status_property(name, &sub3, &info);
2128
2129                 if (r < 0) {
2130                         log_error("Failed to parse reply.");
2131                         r = -EIO;
2132                         goto finish;
2133                 }
2134
2135                 dbus_message_iter_next(&sub);
2136         }
2137
2138         if (!show_properties)
2139                 print_status_info(&info);
2140
2141         while ((p = info.exec)) {
2142                 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2143                 exec_status_info_free(p);
2144         }
2145
2146         r = 0;
2147
2148 finish:
2149         if (m)
2150                 dbus_message_unref(m);
2151
2152         if (reply)
2153                 dbus_message_unref(reply);
2154
2155         dbus_error_free(&error);
2156
2157         return r;
2158 }
2159
2160 static int show(DBusConnection *bus, char **args, unsigned n) {
2161         DBusMessage *m = NULL, *reply = NULL;
2162         int r;
2163         DBusError error;
2164         unsigned i;
2165         bool show_properties, new_line = false;
2166
2167         assert(bus);
2168         assert(args);
2169
2170         dbus_error_init(&error);
2171
2172         show_properties = !streq(args[0], "status");
2173
2174         if (show_properties && n <= 1) {
2175                 /* If not argument is specified inspect the manager
2176                  * itself */
2177
2178                 r = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2179                 goto finish;
2180         }
2181
2182         for (i = 1; i < n; i++) {
2183                 const char *path = NULL;
2184                 uint32_t id;
2185
2186                 if (safe_atou32(args[i], &id) < 0) {
2187
2188                         /* Interpret as unit name */
2189
2190                         if (!(m = dbus_message_new_method_call(
2191                                               "org.freedesktop.systemd1",
2192                                               "/org/freedesktop/systemd1",
2193                                               "org.freedesktop.systemd1.Manager",
2194                                               "LoadUnit"))) {
2195                                 log_error("Could not allocate message.");
2196                                 r = -ENOMEM;
2197                                 goto finish;
2198                         }
2199
2200                         if (!dbus_message_append_args(m,
2201                                                       DBUS_TYPE_STRING, &args[i],
2202                                                       DBUS_TYPE_INVALID)) {
2203                                 log_error("Could not append arguments to message.");
2204                                 r = -ENOMEM;
2205                                 goto finish;
2206                         }
2207
2208                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2209
2210                                 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2211                                         log_error("Failed to issue method call: %s", error.message);
2212                                         r = -EIO;
2213                                         goto finish;
2214                                 }
2215
2216                                 dbus_error_free(&error);
2217
2218                                 dbus_message_unref(m);
2219                                 if (!(m = dbus_message_new_method_call(
2220                                                       "org.freedesktop.systemd1",
2221                                                       "/org/freedesktop/systemd1",
2222                                                       "org.freedesktop.systemd1.Manager",
2223                                                       "GetUnit"))) {
2224                                         log_error("Could not allocate message.");
2225                                         r = -ENOMEM;
2226                                         goto finish;
2227                                 }
2228
2229                                 if (!dbus_message_append_args(m,
2230                                                               DBUS_TYPE_STRING, &args[i],
2231                                                               DBUS_TYPE_INVALID)) {
2232                                         log_error("Could not append arguments to message.");
2233                                         r = -ENOMEM;
2234                                         goto finish;
2235                                 }
2236
2237                                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2238                                         log_error("Failed to issue method call: %s", error.message);
2239                                         r = -EIO;
2240                                         goto finish;
2241                                 }
2242                         }
2243
2244                 } else if (show_properties) {
2245
2246                         /* Interpret as job id */
2247
2248                         if (!(m = dbus_message_new_method_call(
2249                                               "org.freedesktop.systemd1",
2250                                               "/org/freedesktop/systemd1",
2251                                               "org.freedesktop.systemd1.Manager",
2252                                               "GetJob"))) {
2253                                 log_error("Could not allocate message.");
2254                                 r = -ENOMEM;
2255                                 goto finish;
2256                         }
2257
2258                         if (!dbus_message_append_args(m,
2259                                                       DBUS_TYPE_UINT32, &id,
2260                                                       DBUS_TYPE_INVALID)) {
2261                                 log_error("Could not append arguments to message.");
2262                                 r = -ENOMEM;
2263                                 goto finish;
2264                         }
2265
2266                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2267                                 log_error("Failed to issue method call: %s", error.message);
2268                                 r = -EIO;
2269                                 goto finish;
2270                         }
2271                 } else {
2272
2273                         /* Interpret as PID */
2274
2275                         if (!(m = dbus_message_new_method_call(
2276                                               "org.freedesktop.systemd1",
2277                                               "/org/freedesktop/systemd1",
2278                                               "org.freedesktop.systemd1.Manager",
2279                                               "GetUnitByPID"))) {
2280                                 log_error("Could not allocate message.");
2281                                 r = -ENOMEM;
2282                                 goto finish;
2283                         }
2284
2285                         if (!dbus_message_append_args(m,
2286                                                       DBUS_TYPE_UINT32, &id,
2287                                                       DBUS_TYPE_INVALID)) {
2288                                 log_error("Could not append arguments to message.");
2289                                 r = -ENOMEM;
2290                                 goto finish;
2291                         }
2292
2293                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2294                                 log_error("Failed to issue method call: %s", error.message);
2295                                 r = -EIO;
2296                                 goto finish;
2297                         }
2298                 }
2299
2300                 if (!dbus_message_get_args(reply, &error,
2301                                            DBUS_TYPE_OBJECT_PATH, &path,
2302                                            DBUS_TYPE_INVALID)) {
2303                         log_error("Failed to parse reply: %s", error.message);
2304                         r = -EIO;
2305                         goto finish;
2306                 }
2307
2308                 if ((r = show_one(bus, path, show_properties, &new_line)) < 0)
2309                         goto finish;
2310
2311                 dbus_message_unref(m);
2312                 dbus_message_unref(reply);
2313                 m = reply = NULL;
2314         }
2315
2316         r = 0;
2317
2318 finish:
2319         if (m)
2320                 dbus_message_unref(m);
2321
2322         if (reply)
2323                 dbus_message_unref(reply);
2324
2325         dbus_error_free(&error);
2326
2327         return r;
2328 }
2329
2330 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2331         DBusError error;
2332         DBusMessage *m = NULL, *reply = NULL;
2333
2334         assert(connection);
2335         assert(message);
2336
2337         dbus_error_init(&error);
2338
2339         log_debug("Got D-Bus request: %s.%s() on %s",
2340                   dbus_message_get_interface(message),
2341                   dbus_message_get_member(message),
2342                   dbus_message_get_path(message));
2343
2344         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2345                 log_error("Warning! D-Bus connection terminated.");
2346                 dbus_connection_close(connection);
2347
2348         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2349                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2350                 const char *id, *path;
2351
2352                 if (!dbus_message_get_args(message, &error,
2353                                            DBUS_TYPE_STRING, &id,
2354                                            DBUS_TYPE_OBJECT_PATH, &path,
2355                                            DBUS_TYPE_INVALID))
2356                         log_error("Failed to parse message: %s", error.message);
2357                 else if (streq(dbus_message_get_member(message), "UnitNew"))
2358                         printf("Unit %s added.\n", id);
2359                 else
2360                         printf("Unit %s removed.\n", id);
2361
2362         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2363                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2364                 uint32_t id;
2365                 const char *path;
2366
2367                 if (!dbus_message_get_args(message, &error,
2368                                            DBUS_TYPE_UINT32, &id,
2369                                            DBUS_TYPE_OBJECT_PATH, &path,
2370                                            DBUS_TYPE_INVALID))
2371                         log_error("Failed to parse message: %s", error.message);
2372                 else if (streq(dbus_message_get_member(message), "JobNew"))
2373                         printf("Job %u added.\n", id);
2374                 else
2375                         printf("Job %u removed.\n", id);
2376
2377
2378         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Unit", "Changed") ||
2379                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Job", "Changed")) {
2380
2381                 const char *path, *interface, *property = "Id";
2382                 DBusMessageIter iter, sub;
2383
2384                 path = dbus_message_get_path(message);
2385                 interface = dbus_message_get_interface(message);
2386
2387                 if (!(m = dbus_message_new_method_call(
2388                               "org.freedesktop.systemd1",
2389                               path,
2390                               "org.freedesktop.DBus.Properties",
2391                               "Get"))) {
2392                         log_error("Could not allocate message.");
2393                         goto oom;
2394                 }
2395
2396                 if (!dbus_message_append_args(m,
2397                                               DBUS_TYPE_STRING, &interface,
2398                                               DBUS_TYPE_STRING, &property,
2399                                               DBUS_TYPE_INVALID)) {
2400                         log_error("Could not append arguments to message.");
2401                         goto finish;
2402                 }
2403
2404                 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2405                         log_error("Failed to issue method call: %s", error.message);
2406                         goto finish;
2407                 }
2408
2409                 if (!dbus_message_iter_init(reply, &iter) ||
2410                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
2411                         log_error("Failed to parse reply.");
2412                         goto finish;
2413                 }
2414
2415                 dbus_message_iter_recurse(&iter, &sub);
2416
2417                 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2418                         const char *id;
2419
2420                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
2421                                 log_error("Failed to parse reply.");
2422                                 goto finish;
2423                         }
2424
2425                         dbus_message_iter_get_basic(&sub, &id);
2426                         printf("Unit %s changed.\n", id);
2427                 } else {
2428                         uint32_t id;
2429
2430                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32)  {
2431                                 log_error("Failed to parse reply.");
2432                                 goto finish;
2433                         }
2434
2435                         dbus_message_iter_get_basic(&sub, &id);
2436                         printf("Job %u changed.\n", id);
2437                 }
2438         }
2439
2440 finish:
2441         if (m)
2442                 dbus_message_unref(m);
2443
2444         if (reply)
2445                 dbus_message_unref(reply);
2446
2447         dbus_error_free(&error);
2448         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2449
2450 oom:
2451         if (m)
2452                 dbus_message_unref(m);
2453
2454         if (reply)
2455                 dbus_message_unref(reply);
2456
2457         dbus_error_free(&error);
2458         return DBUS_HANDLER_RESULT_NEED_MEMORY;
2459 }
2460
2461 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2462         DBusMessage *m = NULL, *reply = NULL;
2463         DBusError error;
2464         int r;
2465
2466         dbus_error_init(&error);
2467
2468         if (!private_bus) {
2469                 dbus_bus_add_match(bus,
2470                                    "type='signal',"
2471                                    "sender='org.freedesktop.systemd1',"
2472                                    "interface='org.freedesktop.systemd1.Manager',"
2473                                    "path='/org/freedesktop/systemd1'",
2474                                    &error);
2475
2476                 if (dbus_error_is_set(&error)) {
2477                         log_error("Failed to add match: %s", error.message);
2478                         r = -EIO;
2479                         goto finish;
2480                 }
2481
2482                 dbus_bus_add_match(bus,
2483                                    "type='signal',"
2484                                    "sender='org.freedesktop.systemd1',"
2485                                    "interface='org.freedesktop.systemd1.Unit',"
2486                                    "member='Changed'",
2487                                    &error);
2488
2489                 if (dbus_error_is_set(&error)) {
2490                         log_error("Failed to add match: %s", error.message);
2491                         r = -EIO;
2492                         goto finish;
2493                 }
2494
2495                 dbus_bus_add_match(bus,
2496                                    "type='signal',"
2497                                    "sender='org.freedesktop.systemd1',"
2498                                    "interface='org.freedesktop.systemd1.Job',"
2499                                    "member='Changed'",
2500                                    &error);
2501
2502                 if (dbus_error_is_set(&error)) {
2503                         log_error("Failed to add match: %s", error.message);
2504                         r = -EIO;
2505                         goto finish;
2506                 }
2507         }
2508
2509         if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2510                 log_error("Failed to add filter.");
2511                 r = -ENOMEM;
2512                 goto finish;
2513         }
2514
2515         if (!(m = dbus_message_new_method_call(
2516                               "org.freedesktop.systemd1",
2517                               "/org/freedesktop/systemd1",
2518                               "org.freedesktop.systemd1.Manager",
2519                               "Subscribe"))) {
2520                 log_error("Could not allocate message.");
2521                 r = -ENOMEM;
2522                 goto finish;
2523         }
2524
2525         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2526                 log_error("Failed to issue method call: %s", error.message);
2527                 r = -EIO;
2528                 goto finish;
2529         }
2530
2531         while (dbus_connection_read_write_dispatch(bus, -1))
2532                 ;
2533
2534         r = 0;
2535
2536 finish:
2537
2538         /* This is slightly dirty, since we don't undo the filter or the matches. */
2539
2540         if (m)
2541                 dbus_message_unref(m);
2542
2543         if (reply)
2544                 dbus_message_unref(reply);
2545
2546         dbus_error_free(&error);
2547
2548         return r;
2549 }
2550
2551 static int dump(DBusConnection *bus, char **args, unsigned n) {
2552         DBusMessage *m = NULL, *reply = NULL;
2553         DBusError error;
2554         int r;
2555         const char *text;
2556
2557         dbus_error_init(&error);
2558
2559         if (!(m = dbus_message_new_method_call(
2560                               "org.freedesktop.systemd1",
2561                               "/org/freedesktop/systemd1",
2562                               "org.freedesktop.systemd1.Manager",
2563                               "Dump"))) {
2564                 log_error("Could not allocate message.");
2565                 return -ENOMEM;
2566         }
2567
2568         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2569                 log_error("Failed to issue method call: %s", error.message);
2570                 r = -EIO;
2571                 goto finish;
2572         }
2573
2574         if (!dbus_message_get_args(reply, &error,
2575                                    DBUS_TYPE_STRING, &text,
2576                                    DBUS_TYPE_INVALID)) {
2577                 log_error("Failed to parse reply: %s", error.message);
2578                 r = -EIO;
2579                 goto finish;
2580         }
2581
2582         fputs(text, stdout);
2583
2584         r = 0;
2585
2586 finish:
2587         if (m)
2588                 dbus_message_unref(m);
2589
2590         if (reply)
2591                 dbus_message_unref(reply);
2592
2593         dbus_error_free(&error);
2594
2595         return r;
2596 }
2597
2598 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2599         DBusMessage *m = NULL, *reply = NULL;
2600         DBusError error;
2601         int r;
2602         const char *name = "", *path, *id;
2603         dbus_bool_t cleanup = FALSE;
2604         DBusMessageIter iter, sub;
2605         const char
2606                 *interface = "org.freedesktop.systemd1.Unit",
2607                 *property = "Id";
2608
2609         dbus_error_init(&error);
2610
2611         if (!(m = dbus_message_new_method_call(
2612                               "org.freedesktop.systemd1",
2613                               "/org/freedesktop/systemd1",
2614                               "org.freedesktop.systemd1.Manager",
2615                               "CreateSnapshot"))) {
2616                 log_error("Could not allocate message.");
2617                 return -ENOMEM;
2618         }
2619
2620         if (n > 1)
2621                 name = args[1];
2622
2623         if (!dbus_message_append_args(m,
2624                                       DBUS_TYPE_STRING, &name,
2625                                       DBUS_TYPE_BOOLEAN, &cleanup,
2626                                       DBUS_TYPE_INVALID)) {
2627                 log_error("Could not append arguments to message.");
2628                 r = -ENOMEM;
2629                 goto finish;
2630         }
2631
2632         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2633                 log_error("Failed to issue method call: %s", error.message);
2634                 r = -EIO;
2635                 goto finish;
2636         }
2637
2638         if (!dbus_message_get_args(reply, &error,
2639                                    DBUS_TYPE_OBJECT_PATH, &path,
2640                                    DBUS_TYPE_INVALID)) {
2641                 log_error("Failed to parse reply: %s", error.message);
2642                 r = -EIO;
2643                 goto finish;
2644         }
2645
2646         dbus_message_unref(m);
2647         if (!(m = dbus_message_new_method_call(
2648                               "org.freedesktop.systemd1",
2649                               path,
2650                               "org.freedesktop.DBus.Properties",
2651                               "Get"))) {
2652                 log_error("Could not allocate message.");
2653                 return -ENOMEM;
2654         }
2655
2656         if (!dbus_message_append_args(m,
2657                                       DBUS_TYPE_STRING, &interface,
2658                                       DBUS_TYPE_STRING, &property,
2659                                       DBUS_TYPE_INVALID)) {
2660                 log_error("Could not append arguments to message.");
2661                 r = -ENOMEM;
2662                 goto finish;
2663         }
2664
2665         dbus_message_unref(reply);
2666         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2667                 log_error("Failed to issue method call: %s", error.message);
2668                 r = -EIO;
2669                 goto finish;
2670         }
2671
2672         if (!dbus_message_iter_init(reply, &iter) ||
2673             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
2674                 log_error("Failed to parse reply.");
2675                 r = -EIO;
2676                 goto finish;
2677         }
2678
2679         dbus_message_iter_recurse(&iter, &sub);
2680
2681         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
2682                 log_error("Failed to parse reply.");
2683                 r = -EIO;
2684                 goto finish;
2685         }
2686
2687         dbus_message_iter_get_basic(&sub, &id);
2688
2689         if (!arg_quiet)
2690                 puts(id);
2691         r = 0;
2692
2693 finish:
2694         if (m)
2695                 dbus_message_unref(m);
2696
2697         if (reply)
2698                 dbus_message_unref(reply);
2699
2700         dbus_error_free(&error);
2701
2702         return r;
2703 }
2704
2705 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2706         DBusMessage *m = NULL, *reply = NULL;
2707         int r;
2708         DBusError error;
2709         unsigned i;
2710
2711         assert(bus);
2712         assert(args);
2713
2714         dbus_error_init(&error);
2715
2716         for (i = 1; i < n; i++) {
2717                 const char *path = NULL;
2718
2719                 if (!(m = dbus_message_new_method_call(
2720                                       "org.freedesktop.systemd1",
2721                                       "/org/freedesktop/systemd1",
2722                                       "org.freedesktop.systemd1.Manager",
2723                                       "GetUnit"))) {
2724                         log_error("Could not allocate message.");
2725                         r = -ENOMEM;
2726                         goto finish;
2727                 }
2728
2729                 if (!dbus_message_append_args(m,
2730                                               DBUS_TYPE_STRING, &args[i],
2731                                               DBUS_TYPE_INVALID)) {
2732                         log_error("Could not append arguments to message.");
2733                         r = -ENOMEM;
2734                         goto finish;
2735                 }
2736
2737                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2738                         log_error("Failed to issue method call: %s", error.message);
2739                         r = -EIO;
2740                         goto finish;
2741                 }
2742
2743                 if (!dbus_message_get_args(reply, &error,
2744                                            DBUS_TYPE_OBJECT_PATH, &path,
2745                                            DBUS_TYPE_INVALID)) {
2746                         log_error("Failed to parse reply: %s", error.message);
2747                         r = -EIO;
2748                         goto finish;
2749                 }
2750
2751                 dbus_message_unref(m);
2752                 if (!(m = dbus_message_new_method_call(
2753                                       "org.freedesktop.systemd1",
2754                                       path,
2755                                       "org.freedesktop.systemd1.Snapshot",
2756                                       "Remove"))) {
2757                         log_error("Could not allocate message.");
2758                         r = -ENOMEM;
2759                         goto finish;
2760                 }
2761
2762                 dbus_message_unref(reply);
2763                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2764                         log_error("Failed to issue method call: %s", error.message);
2765                         r = -EIO;
2766                         goto finish;
2767                 }
2768
2769                 dbus_message_unref(m);
2770                 dbus_message_unref(reply);
2771                 m = reply = NULL;
2772         }
2773
2774         r = 0;
2775
2776 finish:
2777         if (m)
2778                 dbus_message_unref(m);
2779
2780         if (reply)
2781                 dbus_message_unref(reply);
2782
2783         dbus_error_free(&error);
2784
2785         return r;
2786 }
2787
2788 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2789         DBusMessage *m = NULL, *reply = NULL;
2790         DBusError error;
2791         int r;
2792         const char *method;
2793
2794         dbus_error_init(&error);
2795
2796         if (arg_action == ACTION_RELOAD)
2797                 method = "Reload";
2798         else if (arg_action == ACTION_REEXEC)
2799                 method = "Reexecute";
2800         else {
2801                 assert(arg_action == ACTION_SYSTEMCTL);
2802
2803                 method =
2804                         streq(args[0], "clear-jobs")        ||
2805                         streq(args[0], "cancel")            ? "ClearJobs" :
2806                         streq(args[0], "daemon-reexec")     ? "Reexecute" :
2807                         streq(args[0], "reset-maintenance") ? "ResetMaintenance" :
2808                         streq(args[0], "daemon-exit")       ? "Exit" :
2809                                                               "Reload";
2810         }
2811
2812         if (!(m = dbus_message_new_method_call(
2813                               "org.freedesktop.systemd1",
2814                               "/org/freedesktop/systemd1",
2815                               "org.freedesktop.systemd1.Manager",
2816                               method))) {
2817                 log_error("Could not allocate message.");
2818                 return -ENOMEM;
2819         }
2820
2821         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2822
2823                 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
2824                         /* There's always a fallback possible for
2825                          * legacy actions. */
2826                         r = 0;
2827                         goto finish;
2828                 }
2829
2830                 log_error("Failed to issue method call: %s", error.message);
2831                 r = -EIO;
2832                 goto finish;
2833         }
2834
2835         r = 1;
2836
2837 finish:
2838         if (m)
2839                 dbus_message_unref(m);
2840
2841         if (reply)
2842                 dbus_message_unref(reply);
2843
2844         dbus_error_free(&error);
2845
2846         return r;
2847 }
2848
2849 static int reset_maintenance(DBusConnection *bus, char **args, unsigned n) {
2850         DBusMessage *m = NULL, *reply = NULL;
2851         unsigned i;
2852         int r;
2853         DBusError error;
2854
2855         assert(bus);
2856         dbus_error_init(&error);
2857
2858         if (n <= 1)
2859                 return daemon_reload(bus, args, n);
2860
2861         for (i = 1; i < n; i++) {
2862
2863                 if (!(m = dbus_message_new_method_call(
2864                                       "org.freedesktop.systemd1",
2865                                       "/org/freedesktop/systemd1",
2866                                       "org.freedesktop.systemd1.Manager",
2867                                       "ResetMaintenanceUnit"))) {
2868                         log_error("Could not allocate message.");
2869                         r = -ENOMEM;
2870                         goto finish;
2871                 }
2872
2873                 if (!dbus_message_append_args(m,
2874                                               DBUS_TYPE_STRING, args + i,
2875                                               DBUS_TYPE_INVALID)) {
2876                         log_error("Could not append arguments to message.");
2877                         r = -ENOMEM;
2878                         goto finish;
2879                 }
2880
2881                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2882                         log_error("Failed to issue method call: %s", error.message);
2883                         r = -EIO;
2884                         goto finish;
2885                 }
2886
2887                 dbus_message_unref(m);
2888                 dbus_message_unref(reply);
2889                 m = reply = NULL;
2890         }
2891
2892         r = 0;
2893
2894 finish:
2895         if (m)
2896                 dbus_message_unref(m);
2897
2898         if (reply)
2899                 dbus_message_unref(reply);
2900
2901         dbus_error_free(&error);
2902
2903         return r;
2904 }
2905
2906 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
2907         DBusMessage *m = NULL, *reply = NULL;
2908         DBusError error;
2909         DBusMessageIter iter, sub, sub2;
2910         int r;
2911         const char
2912                 *interface = "org.freedesktop.systemd1.Manager",
2913                 *property = "Environment";
2914
2915         dbus_error_init(&error);
2916
2917         if (!(m = dbus_message_new_method_call(
2918                               "org.freedesktop.systemd1",
2919                               "/org/freedesktop/systemd1",
2920                               "org.freedesktop.DBus.Properties",
2921                               "Get"))) {
2922                 log_error("Could not allocate message.");
2923                 return -ENOMEM;
2924         }
2925
2926         if (!dbus_message_append_args(m,
2927                                       DBUS_TYPE_STRING, &interface,
2928                                       DBUS_TYPE_STRING, &property,
2929                                       DBUS_TYPE_INVALID)) {
2930                 log_error("Could not append arguments to message.");
2931                 r = -ENOMEM;
2932                 goto finish;
2933         }
2934
2935         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2936                 log_error("Failed to issue method call: %s", error.message);
2937                 r = -EIO;
2938                 goto finish;
2939         }
2940
2941         if (!dbus_message_iter_init(reply, &iter) ||
2942             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
2943                 log_error("Failed to parse reply.");
2944                 r = -EIO;
2945                 goto finish;
2946         }
2947
2948         dbus_message_iter_recurse(&iter, &sub);
2949
2950         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
2951             dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING)  {
2952                 log_error("Failed to parse reply.");
2953                 r = -EIO;
2954                 goto finish;
2955         }
2956
2957         dbus_message_iter_recurse(&sub, &sub2);
2958
2959         while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
2960                 const char *text;
2961
2962                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
2963                         log_error("Failed to parse reply.");
2964                         r = -EIO;
2965                         goto finish;
2966                 }
2967
2968                 dbus_message_iter_get_basic(&sub2, &text);
2969                 printf("%s\n", text);
2970
2971                 dbus_message_iter_next(&sub2);
2972         }
2973
2974         r = 0;
2975
2976 finish:
2977         if (m)
2978                 dbus_message_unref(m);
2979
2980         if (reply)
2981                 dbus_message_unref(reply);
2982
2983         dbus_error_free(&error);
2984
2985         return r;
2986 }
2987
2988 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
2989         DBusMessage *m = NULL, *reply = NULL;
2990         DBusError error;
2991         int r;
2992         const char *method;
2993         DBusMessageIter iter, sub;
2994         unsigned i;
2995
2996         dbus_error_init(&error);
2997
2998         method = streq(args[0], "set-environment")
2999                 ? "SetEnvironment"
3000                 : "UnsetEnvironment";
3001
3002         if (!(m = dbus_message_new_method_call(
3003                               "org.freedesktop.systemd1",
3004                               "/org/freedesktop/systemd1",
3005                               "org.freedesktop.systemd1.Manager",
3006                               method))) {
3007
3008                 log_error("Could not allocate message.");
3009                 return -ENOMEM;
3010         }
3011
3012         dbus_message_iter_init_append(m, &iter);
3013
3014         if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3015                 log_error("Could not append arguments to message.");
3016                 r = -ENOMEM;
3017                 goto finish;
3018         }
3019
3020         for (i = 1; i < n; i++)
3021                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3022                         log_error("Could not append arguments to message.");
3023                         r = -ENOMEM;
3024                         goto finish;
3025                 }
3026
3027         if (!dbus_message_iter_close_container(&iter, &sub)) {
3028                 log_error("Could not append arguments to message.");
3029                 r = -ENOMEM;
3030                 goto finish;
3031         }
3032
3033         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3034                 log_error("Failed to issue method call: %s", error.message);
3035                 r = -EIO;
3036                 goto finish;
3037         }
3038
3039         r = 0;
3040
3041 finish:
3042         if (m)
3043                 dbus_message_unref(m);
3044
3045         if (reply)
3046                 dbus_message_unref(reply);
3047
3048         dbus_error_free(&error);
3049
3050         return r;
3051 }
3052
3053 typedef struct {
3054         char *name;
3055         char *path;
3056
3057         char **aliases;
3058         char **wanted_by;
3059 } InstallInfo;
3060
3061 static Hashmap *will_install = NULL, *have_installed = NULL;
3062 static Set *remove_symlinks_to = NULL;
3063
3064 static void install_info_free(InstallInfo *i) {
3065         assert(i);
3066
3067         free(i->name);
3068         free(i->path);
3069         strv_free(i->aliases);
3070         strv_free(i->wanted_by);
3071         free(i);
3072 }
3073
3074 static void install_info_hashmap_free(Hashmap *m) {
3075         InstallInfo *i;
3076
3077         while ((i = hashmap_steal_first(m)))
3078                 install_info_free(i);
3079
3080         hashmap_free(m);
3081 }
3082
3083 static bool unit_name_valid(const char *name) {
3084
3085         /* This is a minimal version of unit_name_valid() from
3086          * unit-name.c */
3087
3088         if (!*name)
3089                 return false;
3090
3091         if (ignore_file(name))
3092                 return false;
3093
3094         return true;
3095 }
3096
3097 static int install_info_add(const char *name) {
3098         InstallInfo *i;
3099         int r;
3100
3101         assert(will_install);
3102
3103         if (!unit_name_valid(name))
3104                 return -EINVAL;
3105
3106         if (hashmap_get(have_installed, name) ||
3107             hashmap_get(will_install, name))
3108                 return 0;
3109
3110         if (!(i = new0(InstallInfo, 1))) {
3111                 r = -ENOMEM;
3112                 goto fail;
3113         }
3114
3115         if (!(i->name = strdup(name))) {
3116                 r = -ENOMEM;
3117                 goto fail;
3118         }
3119
3120         if ((r = hashmap_put(will_install, i->name, i)) < 0)
3121                 goto fail;
3122
3123         return 0;
3124
3125 fail:
3126         if (i)
3127                 install_info_free(i);
3128
3129         return r;
3130 }
3131
3132 static int config_parse_also(
3133                 const char *filename,
3134                 unsigned line,
3135                 const char *section,
3136                 const char *lvalue,
3137                 const char *rvalue,
3138                 void *data,
3139                 void *userdata) {
3140
3141         char *w;
3142         size_t l;
3143         char *state;
3144
3145         assert(filename);
3146         assert(lvalue);
3147         assert(rvalue);
3148
3149         FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3150                 char *n;
3151                 int r;
3152
3153                 if (!(n = strndup(w, l)))
3154                         return -ENOMEM;
3155
3156                 r = install_info_add(n);
3157                 free(n);
3158
3159                 if (r < 0)
3160                         return r;
3161         }
3162
3163         return 0;
3164 }
3165
3166 static int mark_symlink_for_removal(const char *p) {
3167         char *n;
3168         int r;
3169
3170         assert(p);
3171         assert(path_is_absolute(p));
3172
3173         if (!remove_symlinks_to)
3174                 return 0;
3175
3176         if (!(n = strdup(p)))
3177                 return -ENOMEM;
3178
3179         path_kill_slashes(n);
3180
3181         if ((r = set_put(remove_symlinks_to, n)) < 0) {
3182                 free(n);
3183                 return r == -EEXIST ? 0 : r;
3184         }
3185
3186         return 0;
3187 }
3188
3189 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3190         int r = 0;
3191         DIR *d;
3192         struct dirent *de;
3193
3194         assert(fd >= 0);
3195         assert(root);
3196         assert(deleted);
3197
3198         if (!(d = fdopendir(fd))) {
3199                 close_nointr_nofail(fd);
3200                 return -errno;
3201         }
3202
3203         rewinddir(d);
3204
3205         while ((de = readdir(d))) {
3206                 bool is_dir = false, is_link = false;
3207
3208                 if (ignore_file(de->d_name))
3209                         continue;
3210
3211                 if (de->d_type == DT_LNK)
3212                         is_link = true;
3213                 else if (de->d_type == DT_DIR)
3214                         is_dir = true;
3215                 else if (de->d_type == DT_UNKNOWN) {
3216                         struct stat st;
3217
3218                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3219                                 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3220
3221                                 if (r == 0)
3222                                         r = -errno;
3223                                 continue;
3224                         }
3225
3226                         is_link = S_ISLNK(st.st_mode);
3227                         is_dir = S_ISDIR(st.st_mode);
3228                 } else
3229                         continue;
3230
3231                 if (is_dir) {
3232                         int nfd, q;
3233                         char *p;
3234
3235                         if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3236                                 log_error("Failed to open %s/%s: %m", root, de->d_name);
3237
3238                                 if (r == 0)
3239                                         r = -errno;
3240                                 continue;
3241                         }
3242
3243                         if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3244                                 log_error("Failed to allocate directory string.");
3245                                 close_nointr_nofail(nfd);
3246                                 r = -ENOMEM;
3247                                 break;
3248                         }
3249
3250                         /* This will close nfd, regardless whether it succeeds or not */
3251                         q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3252                         free(p);
3253
3254                         if (r == 0)
3255                                 r = q;
3256
3257                 } else if (is_link) {
3258                         char *p, *dest, *c;
3259                         int q;
3260
3261                         if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3262                                 log_error("Failed to allocate symlink string.");
3263                                 r = -ENOMEM;
3264                                 break;
3265                         }
3266
3267                         if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3268                                 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3269                                 free(p);
3270
3271                                 if (r == 0)
3272                                         r = q;
3273                                 continue;
3274                         }
3275
3276                         if ((c = canonicalize_file_name(dest))) {
3277                                 /* This might fail if the destination
3278                                  * is already removed */
3279
3280                                 free(dest);
3281                                 dest = c;
3282                         }
3283
3284                         path_kill_slashes(dest);
3285                         if (set_get(remove_symlinks_to, dest)) {
3286
3287                                 if (!arg_quiet)
3288                                         log_info("rm '%s'", p);
3289
3290                                 if (unlink(p) < 0) {
3291                                         log_error("Cannot unlink symlink %s: %m", p);
3292
3293                                         if (r == 0)
3294                                                 r = -errno;
3295                                 } else {
3296                                         rmdir_parents(p, config_path);
3297                                         path_kill_slashes(p);
3298
3299                                         if (!set_get(remove_symlinks_to, p)) {
3300
3301                                                 if ((r = mark_symlink_for_removal(p)) < 0) {
3302                                                         if (r == 0)
3303                                                                 r = q;
3304                                                 } else
3305                                                         *deleted = true;
3306                                         }
3307                                 }
3308                         }
3309
3310                         free(p);
3311                         free(dest);
3312                 }
3313         }
3314
3315         closedir(d);
3316
3317         return r;
3318 }
3319
3320 static int remove_marked_symlinks(const char *config_path) {
3321         int fd, r = 0;
3322         bool deleted;
3323
3324         assert(config_path);
3325
3326         if (set_size(remove_symlinks_to) <= 0)
3327                 return 0;
3328
3329         if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3330                 return -errno;
3331
3332         do {
3333                 int q, cfd;
3334                 deleted = false;
3335
3336                 if ((cfd = dup(fd)) < 0) {
3337                         r = -errno;
3338                         break;
3339                 }
3340
3341                 /* This takes possession of cfd and closes it */
3342                 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3343                         if (r == 0)
3344                                 r = q;
3345                 }
3346         } while (deleted);
3347
3348         close_nointr_nofail(fd);
3349
3350         return r;
3351 }
3352
3353 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3354         int r;
3355
3356         assert(old_path);
3357         assert(new_path);
3358         assert(verb);
3359
3360         if (streq(verb, "enable")) {
3361                 char *dest;
3362
3363                 mkdir_parents(new_path, 0755);
3364
3365                 if (symlink(old_path, new_path) >= 0) {
3366
3367                         if (!arg_quiet)
3368                                 log_info("ln -s '%s' '%s'", old_path, new_path);
3369
3370                         return 0;
3371                 }
3372
3373                 if (errno != EEXIST) {
3374                         log_error("Cannot link %s to %s: %m", old_path, new_path);
3375                         return -errno;
3376                 }
3377
3378                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3379
3380                         if (errno == EINVAL) {
3381                                 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3382                                 return -EEXIST;
3383                         }
3384
3385                         log_error("readlink() failed: %s", strerror(-r));
3386                         return r;
3387                 }
3388
3389                 if (streq(dest, old_path)) {
3390                         free(dest);
3391                         return 0;
3392                 }
3393
3394                 if (!arg_force) {
3395                         log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3396                         free(dest);
3397                         return -EEXIST;
3398                 }
3399
3400                 free(dest);
3401                 unlink(new_path);
3402
3403                 if (!arg_quiet)
3404                         log_info("ln -s '%s' '%s'", old_path, new_path);
3405
3406                 if (symlink(old_path, new_path) >= 0)
3407                         return 0;
3408
3409                 log_error("Cannot link %s to %s: %m", old_path, new_path);
3410                 return -errno;
3411
3412         } else if (streq(verb, "disable")) {
3413                 char *dest;
3414
3415                 if ((r = mark_symlink_for_removal(old_path)) < 0)
3416                         return r;
3417
3418                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3419                         if (errno == ENOENT)
3420                                 return 0;
3421
3422                         if (errno == EINVAL) {
3423                                 log_warning("File %s not a symlink, ignoring.", old_path);
3424                                 return 0;
3425                         }
3426
3427                         log_error("readlink() failed: %s", strerror(-r));
3428                         return r;
3429                 }
3430
3431                 if (!streq(dest, old_path)) {
3432                         log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3433                         free(dest);
3434                         return 0;
3435                 }
3436
3437                 free(dest);
3438
3439                 if ((r = mark_symlink_for_removal(new_path)) < 0)
3440                         return r;
3441
3442                 if (!arg_quiet)
3443                         log_info("rm '%s'", new_path);
3444
3445                 if (unlink(new_path) >= 0)
3446                         return 0;
3447
3448                 log_error("Cannot unlink %s: %m", new_path);
3449                 return -errno;
3450
3451         } else if (streq(verb, "is-enabled")) {
3452                 char *dest;
3453
3454                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3455
3456                         if (errno == ENOENT || errno == EINVAL)
3457                                 return 0;
3458
3459                         log_error("readlink() failed: %s", strerror(-r));
3460                         return r;
3461                 }
3462
3463                 if (streq(dest, old_path)) {
3464                         free(dest);
3465                         return 1;
3466                 }
3467
3468                 return 0;
3469         }
3470
3471         assert_not_reached("Unknown action.");
3472 }
3473
3474 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3475         char **s;
3476         char *alias_path = NULL;
3477         int r;
3478
3479         assert(verb);
3480         assert(i);
3481         assert(config_path);
3482
3483         STRV_FOREACH(s, i->aliases) {
3484
3485                 if (!unit_name_valid(*s)) {
3486                         log_error("Invalid name %s.", *s);
3487                         r = -EINVAL;
3488                         goto finish;
3489                 }
3490
3491                 free(alias_path);
3492                 if (!(alias_path = path_make_absolute(*s, config_path))) {
3493                         log_error("Out of memory");
3494                         r = -ENOMEM;
3495                         goto finish;
3496                 }
3497
3498                 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3499                         goto finish;
3500
3501                 if (streq(verb, "disable"))
3502                         rmdir_parents(alias_path, config_path);
3503         }
3504
3505         r = 0;
3506
3507 finish:
3508         free(alias_path);
3509
3510         return r;
3511 }
3512
3513 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3514         char **s;
3515         char *alias_path = NULL;
3516         int r;
3517
3518         assert(verb);
3519         assert(i);
3520         assert(config_path);
3521
3522         STRV_FOREACH(s, i->wanted_by) {
3523                 if (!unit_name_valid(*s)) {
3524                         log_error("Invalid name %s.", *s);
3525                         r = -EINVAL;
3526                         goto finish;
3527                 }
3528
3529                 free(alias_path);
3530                 alias_path = NULL;
3531
3532                 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3533                         log_error("Out of memory");
3534                         r = -ENOMEM;
3535                         goto finish;
3536                 }
3537
3538                 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3539                         goto finish;
3540
3541                 if (streq(verb, "disable"))
3542                         rmdir_parents(alias_path, config_path);
3543         }
3544
3545         r = 0;
3546
3547 finish:
3548         free(alias_path);
3549
3550         return r;
3551 }
3552
3553 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3554
3555         const ConfigItem items[] = {
3556                 { "Alias",    config_parse_strv, &i->aliases,   "Install" },
3557                 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3558                 { "Also",     config_parse_also, NULL,          "Install" },
3559
3560                 { NULL, NULL, NULL, NULL }
3561         };
3562
3563         char **p;
3564         char *filename = NULL;
3565         FILE *f = NULL;
3566         int r;
3567
3568         assert(paths);
3569         assert(i);
3570
3571         STRV_FOREACH(p, paths->unit_path) {
3572                 int fd;
3573
3574                 if (!(filename = path_make_absolute(i->name, *p))) {
3575                         log_error("Out of memory");
3576                         return -ENOMEM;
3577                 }
3578
3579                 /* Ensure that we don't follow symlinks */
3580                 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3581                         if ((f = fdopen(fd, "re")))
3582                                 break;
3583
3584                 if (errno == ELOOP) {
3585                         log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3586                         free(filename);
3587                         return -errno;
3588                 }
3589
3590                 if (errno != ENOENT) {
3591                         log_error("Failed to open %s: %m", filename);
3592                         free(filename);
3593                         return -errno;
3594                 }
3595
3596                 free(filename);
3597                 filename = NULL;
3598         }
3599
3600         if (!f) {
3601                 log_error("Couldn't find %s.", i->name);
3602                 return -ENOENT;
3603         }
3604
3605         i->path = filename;
3606
3607         if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3608                 fclose(f);
3609                 return r;
3610         }
3611
3612         fclose(f);
3613
3614         if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3615                 return r;
3616
3617         if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3618                 return r;
3619
3620         if ((r = mark_symlink_for_removal(filename)) < 0)
3621                 return r;
3622
3623         if ((r = remove_marked_symlinks(config_path)) < 0)
3624                 return r;
3625
3626         return 0;
3627 }
3628
3629 static char *get_config_path(void) {
3630
3631         if (arg_session && arg_global)
3632                 return strdup(SESSION_CONFIG_UNIT_PATH);
3633
3634         if (arg_session) {
3635                 char *p;
3636
3637                 if (session_config_home(&p) < 0)
3638                         return NULL;
3639
3640                 return p;
3641         }
3642
3643         return strdup(SYSTEM_CONFIG_UNIT_PATH);
3644 }
3645
3646 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3647         DBusError error;
3648         int r;
3649         LookupPaths paths;
3650         char *config_path = NULL;
3651         unsigned j;
3652         InstallInfo *i;
3653         const char *verb = args[0];
3654
3655         dbus_error_init(&error);
3656
3657         zero(paths);
3658         if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3659                 log_error("Failed to determine lookup paths: %s", strerror(-r));
3660                 goto finish;
3661         }
3662
3663         if (!(config_path = get_config_path())) {
3664                 log_error("Failed to determine config path");
3665                 r = -ENOMEM;
3666                 goto finish;
3667         }
3668
3669         will_install = hashmap_new(string_hash_func, string_compare_func);
3670         have_installed = hashmap_new(string_hash_func, string_compare_func);
3671
3672         if (!will_install || !have_installed) {