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