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