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