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